<template>
  <el-dialog
    center
    width="1024px"
    title="导入发票信息"
    :visible="innerVisible"
    :close-on-click-modal="false"
    @close="() => innerVisible = false"
  >
    <div v-if="tableData && tableData.length > 0" class="tr" style="padding: 10px 0 0 0">
      <el-button :size="'mini'" @click="() => tableData = []">取消</el-button>
      <el-button type="primary" :size="'mini'" @click="onSubmit">提交</el-button>
    </div>
    <div v-else>
      <upload-excel :on-success="onSuccess" :before-upload="beforeUpload" />
    </div>

    <ex-table
      :columns="columns"
      :table="table"
      :data="tableData"
      style="margin: 15px 0 0 0"
    />

    <div style="width:100%;display:flex;justify-content:flex-end;margin-top:10px">
      <el-button size="mini" type="primary">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import companyHelper from '@/mixins/companyHelper'
import { MessageBox } from 'element-ui'
import dayjs from 'dayjs'

import {
  helper,
  columns,
  getTableProperty,
  createErrorMessage,
  createFieldVerification,
  requsetFields,
  requiredFields,
} from './_template'

export default {
  mixins: [companyHelper],
  props: ['visible'],
  data() {
    return {
      columns,
      loading: false,
      tableData: [],
      table: {
        stripe: true,
        border: true,
        'max-height': '800px'
      }
    }
  },
  computed: {
    innerVisible: {
      get() {
        return this.visible
      },
      set(newVal) {
        this.$emit('update:visible', newVal)
      }
    }
  },
  methods: {
    validateTableHeader(header, importHeader) {
      let isHeaderOk = true
      if (header.length !== importHeader.length) return false
      for (const index in header) {
        const field = header[index]
        const importField = importHeader[index]
        if (field !== importField) {
          console.log(field, importField)
          isHeaderOk = false
          break
        }
      }

      return isHeaderOk
    },
    validateRequiredField(requiredFields) {
        const verification = createFieldVerification('发票申请编号、发票类型、发票号码、开票日期、税后金额不能为空')
      const fields = helper.fields(requiredFields)
      requiredFields[fields[0]].forEach((_, index) => {
        if (!helper.values(requiredFields, fields, index).every(value => value && String(value).trim() !== '')) {
          verification.isValid = false
          verification.notValidRows.push(index + 1)
        }
      })
      return verification
    },
    /* 处理不合法的值,提示错误信息,并返回最终的验证状态 **/
    handleNotValidFields(...validStates) {
      const messages = {}
      let isFinalValid = true

      for (const validState of validStates) {
        const { message, isValid, notValidRows } = validState
        if (isValid) continue
        isFinalValid = false

        notValidRows.forEach(row => {
          if (!messages[row]) messages[row] = []
          messages[row].push(message)
        })
      }

      return {
        isFinalValid,
        message: () => !isFinalValid && MessageBox({
          type: 'warning',
          title: '数据填写错误',
          dangerouslyUseHTMLString: true,
          message: createErrorMessage(messages),
          customClass: 'error-message__wrapper'
        })
      }
    },
    /* 校验导入的数据 **/
    validateFields(tableData = []) {
      const mapTableFieldToTableData = {}
      for (const tableItem of tableData) {
        const propertys = Object.keys(tableItem)
        for (const property of propertys) {
          const value = tableItem[property]
          if (!mapTableFieldToTableData[property]) mapTableFieldToTableData[property] = []
          mapTableFieldToTableData[property].push(value)
        }
      }

      return this.handleNotValidFields(
        this.validateRequiredField(helper.write(mapTableFieldToTableData, requiredFields))
      )
    },
    mapTemplateItemToTableItem(templateItem) {
      const tableItem = {}
      const templatePropertys = Object.keys(templateItem)
      templatePropertys.forEach(templateProperty => {
        const tableproperty = getTableProperty(templateProperty)
        tableItem[tableproperty] = templateItem[templateProperty]
      })
      return tableItem
    },
    onSuccess({ results: templateItems, header: templateHeader }) {
      const isHeaderValid = this.validateTableHeader(
        this.columns.map(({ label }) => label).slice(1),
        templateHeader
      )
      if (!isHeaderValid) {
        this.$message.warning('表格与导入的表头不一致!')
        return
      }
      if (templateItems.length === 0) {
        this.$message.warning('导入的表格没有数据!')
        return
      }
      templateItems.forEach(templateItem => {
        const tableItem = this.mapTemplateItemToTableItem(templateItem)
        this.tableData.push(tableItem)
      })
      this.validateFields(this.tableData).message()
    },
    async onSubmit() {
      const { message, isFinalValid } = this.validateFields(this.tableData)
      if (!isFinalValid) return message()

      const list = this.tableData.map(tableItem => requsetFields.reduce((prev, currentKey) => ({
        ...prev,
        [currentKey]: tableItem[currentKey]
      }), {}))

      this.loading = true
    }
  }
}
</script>

<style lang="scss">
.error-message__wrapper{
  width: 1024px;
}
</style>
