<template>
  <div class="white">
    <m-search :items="searchItems" v-model="searchValues" class="mb-3" @search="onSearch">
      <template #button>
        <m-button size="small" type="primary" plain icon="el-icon-finished" :loading="submitLoading" @click="onSave">提交待上传文件</m-button>
        <m-button size="small" type="warning" plain icon="el-icon-s-promotion" :loading="runLoading" @click="onRun">执行</m-button>
      </template>
    </m-search>
    <m-table
      :headers="headers"
      :items="items"
      v-loading="loading"
    >
      <!-- <template #header>
        <div class="header">
          <m-button size="small" type="primary" icon="el-icon-finished" :loading="submitLoading" @click="onSave">提交当前临时文件</m-button>
        </div>
      </template> -->
      <template #month>
        {{ queryValues.month }}
      </template>
      <template #file="{ row }">
        {{ filesValues[row.fileType]?.name }}
      </template>
      <template #actions="{ row }">
        <div class="d-flex">
          <el-upload
            class="mr-3"
            action="#"
            :limit="1"
            :show-file-list="false"
            :on-exceed="(files, fileList) => onExceed(files, fileList, row.fileType)"
            :http-request="e => onImport(e, row.fileType)"
            :on-remove="() => onRemove(row.fileType)"
          >
            <m-button slot="trigger" text type="primary">导入文件</m-button>
          </el-upload>
          <m-button text type="danger" v-show="filesValues[row.fileType]" @click="onDelete(row)">移除临时文件</m-button>
        </div>
      </template>
    </m-table>
  </div>
</template>

<script>
import {
  getSalaryCalculateTemplate,
  uploadSalaryCalculateFiles,
  getSalaryCalculateFiles
} from '@/api/salary'
import { dateFormat } from '@/utils/date'
export default {
  name: 'salaryCalculateUpload',
  data () {
    return {
      searchValues: {
        month: dateFormat('YYYY-mm', new Date()),
        category: null
      },
      queryValues: {},
      filesValues: {},
      categoryItems: [],
      historyItems: [],
      formItems: [],
      headers: [
        { label: '月份', prop: 'month', width: 100 },
        { label: '业务线', prop: 'category' },
        { label: '文件名', prop: 'fileName' },
        { label: '文件', prop: 'history' },
        { label: '待上传文件', prop: 'file' },
        { label: '操作', prop: 'actions' }
      ],
      loading: false,
      submitLoading: false,
      runLoading: false
    }
  },
  computed: {
    items () {
      const items = this.categoryItems.find(e => e.category === this.queryValues.category)?.files
      if (!items) {
        return []
      }
      return items.map(e => {
        return {
          ...e,
          history: this.historyItems.find(h => h.fileType === e.fileType)?.fileOriginalFilename
        }
      })
    },
    searchItems () {
      return [
        {
          label: '月份',
          prop: 'month',
          type: 'datePicker',
          options: {
            clearable: false,
            type: 'month',
            format: 'yyyy-MM',
            valueFormat: 'yyyy-MM',
            placeholder: '选择更新月份'
          }
        },
        {
          label: '业务线',
          prop: 'category',
          type: 'select',
          options: {
            clearable: false,
            placeholder: '选择业务线',
            items: this.categoryItems.map(e => {
              return {
                label: e.category,
                value: e.category
              }
            })
          }
        }
      ]
    }
  },
  // created () {
  //   this.onInit()
  // },
  methods: {
    async onInit () {
      try {
        const { data } = await getSalaryCalculateTemplate()
        this.categoryItems = data
        if (!data.length) {
          return
        }
        this.searchValues.category = data[0].category
        this.queryValues = { ...this.searchValues }
        this.onChange()
        this.onGetHistory()
      } catch (error) {
        this.$message.error(error)
      }
    },
    async onGetHistory () {
      try {
        this.loading = true
        const { data } = await getSalaryCalculateFiles(this.queryValues)
        this.historyItems = data
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    onSearch (query) {
      if (!query.category) {
        this.searchValues.category = this.categoryItems[0]?.category ?? null
      }
      this.queryValues = { ...this.searchValues }
      this.onGetHistory()
    },
    onChange () {
      const items = this.categoryItems.find(e => e.category === this.queryValues.category)?.files ?? []
      if (!items.length) {
        this.filesValues = {}
        return
      }
      this.filesValues = {
        ...items.reduce((res, v) => {
          res[v.fileType] = null
          return res
        }, {})
      }
    },
    onExceed (files, fileList, key) {
      this.filesValues[key] = files[0]
    },
    onImport (e, key) {
      this.filesValues[key] = e.file
    },
    onRemove (key) {
      this.filesValues[key] = null
    },
    onDelete (row) {
      this.filesValues[row.fileType] = null
    },
    async onSave () {
      if (Object.values(this.filesValues).every(e => e === null)) {
        this.$message.warning('请先上传文件')
        return
      }

      const h = this.$createElement
      this.$confirm(h('div', [
        h('p', undefined, '确定要更新文件吗？'),
        h('p', undefined, `更新月份：${this.queryValues.month}`),
        h('p', undefined, `更新物业线：${this.queryValues.category}`),
        h('p', { style: 'color: red' }, '上传文件后，将覆盖之前的文件，请谨慎操作！')
      ]), '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.submitLoading = true
        try {
          const formData = new FormData()
          Object.keys(this.filesValues).forEach(key => {
            if (!this.filesValues[key]) {
              return
            }
            formData.append('files', this.filesValues[key])
            formData.append('fileTypes', key)
          })
          formData.append('month', this.queryValues.month)
          formData.append('category', this.queryValues.category)
          await uploadSalaryCalculateFiles(formData)
          this.$message.success('保存成功')
          this.onGetHistory()
        } catch (error) {
          this.$message.error(error)
        } finally {
          this.submitLoading = false
        }
      }).catch(_ => {})
    },
    onRun () {}
  }
}
</script>

<style lang="scss" scoped>
.d-flex {
  display: flex;
}
.content {
  width: 50%;
  min-width: 500px;
  margin: 0 auto;
}
.buttons {
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep .el-upload-list__item .el-icon-close {
    display: inline-block;
    &::after {
      content: '移除';
    }
}
.header {
  display: flex;
  justify-content: flex-end;
}
</style>
