<template>
  <a-spin :spinning="spinningAdd">
    <div>
      <a-page-header
        style="background-color: #FFFFFF;"
        title="中继线稽核 客户资料导入"
        sub-title="1、先选择客户资料，进行导入前预览。2、信息无误后再确认导入"
        @back="goBack"
      >
        <a-descriptions :title="task.taskName" size="small" :column="3">
          <a-descriptions-item label="状态">
            <a-tag :color="task.taskStateColor">{{ task.taskStateText }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="开始时间">{{ task.taskStartTime }}</a-descriptions-item>
          <a-descriptions-item label="结束时间">{{ task.taskEndTime }}</a-descriptions-item>
          <a-descriptions-item label="描述"><span v-html="task.description"></span></a-descriptions-item>
          <!--{{task.description}}-->
        </a-descriptions>
        <a-divider style="margin: 6px;"/>
      </a-page-header>

      <a-card :bordered="false" style="margin-top: -22px;">
        <!-- 操作按钮区域 start -->
        <div class="table-operator">
          <a-upload name="file"
                    :showUploadList="false"
                    :multiple="false"
                    :headers="tokenHeader"
                    :action="url.importExcel"
                    @change="uploadChange">
            <a-button type="primary" icon="upload">客户资料选择</a-button>
          </a-upload>
          <a-button type="primary" icon="import"
                    @click="importInfo">确定导入
          </a-button>
          <a-button type="primary" icon="import"
                    @click="downloadTemplat">下载导入模版
          </a-button>
          <a-button type="primary" icon="import" v-has="'taskImportTruck:excelError'"
                    @click="handleExportXls('失败数据')">下载失败数据
          </a-button>
        </div>
        <!-- 操作按钮区域 end -->

        <!-- table区域 begin -->
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="false"
            :loading="loading"
            class="j-table-force-nowrap"
            :rowClassName='getRowBackGround'
            @change="handleTableChange">

          </a-table>
        </div>
        <!-- table区域 end -->

      </a-card>

    </div>
  </a-spin>


</template>

<script>

import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import { downFile, getAction, httpAction } from '@api/manage'

export default {
  name: 'TaskImport',
  mixins: [JeecgListMixin],
  data() {
    return {
      //加载属性
      spinningAdd: false,
      description: '导入页面',
      autoSearch: false,
      dataSource: [],
      errorCount: 0,
      task: {},
      type:null,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '客户编号',
          align: "center",
          dataIndex: 'customerNo'
        },
        // {
        //   title: '客户名称',
        //   align: "center",
        //   dataIndex: 'customerName'
        // },
        // {
        //   title: '服务号码',
        //   align: "center",
        //   dataIndex: 'smsNumber'
        // },
        {
          title: '用户编号',
          align: "center",
          dataIndex: 'userNo'
        },
        {
          title: '入网时间',
          align: "center",
          dataIndex: 'networkAccessTime'
        },
        // {
        //   title: '用户状态',
        //   align: "center",
        //   dataIndex: 'userState'
        // },
        {
          title: '用户发展员工',
          align: "center",
          dataIndex: 'staffName'
        },
        {
          title: '员工编号',
          align: "center",
          dataIndex: 'staffNo'
        },
        {
          title: '员工二级部门',
          align: "center",
          dataIndex: 'staffDeptLevel2Name'
        },
        // {
        //   title: '员工二级部门编号',
        //   align: "center",
        //   dataIndex: 'staffDeptLevel2No'
        // },
        {
          title: '员工三级部门',
          align: "center",
          dataIndex: 'staffDeptLevel3Name'
        },
        // {
        //   title: '员工三级部门编号',
        //   align: "center",
        //   dataIndex: 'staffDeptLevel3No'
        // },
        {
          title: '首次激活时间（固网起租时间）',
          align: "center",
          dataIndex: 'firstActivationDate'
        }, {
          title: '账户编码',
          align: "center",
          dataIndex: 'accountCode'
        }, {
          title: '楼宇名称',
          align: "center",
          dataIndex: 'floorName'
        },
        // {
        //   title: '楼宇编号',
        //   align: "center",
        //   dataIndex: 'floorCode'
        // },
        {
          title: '导入结果',
          align: "center",
          dataIndex: 'result',
          customRender: function (text, record, index) {
            if (text == "1") {
              return '成功'
            } else if (text == "0") {
              return '失败'
            }
            return '';
          }
        },
        {
          title: '错误结果',
          align: "center",
          dataIndex: 'errorMsg'
        },
      ],
      batchNo:"",
      url: {
        importExcel: window._CONFIG['domainURL'] + "/smsCheck/task/importCustomerExcel",
        importData: "/smsCheck/task/taskId/importCustomerData",
        queryTask: "/smsCheck/task/queryById",
        exportXlsUrl: "/smsCheckError/task/exportXls",
      },
    }
  },
  created() {
    this.task.id = this.$route.query.id;
    this.type = this.$route.query.type;
    this.queryInfoById(this.task.id);

  },
  methods: {
    handleExportXls(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      this.getQueryParams.taskId=this.task.id;
      let param = this.getQueryParams;
      if(this.selectedRowKeys && this.selectedRowKeys.length>0){
        param['selections'] = this.selectedRowKeys.join(",")
      }
      param['batchNo']=this.batchNo
      console.log("导出参数",param)
      downFile(this.url.exportXlsUrl,param).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName+'.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    /**下载模版*/
    downloadTemplat(){
      const a = document.createElement('a')
     a.href = '/web/tnc/static/taskTruckModel.xlsx'
      //a.href = '/static/taskTruckModel.xlsx'
      //ttp://172.16.142.20:7766/web/tnc/smscheck/modules/web/tnc/static/taskTruckModel.xlsx
      a.setAttribute('download', '中继线稽核模版.xlsx')
      a.click();
      a.remove();
    },
    // 返回上一级
    goBack() {
      this.$router.go(-1);
      this.closeCurrent();
    },
    /**
     * 上传事件回调
     *
     * @param result 回调值
     */
    uploadChange(result) {
      let file = result.file;
      let event = result.event;
      if (event === undefined && file.status === 'uploading') {
        this.$message.info('开始上传');
      }
      if (event && file.status === 'uploading') {
        this.$message.info('上传中，请稍等……');
      }
      if (file.response) {
        let success = file.response.success;
        let message = file.response.message;
        if (!success) {
          this.$message.error(message);
        }
        if (file.status === 'done') {
          this.dataSource = file.response.result.data;
          this.errorCount = file.response.result.errorCount;
          if (this.errorCount > 0) {
            this.$message.error('导入含有错误项，请检查内容')
          } else {
            this.$message.info('上传完成');
          }
        }
      }

    },
    /**
     * 导入信息
     */
    importInfo() {
      if (this.dataSource.length === 0) {
        this.$message.error('暂无导入数据，请上传导入文件！');
        return;
      }
      if (this.errorCount !== 0) {
        this.$message.error('包含非法数据，无法导入！');
        return;
      }

      this.$message.info('开始导入，请稍等……');
      this.spinningAdd = true;
      let httpUrl = this.url.importData.replaceAll("taskId", this.task.id);
      let params = this.dataSource;
      for (let i in params){
        params[i].type = this.type
      }
      let method = 'POST';
      let that = this;
      // 发送请求
      httpAction(httpUrl, params, method)
        .then((res) => {
          if (res.success) {
            that.dataSource = res.result
            if (res.result!==null){
              that.batchNo=res.result[0].batchNo
            }
            that.$message.success(res.message);
            that.$emit('ok');
            that.visible = false;
          } else {
            that.$message.warning(res.message);
          }
          this.spinningAdd = false;
        }).finally(() => {
        that.confirmLoading = false;
        this.spinningAdd = false;
      })
    },
    /**整行换色*/
    getRowBackGround(recordAlarm) {
      switch (recordAlarm.result) {//这里根据条件改变表格背景色
        case "0":
          return "table-color-error"
      }
    },

    getTaskState(taskState) {
      if (taskState === 0) {
        this.task.taskStateColor = '#fadb14';
        this.task.taskStateText = '未开始';
      } else if (taskState === 1) {
        this.task.taskStateColor = '#1890ff';
        this.task.taskStateText = '稽核中';
      } else if (taskState === 2) {
        this.task.taskStateColor = '#52c41a';
        this.task.taskStateText = '稽核完成';
      }
    },
    queryInfoById(id) {
      let url = this.url.queryTask;
      let params = {
        id: id
      }
      let that = this;
      getAction(url, params).then(res => {
        if (res.success) {
          that.task = res.result;
          that.getTaskState(that.task.taskState);
        }
      }).finally(() => {

      })
    },
  }
}
</script>

<style>
.table-color-error {
  color: rgba(255, 0, 0, 0.82);
  /*background-color: rgba(255, 0, 0, 0.82);*/
}

</style>