<template>
  <div class="common-wrap-cnt">
    <section class="create-form-header">
      <p class="form-title">导入创建</p>
      <section class="form-operate">
        <el-button type="plain" size="small" @click="handleMessageCancel">重置</el-button>
        <el-button type="primary" size="small" @click="handleSubmit">提交</el-button>
      </section>
    </section>
    <section class="common-create-main">
      <p class="common-title">文件上传</p>
      <section class="file-upload">
        <div class="file-upload-bg">
          <div style=" display: flex;align-items: center;justify-content: center; height:50px;margin-top:25px">
            <i class="el-icon-upload"></i>
          </div>
          <div class="file-upload-desc">仅允许导入xls、xlsx格式文件，文件大小不超过10m</div>
          <div class="file-upload-btn">
            <el-upload class="custom-el-upload" style="display:inline-block" ref="upload" :on-change="handleFileChange"
              :file-list="fileList" :auto-upload="false" :on-remove="handleRemove" action="#" accept=".xlsx, .xls">
              <el-button type="primary" :disabled="iscustomType">上传文件</el-button>
            </el-upload>
            <el-button class="template" icon="el-icon-download" type='text' @click="handleCsvDownload">模板样例.xlsx</el-button>
          </div>
          <!-- <div class="file-upload-download">
            <el-button icon="el-icon-download" type='text' @click="handleCsvDownload(2)" :disabled="isPrivate">企业模板下载</el-button>
            <el-button icon="el-icon-download" type='text' @click="handleCsvDownload(1)" :disabled="isPublic">商户模板下载</el-button>
            <el-button icon="el-icon-download" type='text' @click="handleCsvDownload(0)" :disabled="isPublic">个人模板下载</el-button>
          </div> -->
          <div class="file-upload-progress">
            <el-progress v-show="progressFlag" style="width:70%" :percentage="loadProgress"></el-progress>
            <el-button v-show="progressFlag" type="text" style="margin-left:20" @click="handleCsvPrase">预览</el-button>
          </div>
        </div>
        <div class="group-input">
          <span style="font-weight: 500">分群名称</span>
          <el-input placeholder="请输入客群名称" style="width: 612px;margin-left:20px" v-model="groupName" clearable></el-input>
        </div>
        <div class="group-select">
          <span style="font-weight: 400">客户类型</span>
          <el-select v-model="custType" style="width: 612px;margin-left:20px" change="handSelect" clearable>
            <el-option v-for="item in clientTypeOptions" :key="item.value" :label="item.label"
              :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </div>
      </section>


      <section class="preview-cnt">
        <p class="common-title">预览</p>
        <section class="table-wrap preview-table">
          <el-table :data="paginatedData" class="common-table-cnt">
            <el-table-column v-for="(column, index) in columns" :key="index" :prop="column"
              :label="column"></el-table-column>
            <!-- <el-table-column prop="客户号" label="客户号" align="center"></el-table-column>
            <el-table-column prop="客户内码" label="客户内码" align="center"></el-table-column>
            <el-table-column prop="客户姓名*" label="客户姓名*" align="center"></el-table-column>
            <el-table-column prop="证件号*" label="证件号*" align="center"></el-table-column>
            <el-table-column prop="推送客户经理" label="推送客户经理" align="center"></el-table-column>
            <el-table-column prop="推送网点" label="推送网点" align="center"></el-table-column> -->
          </el-table>
          <!-- 分页 -->
          <el-pagination v-if="isPagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="->,total,prev,pager,next,sizes"
            :total="tableData.length" :current-page="currentPage"></el-pagination>
        </section>
      </section>
    </section>
    <!-- <div class="dialog-container">
      <el-dialog :visible.sync="importVisible" title="" width="25%" class="dialog-header" center>
        <div class="dialog-content">
          <div class="group-text err-text">
            <p>
              这是一段报错信息...
            </p>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleImportCancle">取 消</el-button>
          <el-button type="primary"  @click="exportErrData">
            导出
          </el-button>
        </span>
      </el-dialog>
    </div> -->
  </div>
</template>
<script>
import * as XLSX from "xlsx";
import { Message } from 'element-ui'
import { importData,downloadFile } from '@/api/system/importdata.js'
import { downloadFiles } from '@/utils'
import { mapGetters } from 'vuex'
// import axios from 'axios'
export default {
  created() {
  },
  data() {
    return {
      isPagination: false,
      columns: ["客户类型*", "客户名称", "客户号*", "推送机构号", "联系方式", "推送柜员号"],
      iscustomType: false,
      progressFlag: false,
      loadProgress: 0,
      file: null,
      groupName: '',
      jsonData: [],
      tablekey: 0,
      fileList: [],
      tableData: [],
      tableHeaders: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      custType: "",
      clientTypeOptions: [
        { value: "0", label: "个人" },
        { value: "1", label: "商户" },
        { value: "2", label: "企业" },
      ],
      importVisible:false,
      groupId:''
    };
  },
  computed: {
    ...mapGetters(['roles']),
    //对公
    isPublic() {
      return this.roles.includes('headPublic');
    },
    //对私
    isPrivate() {
      return this.roles.includes('headPrivate')
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
  },

  created(){
    if(this.isPrivate){
      this.clientTypeOptions = this.clientTypeOptions.map(item=>{
          return {
            ...item,
            disabled:item.value == '2'
          }
        })
    }
    if(this.isPublic){
      this.clientTypeOptions = this.clientTypeOptions.map(item=>{
          return {
            ...item,
            disabled:item.value != '2'
          }
        })
    }
  },

  methods: {
    handleMessageCancel() {
      this.custType = '';
      this.groupName = '';
      this.tableData = [];
      this.$refs.upload.clearFiles();
      this.loadProgress = 0;
      this.progressFlag = false;
      Message.warning('取消提交!')
    },
    handleSubmit() {
      const formData = new FormData();

      if (this.groupName == '') {
        Message.error('分群名称不能为空')
        return;
      }
      if (this.custType == '') {
        Message.error('客户类型未选择')
        return;
      }
      if (this.$refs.upload.uploadFiles[0]?.raw == null) {

        Message.error('请上传文件侯提交')
        return;
      }
      formData.append('groupName', this.groupName.trim())
      formData.append('file', this.$refs.upload.uploadFiles[0]?.raw)
      formData.append('custType', this.custType)
      formData.append('importType ','0')
      importData(formData).then(res => {
        if (res.code == 200) {
          const {warningStr,notEmptyList} = res.data;
          if(warningStr){
            // const groupId = notEmptyList[0].groupId;
            // this.goBackToCreateType(warningStr,groupId,this.groupName.trim())
            Message.success(`导入成功,${warningStr}`)
          }else{
            Message.success('导入成功')
            this.goBackToCreateType()
          }
        }
      })

    },

    // 导入报错弹框取消
     handleImportCancle() {
      this.importVisible = false;
     },

    // 导出失败数据
    exportErrData(){
      this.download(
        `/system/group/exportDataError/?groupId=${this.groupId
        }`,
        {},
        `导入失败_${new Date().getTime()}.xlsx`
      );
    },
    handleFileChange(file, fileList) {
      //判断客户类型
      if(file.size>10*1024*1000){
        Message.warning('文件大小不能超过10m');
        return;
      }
      this.file = file;
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      }
      if (file.status === 'ready') {
        // alert(file.status)
        this.progressFlag = true;
        this.loadProgress = 0;
        const interval = setInterval(() => {
          if (this.loadProgress >= 100) {

            // alert(this.subCustType)

            clearInterval(interval)
            return;
          }
          this.loadProgress += 1;
        }, 20)
      }
      if (file.status == 'success') {

        this.progressFlag = false;
        this.loadProgress = 100;
      }

    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    handleCsvColumns() {
      if (!this.file) return;
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: "binary" });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const json_data = XLSX.utils.sheet_to_json(worksheet);
        // this.columns = Object.keys(json_data[0]).map(item => {
        //   if (item.includes('商户')) {
        //     this.subCustType = 1
        //     return;
        //   }
        //   else if (item.includes('企业')) {
        //     this.subCustType = 2
        //     return;
        //   } else {
        //     this.subCustType = 0
        //   }

        // })
      };
      reader.readAsBinaryString(this.file.raw);
    },
    handleCsvPrase() {
      if (!this.file) return;
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: "binary" });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const json_data = XLSX.utils.sheet_to_json(worksheet);
        // console.log(json_data,'json_data')
        // this.columns = Object.keys(json_data[0]).map(item => {

        //   if (item.includes('证件类型(居民二代身份证/居民身份证/港澳居民来往内地通行证/台湾居民来往大陆通行证/外国人永久居留身份证)')) {
        //     return item = '证件类型'
        //   }
        //   return item;
        // })
        this.tableData = json_data.map(obj => {
          // if (obj['证件类型(居民二代身份证/居民身份证/港澳居民来往内地通行证/台湾居民来往大陆通行证/外国人永久居留身份证)']) {
          //   obj['证件类型'] = obj['证件类型(居民二代身份证/居民身份证/港澳居民来往内地通行证/台湾居民来往大陆通行证/外国人永久居留身份证)']
          //   delete obj['证件类型(居民二代身份证/居民身份证/港澳居民来往内地通行证/台湾居民来往大陆通行证/外国人永久居留身份证)']
          // }
          let keys = Object.keys(obj);
          let key1 = keys.find(i=>i.includes('客户类型'));
          let key2 = keys.find(i=>i.includes('客户名称'));
          let key3 = keys.find(i=>i.includes('推送机构号'));
          return {
            ...obj,
            '客户类型*':obj[key1],
            '客户名称':obj[key2],
            '推送机构号':obj[key3],
          }
          // for (let key in obj) {
          //   debugger
          //   if (key == '证件类型(居民二代身份证/居民身份证/港澳居民来往内地通行证/台湾居民来往大陆通行证/外国人永久居留身份证)') {
          //     obj['证件类型'] = obj[key];
          //     delete obj.key;

          //   }
          //   return obj
          // }

        }) || [];
        this.isPagination = true
      };
      // console.log(this.columns,this.tableData)
      reader.readAsBinaryString(this.file.raw);
    },

    goBackToCreateType(warningStr,groupId,groupName) {

      this.$router.replace({
        path:'/grid/create/segmentation',
        // query: {
        //   refresh: true,
        //   warningStr,
        //   groupId
        // }
      })
      if(warningStr){
        this.$store.commit("SET_IMPORT_ERROR", {
          warningStr,
          groupId,
          groupName
        });
      }
    },
    handleCsvDownload() {
      let resultName = `模板_${new Date().getTime()}.xlsx`;
      // if (type == 0) {
      //   // this.custType='0'
      //   resultName = `个人模板_${new Date().getTime()}.xlsx`
      // }
      // else if (type == 2) {
      //   // this.custType='2'
      //   resultName = `企业模板_${new Date().getTime()}.xlsx`
      // }
      // else {
      //   // this.custType='1'
      //   resultName = `商户模板_${new Date().getTime()}.xlsx`
      // }
      
      downloadFile('').then(res=>{
        downloadFiles(res, resultName)
      })
    },
    handleRemove() {
      this.tableData = []
      this.loadProgress = 0;
      this.progressFlag = false
    }
  },
};

</script>
<style lang="scss" scoped>
@import './../create-style.scss';

.file-upload {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: space-between;
  height: 320px;

  .group-input {
    width: 702px;
    height: 288px;
    margin-top: 25px;

  }

  .group-select {
    width: 702px;
    height: 288px;
    margin-top: 25px;
  }

  .file-upload-bg {
    width: 702px;
    height: 288px;
    background: #F7F8FA;
    // display: flex;
    // align-items: center;
    // justify-content: center;
  }

  .el-icon-upload {
    text-align: center;
    font-size: 47.36px;
    color: #CCCCCC;
  }

  .file-upload-desc {
    font-weight: 400;
    font-size: 14px;
    color: #666666;
    letter-spacing: 0;
    text-align: center;
    line-height: 12px;
    margin-top: 8px;
  }

  .file-upload-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    margin-top: 20px;
    ::v-deep .el-upload-list{
      display: none;
    }
    .template{
      margin-left: 5px;
    }
  }

  .file-upload-download {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    margin-top: 15px;
    font-size: 14px;
  }

  .file-upload-progress {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    margin-top: 15px;
    font-size: 14px;
  }
}

.preview-table {
  width: 100%;
  margin-top: 16px;
}

.preview-cnt {
  margin-top: 40px;
}

.chose-cnt {
  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: space-between;

    .el-button {
      width: 88px;
      margin-left: 24px;
    }

    .el-select {
      flex: 1;
    }
  }
}
</style>
