<template>
  <el-dialog title="导入数据" :close-on-click-modal="false" :visible.sync="visible" class="JNPF-dialog JNPF-dialog_center JNPF-dialog-export" lock-scroll :width="formData.generalWidth">
    <el-steps :space="330" :active="active" align-center finish-status="success">
      <el-step title="导入Excel文件"></el-step>
      <el-step title="字段关联"></el-step>
      <el-step title="完成导入"></el-step>
    </el-steps>
    <el-form label-position="top" style="margin-top: 20px">
      <el-form-item v-show="active === 0">
        <el-upload
          class="upload-demo"
          ref="uploadFile"
          drag
          :on-success="onSuccess"
          :before-upload="beforeUploadChange"
          accept=".xlsx,.xls"
          :action="define.comUploadUrl"
          :headers="{ 'Blade-Auth': Authorization }"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
        </el-upload>
      </el-form-item>
      <el-form-item v-show="active === 1">
        <el-table :data="fileList" border height="530">
          <el-table-column v-for="(item, index) in fileListCols" :key="index" :label="item" align="center" minWidth="120">
            <template slot-scope="scope">
              {{ scope.row[item] }}
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item v-show="active === 2">
        <el-tag type="info">文件名称：{{ fileName }}</el-tag>
        <div style="display: flex; justify-content: space-between; margin: 10px 0">
          <div>备注：<el-input v-model="fileContname" placeholder="请填写备注" style="width: 300px"></el-input></div>
          <div>是否清空原有数据：<el-switch v-model="coverData" active-color="#13ce66" :active-value="true" :inactive-value="false"></el-switch></div>
        </div>
        <el-table :data="fileList" border highlight-current-row height="520">
          <el-table-column width="80" align="center">
            <template slot-scope="scope">
              <div v-if="scope.$index === 0">字段绑定</div>
              <div v-else>{{ scope.$index }}</div>
            </template>
          </el-table-column>
          <el-table-column v-for="(item, index) in fileListCols" :key="index" :label="item" align="center" minWidth="120">
            <template slot-scope="scope">
              <el-form-item v-if="scope.$index === 0">
                <el-select v-model="associationLists[index].fieldId" placeholder="请选择关联字段" clearable>
                  <el-option-group v-for="group in columnList" :key="group.id" :label="group.tableName">
                    <el-option
                      v-for="item in group.children"
                      :key="item.id"
                      :value="item.id"
                      :disabled="getDisabledSelect(item.id)"
                      :label="item.columnTitle ? item.columnTitle + ' ' + item.columnName : item.columnComment + ' ' + item.columnName"
                    >
                    </el-option>
                  </el-option-group>
                </el-select>
                <!--                <el-select v-model="associationLists[index].fieldId" clearable placeholder="选择关联字段">-->
                <!--                  <el-option v-for="val in columnLists" :label="val.label" :value="val.propId" :key="val.propId" :disabled="getDisabledSelect(val.propId)"></el-option>-->
                <!--                </el-select>-->
              </el-form-item>
              <span v-else>{{ scope.row[item] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeClick">{{ $t('common.cancelButton') }}</el-button>
      <el-button v-if="active === 1" @click="removeClick()">上一步</el-button>
      <el-button
        v-if="active === 1"
        @click="
          active = 2
          fileList.unshift({})
        "
        >下一步</el-button
      >
      <el-button type="primary" :disabled="active !== 2" @click="downLoad">导 入</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import { read, utils } from 'xlsx'
import { cubeFieldList } from '@/api/workFlow/FlowEngine'
import { deepClone } from '@/utils'
export default {
  data() {
    return {
      visible: false,
      active: 0,
      btnLoading: false,
      type: 0,
      columns: [],
      checkAll: true,
      isIndeterminate: false,
      columnList: [],
      columnLists: [],
      Authorization: 'bearer ' + getToken(),
      files: [],
      fileList: [],
      fileListCols: [],
      fileName: '',
      listValue: '',
      associationLists: [],
      coverData: false,
      fileContname: '',
      formData: {}
    }
  },
  methods: {
    init(formData, columnList, dbLinkId) {
      this.formData = deepClone(formData)
      this.visible = true
      this.columnLists = columnList
      this.columns = columnList.map((o) => o.prop)
      if (dbLinkId) this.getCubeFieldList(dbLinkId)
    },
    getCubeFieldList(val) {
      cubeFieldList({ cubeDataId: val }).then((res) => {
        this.columnList = this.getmapList(res.data.data)
      })
    },
    //重装list
    getmapList(data) {
      let Idlist = data
        .map((o, i) => {
          if (o.columnAttr === 'NORMAL') {
            return {
              id: i,
              tableName: o.tableName,
              children: []
            }
          }
        })
        .filter((l) => l !== undefined)
      //去重分类
      let NewList = this.getfilterList(Idlist, 'tableName')
      //小蝌蚪找妈妈
      NewList.forEach((item, index) => {
        data.forEach((value, key) => {
          if (item.tableName === value.tableName) {
            item.children.push(value)
          }
        })
      })
      return NewList
    },
    getfilterList(arr, u_key) {
      let map = new Map()
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item)
        }
      })
      return [...map.values()]
    },
    getDisabledSelect(val) {
      let res = false
      this.associationLists.filter((i, k) => {
        if (i.fieldId && i.fieldId === val) {
          res = true
        }
      })
      return res
    },
    beforeUploadChange(file) {
      this.files = { 0: file }
      const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = fileType === ''
      const extension2 = fileType === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 100

      if (!extension && !extension2) {
        this.$message.error('上传文件只能是 xls或xlsx 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return (extension || extension2) && isLt2M
    },
    onSuccess(res) {
      if (res.code === 200) {
        this.fileName = res.msg
        const fileReader = new FileReader()
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result
            const workbook = read(data, { type: 'binary', cellDates: true, dateNF: 'yyyy-mm-dd' })
            //取第一张表
            const wsname = workbook.SheetNames[0]
            const wss = workbook.Sheets[wsname]
            //生成json表格
            const ws = utils.sheet_to_row_object_array(workbook.Sheets[wsname], {
              raw: false
            })
            //截取前六位展示預覽
            this.fileList = ws.slice(0, 6)
            // this.fileList.unshift({})
            //获取表头
            this.fileListCols = this.getHeaderRow(wss)
            this.associationLists = this.fileListCols.map((i, k) => {
              return {
                fieldName: i,
                fieldId: null,
                fieldKey: k
              }
            })
            this.$nextTick(() => {
              //如果字段和表头相同可以直接绑定
              function asscListFun(data, Lists) {
                data.forEach((item, index) => {
                  if (item.children && item.children.length) {
                    asscListFun(item.children, Lists)
                  } else {
                    Lists.forEach((i, k) => {
                      data.forEach((v, c) => {
                        if (i.fieldName === v.columnTitle) {
                          i.fieldId = v.id
                        }
                      })
                    })
                  }
                })
              }
              asscListFun(this.columnList, this.associationLists)
              this.active = 1
            })
          } catch (e) {
            return false
          }
        }
        fileReader.readAsBinaryString(this.files[0])
      }
    },
    getHeaderRow(sheet) {
      const headers = []
      /* sheet['!ref']表示所有单元格的范围，例如从A1到F8则记录为 A1:F8*/
      const range = utils.decode_range(sheet['!ref'])
      let C,
        R = range.s.r /* 从第一行开始 */
      /* 按列进行数据遍历 */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* 查找第一行中的单元格 */
        const cell = sheet[utils.encode_cell({ c: C, r: R })]
        let hdr = 'UNKNOWN ' + C // <-- 进行默认值设置
        if (cell && cell.t) hdr = utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    //取消
    closeClick() {
      if (this.active > 0) {
        this.$confirm('此操作将删除已导入的文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.fileList = []
            this.associationLists = []
            this.fileListCols = []
            this.$nextTick(() => {
              this.$refs.uploadFile.clearFiles()
              this.active = 0
              this.visible = false
            })
          })
          .catch(() => {})
      } else {
        this.visible = false
      }
    },
    //返回上一步操作
    removeClick() {
      this.$confirm('此操作将删除已导入的文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.fileList = []
          this.associationLists = []
          this.fileListCols = []
          this.$nextTick(() => {
            this.$refs.uploadFile.clearFiles()
            this.active = 0
          })
        })
        .catch(() => {})
    },
    downLoad() {
      let data = this.associationLists
        .map((o, i) => {
          if (o.fieldId) {
            return {
              fieldId: o.fieldId,
              index: o.fieldKey
            }
          }
        })
        .filter((l) => l !== undefined)
      this.$emit('UploadChange', { file: this.fileName, list: data, truncate: this.coverData, name: this.fileContname })
    }
  }
}
</script>
<style scoped></style>
