<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'
import dayjs from 'dayjs'

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.openTime){
            const chunks = (String(tableItem[property]) || "").split("-")

            if(chunks.length !== 3 || (
              chunks[0].length !== 4 ||
              chunks[1].length !== 2 ||
              chunks[2].length !== 2
            )){
              this.$message.warning(`第 ${line} 行 : 开票日期格式错误,请使用"2023-01-01"格式上传`)
              return
            }

          }

          //发票相关校验
          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
            }

            //普通发票校验验证码
            if(["1","3"].includes(invoiceType.value) && tableItem[mapFields.checkNumber] === ""){
              this.$message.warning(`第 ${line} 行 : 发票类型为普通发票时必须上传校验码`)
              return false
            }

            console.log(invoiceType.value)
          }
        }
      }

      return true
    },
    formatDate (timeNum) {
      const time = new Date(((Number(timeNum) - 70 * 365 - 19) * 24 * 3600 - 8 * 3600 - 42.5) * 1000)
      const year = time.getFullYear()
      const month = time.getMonth() + 1
      const date = time.getDate() + 1
      const dateArr = [
          year,
          (month < 10 ? '0' + month : month),
          (date < 10 ? '0' + date : date),
      ]
      return `${dateArr.join('-')}`
    },
    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(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)
    },
    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>
