<template>
  <div>
    <a-card :bordered="false" style="margin-top: -20px;">

      <a-tabs v-has="'specialApply:check:state:01'" :active-key="currentTab" default-active-key="all" @change="tabChange">
        <a-tab-pane key="all" :tab="tableALLPart"></a-tab-pane>
        <a-tab-pane key="uncheck" :tab="tabUncheck"></a-tab-pane>
        <a-tab-pane key="checked" :tab="tabChecked"></a-tab-pane>
        <a-tab-pane key="passed" :tab="tabPassed"></a-tab-pane>
      </a-tabs>

      <a-tabs v-has="'specialApply:check:state:all'" :active-key="currentTab" default-active-key="all" @change="tabChange">
        <a-tab-pane key="all" :tab="tabAll"></a-tab-pane>
        <a-tab-pane key="handel" :tab="tabHandle"></a-tab-pane>
        <a-tab-pane key="undo" :tab="tabUndo"></a-tab-pane>
        <a-tab-pane key="uncheck" :tab="tabUncheck"></a-tab-pane>
        <a-tab-pane key="checked" :tab="tabChecked"></a-tab-pane>
        <a-tab-pane key="passed" :tab="tabPassed"></a-tab-pane>
      </a-tabs>

      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="机主姓名">
                <j-input placeholder="请输入机主姓名" v-model="queryParam.customerName"></j-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="号码">
                <j-input placeholder="请输入号码" v-model="queryParam.smsNumber"></j-input>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">

            </template>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button v-has="'specialApply:task:check:import:custiom'" type="primary" icon="download"
                  @click="importCustiom">导入客户
        </a-button>
        <a-button type="primary" icon="download" @click="handleExportXls('特审复开信息')">导出</a-button>
        <a-button v-if="selectedRowKeys.length > 0" type="primary" icon="upload" @click="batchImproves()">材料批量上传
        </a-button>

        <!-- 高级查询区域 -->
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="batchDel" v-has="'task:check:list:delete'">
              <a-icon type="delete"/>
              删除
            </a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px"> 批量操作
            <a-icon type="down"/>
          </a-button>
        </a-dropdown>
      </div>

      <!-- table区域-begin -->
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          ref="table"
          size="middle"
          :scroll="{x:true}"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          class="j-table-force-nowrap"
          @change="handleTableChange">


          <template slot="action" slot-scope="text, record">

            <span v-has="'special:task:check:list:upload:improve'"
                  v-if="record.checkState == 0 || record.checkState == 1">
              <a @click="showImprove(record)">上传资料</a>
              <a-divider type="vertical"/>
            </span>

            <span v-has="'special:task:check:list:upload:improve'" v-if="record.checkState == 4">
              <a @click="showUpload(record)">整改</a>
              <a-divider type="vertical"/>
            </span>



            <span v-has="'special:task:check:list:audit'" v-if="record.checkState === 2 || record.checkState === 3">
              <a @click="showCheckCheck(record)">稽核</a>
              <a-divider type="vertical"/>
            </span>

            <span v-has="'special:task:check:list:download:all'">
              <a @click="getFileUrls(record)">下载资料</a>
              <a-divider type="vertical"/>
            </span>


            <span v-has="'lot:task:check:list:audit:resetting'" v-if="record.checkState === 5">
              <a @click="showCheckCheck(record)">重新稽核</a>
              <a-divider type="vertical"/>
            </span>

            <span v-has="'special:task:check:list:history'" v-if="record.checkState >= 4">
              <a @click="showCheckLog(record)">历史</a>
              <a-divider type="vertical"/>
            </span>

            <span v-has="'special:task:check:list:history'" v-if="record.checkState >= 4">
              <a @click="showCheckLog(record)">下载资料</a>
              <a-divider type="vertical"/>
            </span>

            <span v-has="'special:task:check:list:notice'"
                  v-if="record.checkState != 2 && record.checkState != 3 && record.checkState != 5">
              <a @click="noticeDeal(record)">催办</a>
              <a-divider type="vertical"/>
            </span>


            <a-dropdown>
              <a class="ant-dropdown-link">更多
                <a-icon type="down"/>
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-has="'special:task:check:list:delete'" v-if="record.checkState == 0 || record.checkState == 1">
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>

          <template v-slot:customerName="text, record">
            <a @click="showCheckDetail(record)">{{ text }}</a>
          </template>

          <template v-slot:checkState="status">
            <a-badge :status="status | statusTypeFilter" :text="status | statusFilter"/>
          </template>

          <template v-slot:shutdownLabel="text, record">
           <span style="width: 200px;max-width: 30em;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;display: block;">{{shutdownLabelSpan(text,record)}}</span>
          </template>


          <template v-slot:rowIndex="text,records,index">
            {{ (ipagination.current - 1) * ipagination.pageSize + Number(index) + 1 }}
          </template>

        </a-table>

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

  </div>

</template>

<script>

import {postAction, getAction, httpAction, deleteAction} from '@api/manage'
import '@/assets/less/TableExpand.less'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import FileSaver from 'file-saver'
import JSZip from "jszip";

export default {
  name: 'TaskCheckList',
  mixins: [JeecgListMixin],
  inject: ['closeCurrent'],
  data() {
    let _self = this;
    return {
      description: '稽核详情页面',
      currentTab: 'all',
      currentCheckState: null,
      task: {
        id: '',
        taskName: '',
        taskStartTime: '',
        taskEndTime: '',
        description: '',
        taskState: 0,
        taskStateText: '',
        taskStateColor: '',
      },
      tabAll: '全部（0）',
      tabHandle:"未处理（0）",
      tabUndo: '未完善（0）',
      tabUncheck: '待稽核（0）',
      tabChecked: '待整改（0）',
      tabPassed: '稽核通过（0）',
      tableALLPart:'全部（0）',
      count: 0,
      undoCount: 0,
      uncheckCount: 0,
      checkedCount: 0,
      passedCount: 0,
      /* 排序参数 */
      queryParam: {
        column: 'createTime',
        order: 'desc',
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 20,
          align: "center",
          fixed: 'left',
          scopedSlots: {customRender: 'rowIndex'}
        },
        {
          title: '提交材料日期',
          align: "center",
          width: 40,
          sorter: true,
          fixed: 'left',
          dataIndex: 'createTime'
        },
        {
          title: '机主姓名',
          align: "center",
          width: 40,
          sorter: true,
          dataIndex: 'customerName',
          fixed: 'left',
          scopedSlots: {customRender: 'customerName'}
        },
        {
          title: '号码',
          align: "center",
          width: 40,
          sorter: true,
          fixed: 'left',
          dataIndex: 'smsNumber'
        },
        {
          title: '关停标签',
          align: "center",
          sorter: true,
          width: 20,
          dataIndex: 'shutdownLabel',
          scopedSlots: {customRender: 'shutdownLabel'}
        },
        {
          title: '最后一次关停时间',
          align: "center",
          sorter: true,
          width: 40,
          dataIndex: 'shutdownLabelDate'
        },
        {
          title: '有无特审单',
          align: "center",
          sorter: true,
          dataIndex: 'materialLabel'
        },
        {
          title: '是否自查实名制合规',
          align: "center",
          sorter: true,
          dataIndex: 'nameFindCompliance'
        },
        {
          title: '复开时间',
          align: "center",
          sorter: true,
          dataIndex: 'reopenTime'
        },
        {
          title: '申请人二级部门',
          align: "center",
          sorter: true,
          dataIndex: 'staffDeptLevel2Name'
        },
        {
          title: '申请人三级部门',
          align: "center",
          sorter: true,
          dataIndex: 'staffDeptLevel3Name'
        },
        {
          title: '申请人厅店/组别',
          align: "center",
          sorter: true,
          dataIndex: 'staffDeptLevel4Name'
        },
        {
          title: '工单创建人',
          align: "center",
          sorter: true,
          dataIndex: 'staffName'
        },
        {
          title: '创建人工号',
          align: "center",
          sorter: true,
          dataIndex: 'staffNo'
        },
        {
          title: '稽核进度',
          align: "center",
          sorter: true,
          dataIndex: 'checkState',
          scopedSlots: {customRender: 'checkState'}
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: "center",
          scopedSlots: {customRender: 'action'}
        }
      ],
      url: {
        queryTask: "/smsCheck/task/queryById",
        list: "/smsCheck/customerInfo/special/list",
        count: "/special/examination/type/count",
        delete: "/smsCheck/customerInfo/delete",
        edit: "/smsCheck/customerInfo/edit",
        notice: "/smsCheck/customerInfo/notice",
        editCheck: "/smsCheck/customerInfo/edit/check/state",
        dataDelete: "/smsCheck/customerData/clear",
        exportXlsUrl: "/special/examination/exportXls",
        deleteBatch:"/smsCheck/customerInfo/deleteBatch",
        queryUrlById:"/smsCheck/customerInfo/queryUrlById"
      },
      autoSearch: false,
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '50', '100','200'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
    }
  },
  created() {
    this.task.id = this.$route.query.id;
    this.queryTaskById(this.task.id);
    this.queryParam.taskId = this.task.id;
    this.loadData();
    this.loadTabNumber(this.task.id);
  },
  filters: {
    statusTypeFilter(type) {
      const statusTypeMap = {
        '0': 'default',
        '1': 'error',
        '2': 'warning',
        '3': 'warning',
        '4': 'processing',
        '5': 'success'
      }
      return statusTypeMap[type]
    },
    statusFilter(status) {
      const statusMap = {
        '0': '未处理',
        '1': '未完善',
        '2': '待稽核',
        '3': '待稽核',
        '4': '待整改',
        '5': '通过'
      }
      return statusMap[status]
    }
  },
  methods: {
    /**导入客户列表*/
    importCustiom() {
      this.$router.push({path: '/specialApply/task/import', query: {id: this.task.id}});
    },
    // 返回上一级
    goBack() {
      this.$router.go(-1);
      //关闭当前页面
      this.closeCurrent();
    },
    // 上传客户资料
    showImprove(record) {
      this.$router.push({path: '/specialApply/data/upload', query: {id: record.id}});
    },
    //批量上传客户资料
    batchImproves(ids) {
      this.$router.push({path: '/specialApply/data/upload', query: {ids: this.selectedRowKeys, batchImproves: true}});
    },
    // 整改
    showUpload(record) {
      this.$router.push({path: '/specialApply/data/upload', query: {id: record.id, data: record, rectification: true}});
    },
    // 显示上传页面
    handSubmit(record) {
      let that = this;
      let model = {
        id: record.id,
      }
      postAction(this.url.editCheck, model)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData(that.ipagination.current);
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {

      })
    },
    dataDelete(id) {
      var that = this;
      deleteAction(that.url.dataDelete, {infoId: id}).then((res) => {
        if (res.success) {
          that.$message.success('附件资料清空完成！');
        } else {
          that.$message.warning('附件资料清空失败！');
        }
      });
    },
    // 稽核点击事件
    showCheckCheck(record) {
      this.$router.push({path: '/specialApply/modules/TaskCheckAudit', query: {id: record.id}});
    },
    // 显示稽核详情页面
    showCheckDetail(record) {
      this.$router.push({path: '/specialApply/data/upload', query: {id: record.id, data: record,
          rectification: true,detail:true}});
    },
    // 显示稽核历史页面
    showCheckLog(record) {
      this.$router.push({path: '/sms/check/task/check/log', query: {id: record.id}});
    },
    // 构建任务信息
    buildTaskInfo(record) {
      let taskInfo = Object.assign({}, this.task);
      taskInfo.count = this.count;
      taskInfo.undoCount = this.undoCount;
      taskInfo.uncheckCount = this.uncheckCount;
      taskInfo.checkedCount = this.checkedCount;
      taskInfo.passedCount = this.passedCount;
      return {
        task: this.task,
        info: record
      }
    },
    handleCancel() {
      this.visible = false;
    },
    detail(record) {
      this.model = Object.assign({}, record);
      this.visible = true;
    },
    searchQuery() {
      this.loadData(1);
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.loadTabNumber(this.task.id);
    },
    searchReset() {
      this.queryParam = {};
      this.queryParam.taskId = this.task.id;
      this.queryParam.checkState_MultiString = this.currentCheckState;
      this.tabChange('all');
      this.loadTabNumber(this.queryParam.taskId);
    },
    tabChange(key) {
      // 稽核状态（0：未处理；1：未完善；2：待稽核；3：待整改；4：已整改；5：稽核通过；）
      if (key === 'all') {
        this.currentCheckState = null;
        this.queryParam.checkState_MultiString = this.currentCheckState;
        this.currentTab = 'all';
      }else if (key === 'handel'){
        this.currentCheckState = '0';
        this.queryParam.checkState_MultiString = this.currentCheckState;
        this.currentTab = 'handel';
      } else if (key === 'undo') {
        this.currentCheckState = '1';
        this.queryParam.checkState_MultiString = this.currentCheckState;
        this.currentTab = 'undo';
      } else if (key === 'uncheck') {
        this.currentCheckState = '2';
        this.queryParam.checkState_MultiString = this.currentCheckState;
        this.currentTab = 'uncheck';
      } else if (key === 'checked') {
        this.currentCheckState = '4';
        this.queryParam.checkState_MultiString = this.currentCheckState;
        this.currentTab = 'checked';
      } else if (key === 'passed') {
        this.currentCheckState = '5';
        this.queryParam.checkState_MultiString = this.currentCheckState;
        this.currentTab = 'passed';
      }
      this.loadData(1);
    },
    loadTabNumber(taskId) {
      let params = {id: "1111"}
      let url = this.url.count;
      if (taskId) {
        params = {
          id: taskId
        }
      }
      let that = this;
      getAction(url, params).then(res => {
        let {result} = res;
        if (result) {
          that.count = result.count;
          that.undoCount = result.undoCount;
          that.uncheckCount = result.uncheckCount;
          that.checkedCount = result.checkedCount;
          that.passedCount = result.passedCount;
          that.handelCount = result.handleCount;
          that.tabAll = '全部（' + result.count + '）';
          that.tabHandle = '未处理（' + result.handleCount + '）';
          that.tabUndo = '未完善（' + result.undoCount + '）';
          that.tabUncheck = '待稽核（' + result.uncheckCount + '）';
          that.tabChecked = '待整改（' + result.checkedCount + '）';
          that.tabPassed = '稽核通过（' + result.passedCount + '）';
          that.tableALLPart ='全部（' + (result.count -    result.undoCount -  result.handleCount) + '）';
        }
      }).finally(() => {

      })
    },
    noticeDeal(record) {
      let url = this.url.notice;
      let params = {
        customerName: record.customerName,
        smsNumber: record.smsNumber,
        staffNo: record.staffNo,
        userNo: record.userNo,
      }
      let that = this;
      postAction(url, params).then(res => {
        let {result} = res;
        if (res.success) {
          that.$message.info('已通知客户经理，进行材料补充！');
        }
      }).finally(() => {

      })

    },
    queryTaskById(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(() => {

      })
    },
    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 = '稽核完成';
      }
    },
    // 关停标签处理
    shutdownLabelSpan(text,record){
      let value = '';
      if (text){
        text = text.split(",")
        if (text.indexOf("0") > -1){
          value = value + " " + "安防停机（高危漫游地）";
        }
        if (text.indexOf("1") > -1){
          value = value + " " + "安防关停（紫名单）";
        }
        if (text.indexOf("2") > -1){
          value = value + " " + "安防停机（专班研判）";
        }
        if (text.indexOf("3") > -1){
          value = value + " " + "安防停机（可复开）";
        }
        if (text.indexOf("4") > -1){
          value = value + " " + "沉默移动卡保护性单停 ";
        }
        if (text.indexOf("5") > -1){
          value = value + " " + "集团一点停复机（单停） ";
        }
        if (text.indexOf("6") > -1){
          value = value + " " + "大数据保护停机单停 ";
        }
        if (text.indexOf("7") > -1){
          value = value + " " + "工信部断卡单停 ";
        }
        if (text.indexOf("8") > -1){
          value = value + " " + "实人核验未通过关停（单停） ";
        }
        if (text.indexOf("999") > -1){
          if (record.shutdownLabelOther){
            value = value + " " + "其它:"+ record.shutdownLabelOther;
          }
        }
      }
      return value
    },
    // 一键下载资料
    getFileUrls(data) {
      let url = this.url.queryUrlById;
      let params = {
        id: data.id
      }
      let that = this;
      getAction(url, params).then(res => {
        if (res.success) {
          that.fileInfoList = res.result
          this.filesToRar(this.fileInfoList, '客户:'+data.customerName+'资料下载');
        }else {
          this.$message.warning('该客户没有资料')
        }
      })
    },
    /**文件打包* arrImages:文件list:[{fileUrl:文件url,renameFileName:文件名}]* filename 压缩包名* */
    filesToRar(arrImages, filename) {
      let _this = this;
      let zip = new JSZip();
      let cache = {};
      let promises = [];
      _this.title = '正在加载压缩文件';
      // const loading = this.$loading({lock: true,text: '正在加载压缩文件',spinner: 'el-icon-loading',background: 'rgba(0, 0, 0, 0.7)'});
      for (let item of arrImages) {
        for (let url of item.fileStaticUrl) {

          console.log("item",item)
          // 下载文件, 并存成ArrayBuffer对象
          const promise = this.getImgArrayBuffer(url.fileStaticUrl).then(data => {
            var testZip = zip.folder(item.fileId);
            // 获取文件名
            const file_name = url.fileName
            // 逐个添加文件
            testZip.file(file_name, data, { binary: true })
            //testZip.file(file_name,item.fileId)
            cache[file_name] = data})
          promises.push(promise);
        }
      }
      Promise.all(promises)
        // 生成二进制流
        .then(() => {zip.generateAsync({ type: "blob" })
          .then(content => {_this.title = '正在压缩';
            // 利用file-saver保存文件  自定义文件名
            FileSaver.saveAs(content, filename);
            _this.title = '压缩完成';}
          );
        }).catch(res=>{
        _this.$message.error('文件压缩失败');
      });
    },
    getImgArrayBuffer(url) {
      return new Promise((resolve, reject) => {
        //通过请求获取文件blob格式
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
          if (this.status == 200) {
            resolve(this.response);
          } else {
            reject(this.status);
          }};
        xmlhttp.send();
      });
    },
  }
}
</script>

<style scoped>

</style>