<template>
  <div>
  <el-dialog
    title="导入"
    v-loading="loading"
    element-loading-text="正在导入..."
    :visible.sync="show"
    :append-to-body="true"
    :modal-append-to-body="false"
    width="800px"
    :show-close="false"
  >
    <div class="body_header">
      <span>上传模板下载：</span>
      <el-button
        type="success"
        size="mini"
        icon="el-icon-download"
        @click="postImportDown"
        >获取模板</el-button
      >
    </div>
    <div class="body_header">
      <span> 导 入 模 式：</span>
      <el-radio-group v-model="method" >
        <el-radio label="1" :disabled="disabledMethod.method2">追加式</el-radio>
        <el-radio label="0" :disabled="disabledMethod.method1">更新式</el-radio>
        <el-radio label="2" :disabled="disabledMethod.method3">覆盖式</el-radio>
      </el-radio-group>
    </div>
    <div class="body_header">
      <span>是否部分导入：</span>
      <el-radio-group v-model="isAllowPartImport" >
        <el-radio label="0" :disabled="disabledIsAllowPartImport.isAllowPartImport1">是</el-radio>
        <el-radio label="1" :disabled="disabledIsAllowPartImport.isAllowPartImport2">否</el-radio>
      </el-radio-group>
    </div>
    <curren-Form
      class="importFile"
      size="medium"
      :searchData="FormData"
      :searchForm="Form"
      :searchHandle="editHandle"
      :rules="Rules"
      @submitForm="formClick(arguments)"
    >
    </curren-Form>
  </el-dialog>
  <!-- 导入预览 -->
  <el-dialog
    class="previewClass"
    title="导入预览"
    :visible.sync="previewShow"
    :append-to-body="true"
    :modal-append-to-body="false"
    :show-close="false"
    width="70%"
  >
    <div >
      <el-table 
        :data="excelData.results" 
        :border="true" 
        highlight-current-row 
        style="width: 100%;
        margin-top:10px;"
        max-height="400"
      >
        <el-table-column 
          v-if="excelData.header.length > 0" 
          type="index" 
          fixed="left" 
          label="序号"
          width="50"
        />
        <el-table-column 
          v-for="(item,index) of excelData.header" 
          :key="index" 
          :prop="item" 
          :label="item" 
        />
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="submitForm(0)">取 消</el-button>
      <el-button type="primary" @click="submitForm(1)">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
import XLSX from 'xlsx'
import currenForm from "@/components/currenForm"
export default {
  name: 'importFile',
  components: {
    currenForm
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    show: {
      type: Boolean,
      default: false
    },
    url: {
      type: String
    },
    postImport: {
      type: Function,
      default: () => { }
    },
    disabledMethod:{
       type: Object,
       default: () => {
          return {}
        }
    },
    disabledIsAllowPartImport:{
       type: Object,
       default: () => {
          return {}
        }
    },
    methodValue:{
      type: String,
      default:'1'
    },
    isAllowPartImportValue:{
      type: String
    }
  },
  data () {
    return {
      previewShow: false,
      // exel表头及数据
      excelData: {
        header: [],
        results: []
      },
      //表格流体最大高度
      tableMaxHeight:null,
      // 临时存储提交数据
      submitDataLS: null,
      method: '1',
      isAllowPartImport: '1',
      editHandle: [
        { label: "取消", name: "cancel" },
        { label: "确定", type: "primary", name: "determine" },
      ],
      FormData: {
        formFile: []
      },
      Form: [
        { type: "upload", label: "文件导入", prop: "formFile", limit: 1, colSpan: 24 }
      ],
      Rules: {
        formFile: { required: true, trigger: "change", message: "不可为空" }
      }
    }
  },
  mounted () {
    this.method = this.methodValue
    this.isAllowPartImport = this.isAllowPartImportValue
  },
  methods: {
    postImportDown () {
      this.$emit('postImportDown')
    },
    // postImport () {
    //   this.$emit('postImport')
    // },
    // methodValueChane() {
    //   this.$emit("methodChange", this.methodValue); // 用 $emit 通知父组件去修改
    // },
    // isAllowPartImportValueChane() {
    //   this.$emit("isAllowPartImportChange", this.isAllowPartImportValue); // 用 $emit 通知父组件去修改
    // },
    readerData(rawFile) {
      if (rawFile) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          // const workbook = XLSX.read(data, { type: 'array',cellText:false,cellDates:true })
          const workbook = XLSX.read(data, { type: 'array'})
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet,{raw:false})
          // const results = XLSX.utils.sheet_to_json(worksheet,{raw:false,dateNF:'yyyy-mm-dd'}) //yyyy-MM-dd HH:mm:ss
          if(results.length <= 0){
            this.$message.error('导入表格内无数据，请确认后重新导入');
            this.loading = false
            return
          }
          // this.generateData({ header, results })
          this.excelData.header = header
          this.excelData.results = results
          // this.tableMaxHeight = document.getElementById("tableOuter").clientHeight
          resolve()
          this.tab
        }
        reader.readAsArrayBuffer(rawFile)
      })
      }
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    // 文件预览
    submitForm(val) {
      if (val == 0) {
        this.previewShow = false
      } else {
        this.submiData(this.submitDataLS)
        this.previewShow = false
      }
    },
    // formClick(val) {
    //   this.FormData.method = this.method
    //   this.FormData.isAllowPartImport = this.isAllowPartImport
    //   this.$emit('importClick', val, this.FormData)
    // }
    formClick (val) {
      if (val[0] == 0) {
        this.submiData(val)
      } else {
        // 显示预览页
        // 没上传文件时 不显示预览界面
        if (val[1].fields[0].fieldValue[0]) {
          this.previewShow = true
          this.submitDataLS = val
          // 文件数据展示
          this.readerData(val[1].fields[0].fieldValue[0])
        } else {
          this.$message.error('请上传文件！');
        }
      }
    },
    // 提交数据
    submiData(val) {
      this.FormData.method = this.method
      this.FormData.isAllowPartImport = this.isAllowPartImport
      this.$emit('importClick', val, this.FormData)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  max-height: 100vh;
  display: flex;
  flex-direction: column;
}
.body_header {
  display: flex;
  align-items: center;
  padding: 0 0 20px 100px;
}
::v-deep .importFile {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .el-form {
    flex: 1;
    padding-left: 70px;
    padding-right: 70px;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    .el-row {
      flex: 2;
      padding-left: 30px;
      padding-right: 30px;
    }
  }
  .formButton {
    padding: 20px 20px 20px 0;
  }
}
</style>