<template>
  <el-dialog title="上传评估预算函" :visible="innerVisible" width="1024px" @close="handleClose" center>
    <div style="padding:10px" v-loading="loading">
       <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>
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/service/customerService/workbench";
import companyHelper from '@/mixins/companyHelper'
import { template } from "./_template"
import { utils, writeFile } from "xlsx"

import {
  columns,
  getColumn,
  requsetFields,
  requiredFields,
  getTableProperty,
} from './_template'

export default {
  mixins: [companyHelper],
  props: ['visible', 'sitem', 'storeId'],
  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: {
    handleClose(){
      this.tableData = []
      this.innerVisible = false
    },
    downloadTemplate(){
      const workBook = utils.book_new()
      const workSheet = utils.json_to_sheet(template)
      utils.book_append_sheet(workBook,workSheet,"sheet")
      writeFile(workBook,"预算函模板.xlsx",{
        bookType:'xlsx'
      })
    },
    validateTableHeader(header, importHeader) {
      let isHeaderOk = true
      console.log(header,importHeader)
      if (header.length !== importHeader.length) return false
      for (const index in header) {
        const field = header[index]
        const importField = importHeader[index]
        if (field !== importField) {
          isHeaderOk = false
          break
        }
      }

      return isHeaderOk
    },
    isValueNotNull(value){
      if(!value) return
      const _value = String(value)
      return _value.trim() !== ""
    },
    /* 校验导入的数据 **/
    validateFields(tableData = []) {
      for (const index in tableData) {
        const line = Number(index) + 1
        const tableItem = 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
          }
        }
      }

      return true
    },
    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)
    },
    async onSubmit() {
      if(!this.validateFields(this.tableData)){
        return
      }

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

      const params = {
        store_id: this.storeId,
        req_id:this.sitem.id,
        plan_info
      }

      const { code } = await asyncRequest.planCreate(params)

      if(code === 1){
        this.innerVisible = false
        this.tableData = []
        this.$emit("refresh")
      }

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

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