<template>
  <el-dialog title="上传活动方案" :visible="innerVisible" width="1024px" @close="handleClose" center>

    <div v-if="file_url" style="margin-left:20px">
      <a :href="file_url" download="计划预算函">点击下载</a>
      <el-link
        :underline="false"
        @click="deleteUrl('3')"
        type="warning"
        style="margin: 0 0 0 16px"
        >删除</el-link
      >
    </div>

    <div class="activity-upload" v-else>
      <div class="btnupload" style="position: relative">
        <i class="el-icon-plus avatar-uploader-icon"></i>
        <file-upload-pdf
          class="Upload"
          :accept="'.xlsx,.xls,.pdf,.zip,.rar,.7z'"
          :multiple="false"
          :uploadcondition="beforeOtherUpload"
          @UploadErrorEvent="UploadErrorOtherproof_url"
          @UploadSuccessEvent="UploadSuccessOtherproof_url"
        />
      </div>
      <div class="txt-tips fl">
        <p>建议大小：小于5MB</p>
        <p>文件格式：.xlsx,.xls,.pdf,.zip,.rar,.7z</p>
      </div>
    </div>

    <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', 'id'],
  data() {
    return {
      columns,
      loading: false,
      tableData: [],
      file_url:"",
      isInit:true,
      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.loading = false
      this.file_url = ""
      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
    },
    beforeOtherUpload(file) {
      let isJPG = false;
      if (
        file.type === "application/vnd.ms-excel" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        file.type === "application/pdf" ||
        file.type === "application/x-zip-compressed"
      ) {
        isJPG = true;
      }
      let name = file.name;
      let list = name.split(".");
      if (list[list.length - 1] === "rar" || list[list.length - 1] === "7z" || list[list.length - 1] === "zip") {
        isJPG = true;
      }

      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error("文件格式不正确！");
      }
      if (!isLt2M) {
        this.$message.error("文件大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
        //其他文件上传失败
    UploadErrorOtherproof_url(res) {
      if (res !== "break") {
        this.$message.error("文件上传失败!");
      }
    },
    async UploadSuccessOtherproof_url(data) {
      console.log(data)
      const { url } = data;
      this.file_url = url;
      this.$message.success("文件成功!");
    },
    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 planinfo = this.tableData.map(tableItem => requsetFields.reduce((prev, currentKey) => ({
        ...prev,
        [currentKey]: tableItem[currentKey]
      }), {}))

      const params = {
        status: 2,
        id: this.id,
        planinfo,
        file_activty_url: this.file_url
      }

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

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

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

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

.activity-upload{
  margin-bottom: 50px;
  margin-left: 10px;
}
</style>
