<template>
  <el-dialog
    center
    width="1024px"
    title="导入业务经理修正"
    :visible="innerVisible"
    :close-on-click-modal="false"
    @close="() => {innerVisible = false; tableData = [];manager = ''; managerid = [];}"
  >
    <div v-if="tableData && tableData.length > 0" class="tr" style="padding: 10px 0 0 0;display:flex">
      <project-manager size="mini" :is-detail="true" :names="manager" :value="managerid" @searchChange="manageridChange" />

      <el-button type="warning" size="mini" style="margin-left:10px" @click="batchSetting">批量设置</el-button>
      <el-button type="danger" 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"
      @selection="handleSelection"
    />
  </el-dialog>
</template>

<script>
import asyncRequest from '@/apis/service/dataCorrection/managerBatchCorrection'
import companyHelper from '@/mixins/companyHelper'
import { MessageBox } from 'element-ui'
import dayjs from 'dayjs'

import {
  helper,
  columns,
  PROPERTYS,
  getTableProperty,
  createErrorMessage,
  createFieldVerification,
  requsetFields,
  requiredFields,
  orderCodeFields
} from './template'

export default {
  mixins: [companyHelper],
  props: ['visible','companyNo'],
  data() {
    return {
      columns,
      manager: "",
      managerid: [],
      selected: [],
      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: {
    batchSetting(){
      if(!this.manager || this.managerid.length === 0){
        this.$message.warning("请选择业务经理!")
        return
      }

      if(this.selected.length === 0){
        this.$message.warning("请选择至少一条记录!")
        return
      }

      const newTableData = JSON.parse(JSON.stringify(this.tableData));
      const orderCodes = this.selected.map(({orderCode}) => orderCode);

      newTableData.forEach(item => {
        if(orderCodes.includes(item.orderCode)){
          item.managerid = this.managerid[0];
          item.manager = this.manager;
        }
      })


      this.tableData = newTableData;
    },
    handleSelection(data){
      this.selected = data.list
    },
    manageridChange(data){
      this.managerid = data.id ? [data.id] :  []
      this.manager = data.label || ""

      console.log(this.managerid,this.manager)
    },
    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) {
          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
    },
    validateCodeField(orderCodeFields) {
      const verification = createFieldVerification('销售订单编号应该由字母和数字组成!')
      const fields = helper.fields(orderCodeFields)

      const reg = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]+$/
      orderCodeFields[fields[0]].forEach((_, index) => {
        if (!helper.values(orderCodeFields, fields, index).every(value => value && reg.test(value))) {
          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)),
        this.validateCodeField(helper.write(mapTableFieldToTableData, orderCodeFields))
      )
    },
    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 header = [columns[2].label,columns[3].label]
      const isHeaderValid = this.validateTableHeader(
        header,
        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)
      })
      const {isFinalValid, message} = this.validateFields(this.tableData)

      if(!isFinalValid){
        message();
        this.tableData = [];
      }
    },
    async onSubmit() {
      const { message, isFinalValid } = this.validateFields(this.tableData)

      if (!isFinalValid) return message()

      console.log(this.tableData)

      const isPass = this.tableData.every(({manager, managerid }) => manager && managerid)

      if(!isPass){
        this.$message.warning("部分订单未设置业务经理！")
        return
      }

      const list = this.tableData.map(tableItem => requsetFields.reduce((prev, currentKey) => ({
        ...prev,
        [currentKey]: currentKey === PROPERTYS.SEND_TIME ? dayjs(tableItem[currentKey] * 1000).format('YYYY-MM-DD HH:mm:ss') : tableItem[currentKey]
      }), {}))

      this.loading = true
      const result = await asyncRequest.import({ companyNo:this.companyNo, list })
      this.loading = false

      switch (String(result.code)) {
        case '0':
          this.$message.success('导入成功')
          this.innerVisible = false
          this.$emit('refresh')
          break
        default:
          this.$message.warning(result.message)
          break
      }
    }
  }
}
</script>

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