<template>
  <el-dialog
    center
    width="1024px"
    title="导入发票信息"
    :visible="innerVisible"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <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"
    />
  </el-dialog>
</template>

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

import {
  columns,
  getColumn,
  getTableProperty,
  requsetFields,
  requiredFields,
  mapFields,
} from './_template'
import { invoiceTypeList } from '@/assets/js/statusList'

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
    },
    /* 校验导入的数据 **/
    /* 校验导入的数据 **/
    validateFields() {
      for (const index in this.tableData) {
        const line = Number(index) + 1
        const tableItem = this.tableData[index]
        const properties = Object.keys(tableItem)
        for (const property of properties) {
          if(requiredFields.includes(property) && !this.isValueNotNull(tableItem[property])){
            this.$message.warning(`第 ${line} 行 : ${getColumn(property).label} 不能为空`)
            return false
          }

          if(property === mapFields.invoiceType){
            const invoiceType = invoiceTypeList.find(({label}) => label === tableItem[property])

            if(!invoiceType){
              this.$message.warning(`第 ${line} 行 : ${getColumn(property).label} 必须为 ${invoiceTypeList.map(({label}) => label).join('、')}`)
              return false
            }

            // this.tableData[index][property] = invoiceType.value
          }
        }
      }

      return true
    },
    isValueNotNull(value){
      if(!value) return
      const _value = String(value)
      return _value.trim() !== ""
    },
    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(2),
        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)
    },
    handleClose(){
      this.innerVisible = false
      this.tableData = []
    },
    async onSubmit() {
      if(!this.validateFields(this.tableData)){
        return
      }

      const list = this.tableData.map(tableItem => requsetFields.reduce((prev, currentKey) => {
        let data = tableItem[currentKey]
        if(currentKey === mapFields.invoiceType){
          const invoiceType = invoiceTypeList.find(({label}) => label === tableItem[currentKey])
          data = invoiceType.value
        }

        return {
            ...prev,
            [currentKey]: data
          }
      }, {}))


      this.$emit("change",list)
      this.innerVisible = false
    }
  }
}
</script>

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