<template>
  <div class="main-content m20">
    <!--头部-查询-->
    <div class="content-header">
      <searchHeader title="查询" />
      <div class="body search-body">
        <el-row class="mb10">
          <el-col :span="12">
            <label class="label-name" style="width: 220px">统一社会信用代码/注册号：</label>
            <div class="search-input-box" style="width: calc(100% - 220px)">
              <el-input v-model="searchForm.searchCode" clearable type="text" class="search-input" placeholder="请输入统一社会信用代码/注册号" @keyup.enter.native="search" />
            </div>
          </el-col>
          <el-col :span="12">
            <label class="label-name">主体名称：</label>
            <div class="search-input-box">
              <el-input v-model="searchForm.searchEntName" clearable type="text" class="search-input" placeholder="请输入主体名称（模糊）" @keyup.enter.native="search" />
            </div>
          </el-col>
        </el-row>
        <el-row v-if="showMore">
          <el-col :span="12">
            <label class="label-name" style="width: 220px;margin-bottom: 10px">锁定类型：</label>
            <el-select v-model="searchForm.searchLockType" filterable clearable placeholder="请选择" style="width: calc(100% - 220px);">
              <el-option
                v-for="item in lockTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12" :offset="1">
            <div class="btn-box">
              <span v-if="!showMore" style="margin-right:20px;color:#409EFF;cursor:pointer;font-size: 16px;" @click="showMore = true">
                展开<i class="el-icon-d-arrow-right" />
              </span>
              <span v-if="showMore" style="margin-right:20px;color:#409EFF;cursor:pointer;font-size: 16px;" @click="showMore = false">
                <i class="el-icon-d-arrow-left" />隐藏
              </span>
              <el-button type="primary" size="mini" @click="search">查询</el-button>
              <el-button size="mini" @click="searchForm.searchCode = '';searchForm.searchEntName='';searchForm.searchLockType='';">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--body-查询结果-->
    <div class="content-body">
      <div class="body">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 95%;margin:0 auto"
          :fit="true"
          :row-class-name="tableRowClassName"
          :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column class="no" type="selection" min-width="25" align="center" />
          <el-table-column prop="index" label="序号" min-width="40" align="center" />
          <el-table-column prop="uscc" label="统一社会信用代码/注册号" min-width="120" align="left" />
          <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="120" align="left" />
          <el-table-column prop="locktype" :show-overflow-tooltip="true" label="锁定类型" min-width="80" align="left" :formatter="lockTypeFormat" />
          <!-- <el-table-column :show-overflow-tooltip="true" label="锁定状态" min-width="80" align="left" /> -->
          <!--          <el-table-column prop="lockreason" :show-overflow-tooltip="true" label="锁定原因" min-width="200" align="left"  />-->
          <el-table-column prop="orgunit" :show-overflow-tooltip="true" label="锁定机关" min-width="100" align="left"  />
          <el-table-column prop="punishFrom" :show-overflow-tooltip="true" label="惩戒来源" min-width="100" align="left" :formatter="punishFromFormat" />
          <!--          <el-table-column prop="ulockSpecificReason" :show-overflow-tooltip="true" label="解锁原因" min-width="150" align="left" />-->
          <el-table-column prop="lockusername" label="锁定人" min-width="60" align="left" />
          <el-table-column prop="lockstartdate" :show-overflow-tooltip="true" label="锁定时间" min-width="90" align="left" :formatter="dateTimeFormat" />
          <!-- <el-table-column label="锁定开始日期" min-width="100" align="left" />
          <el-table-column label="锁定结束日期" min-width="100" align="left" /> -->
          <!-- <el-table-column label="操作" min-width="100" align="left">
            <template slot-scope="scope">
              <i style="margin-right: 5px" class="el-icon-view icon" />
              <i style="margin-right: 5px" class="el-icon-edit icon" />
              <i class="el-icon-lock icon" />
            </template>
          </el-table-column> -->
        </el-table>
        <div class="page-box">
          <el-row>
            <el-col :span="6">
              <el-button size="mini" @click="selectAll">全选</el-button>
              <el-button size="mini" @click="$util.toggleSelect($refs.multipleTable)">反选</el-button>
              <el-button size="mini" type="primary" @click="startTask">办理</el-button>
              <!--<el-button size="mini" type="primary" @click="templateDialog = true">导入</el-button>-->
            </el-col>
            <el-col :span="18">
              <el-pagination
                :disabled="loading"
                :page-size="pageParam.pageSize"
                :total="pageParam.total"
                :page-sizes="[10, 20, 30, 40,50,100,200]"
                layout="slot,total, sizes, prev, pager, next, jumper"
                @size-change="pageSizeChange"
                @current-change="pageIndexChange"
              >
                <!-- <batchFunction :options="options" style="float:left" /> -->
                <span>
                  第 {{ pageParam.curPage }} 页 /
                  共 {{ (pageParam.total !== 0 ? parseInt((pageParam.total + pageParam.pageSize - 1)/pageParam.pageSize) : 1) }} 页
                </span>
              </el-pagination>
            </el-col>
          </el-row>
        </div>
        <!--分页多选组件-->
        <!-- <pageSelector :selection="selection" :columns="selectionColumn" @removeCallback="removeCallback" /> -->
      </div>
    </div>
    <el-dialog
      title="联合惩戒解锁导入"
      :visible.sync="templateDialog"
      width="50%"
    >
      <el-row class="mb10" style="margin-bottom:10px">
        <el-row class="mb10" style="margin-bottom:10px">
          <span>请选择惩戒措施再上传文件</span>
        </el-row>
        <label class="label-name" style="width: 80px">惩戒措施：</label>
        <el-select v-model="measure" filterable clearable placeholder="请选择" style="width: calc(100% - 100px);">
          <el-option
            v-for="item in punishmeasures"
            :key="item.measureId"
            :label="item.measure"
            :value="item.measure"
          />
        </el-select>
      </el-row>
      <el-row class="mb10" style="margin-bottom:10px">
        <el-col span="6">
          <el-upload
            :limit="1"
            :action="uploadPath"
            :data="{'measure':measure}"
            :on-exceed="checkNum"
            :before-upload="uploadCheck"
            :on-success="uploadCallback"
            :on-remove="remFileCallback"
            accept=".xls,.xlsx"
            multiple
            :file-list="fileList"
            class="templateUpload"
          >
            <el-link
              style="font-size: medium;margin-top: 10px"
              type="primary"
            >上传文件</el-link>
          </el-upload>
        </el-col>
        <el-col span="6">
          <el-link
            style="font-size: medium;margin-top: 10px"
            type="primary"
            @click="downLoadTemp"
          >下载模板</el-link>
        </el-col>

      </el-row>
      <el-row v-if="isUpload" class="mb10" style="margin-bottom:10px">
        <span style="font-size: medium">导入总数:<span>{{ count }}</span>   成功数量:<span>{{ successList.length }}</span>   失败数量:<span>{{ failList.length }}</span></span>
      </el-row>
      <el-row v-if="isUpload && failList.length > 0">
        <el-link type="primary" style="font-size: medium" @click="showFailList">查看失败名单</el-link>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button v-loading="uploadDataLoading" type="primary" @click="uploadData">确定上传 </el-button>
        <el-button @click="templateDialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="校验不通过的数据" :visible.sync="isShowFailList" width="50%" @close="isShowFailList = false">
      <div v-if="failList.length >0">
        <el-button @click="downE(failList)">导出</el-button>
      </div>
      <el-table
        ref="multipleTable"
        :data="dataShow"
        tooltip-effect="dark"
        style="width: 100%;padding: 0"
        :fit="true"
        :header-cell-style="{background:'#8cc3fb',color:'#fff'}"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="uniscid" :show-overflow-tooltip="true" label="统一社会信用代码" min-width="120" align="left" />
        <el-table-column prop="regno" :show-overflow-tooltip="true" label="注册号" min-width="120" align="left" />
        <el-table-column prop="entname" :show-overflow-tooltip="true" label="主体名称" min-width="120" align="left" />
        <el-table-column prop="reason" :show-overflow-tooltip="true" label="失败原因" />
      </el-table>
      <el-row>
        <el-col style="text-align: right">
          <el-pagination
            :current-page="currentPage"
            small
            layout="prev, pager, next"
            :total="failList.length"
            :page-size="pageSizeFail"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import searchHeader from '@/components/searchHeader'
import pageSelector from '@/components/PageSelector'
import {
  getPunishFromList,
  saveUnlockAccept,
  toUnLockEntListPage,
  getLockTypeList,
  unLockExportExcel,
  queryAllPunishMeasures,
  saveAcceptByUpload,
  getDepartmentList,
  queryOrgDept
} from '@/api/punishment'
export default {
  components: {
    pageSelector: pageSelector,
    searchHeader
  },
  data() {
    return {
      uploadDataLoading: false,
      uploadPath: `${process.env.VUE_APP_BASE_API}/tsbizpunishunlock/upload`,
      templateDialog: false,
      lockTypeOptions: [],
      selection: [],
      fileList: [],
      selectionColumn: [{ label: '序号', type: 'index' }, { label: '统一社会信用代码/注册号', prop: 'uscc' }, { label: '主体名称', prop: 'entname' }],
      searchForm: {
        entertype: 'company',
        searchUscc: '',
        searchName: '',
        reportYear: ''
      },
      loading: false,
      tableData: [],
      pageParam: {
        customParamMap: { entertype: 'company' },
        curPage: 1,
        total: 0,
        pageSize: 10
      },
      isUpload: false,
      successList: [],
      failList: [],
      dataShow: [],
      pageNum: '',
      pageSizeFail: 4,
      totalPageData: [],
      currentPage: 1,
      isShowFailList: false,
      punishmeasures: [],
      measure: '',
      showMore: false,
      departmentList: []
    }
  },
  mounted() {
    // 加载锁定类型
    this.lockTypeOptions = getLockTypeList()
    this.departmentList = getDepartmentList()
    this.punishFromList = getPunishFromList()
    queryAllPunishMeasures().then(res => {
      this.punishmeasures = res.data
    })
    // this.loadPage()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      }
    },
    calcPageData(dataList) {
      if (dataList.length >= 1) {
        this.pageNum = Math.ceil(dataList.length / this.pageSizeFail) || 1
      }
      // 数据分组
      for (let i = 0; i < this.pageNum; i++) {
        this.totalPageData[i] = dataList.slice(this.pageSizeFail * i, this.pageSizeFail * (i + 1))
      }
      this.dataShow = this.totalPageData[this.currentPage - 1]
    },
    // 当前页码发生变化
    handleCurrentChange(newPageNum) {
      this.currentPage = newPageNum
      this.dataShow = this.totalPageData[newPageNum - 1]
    },
    downE(data) {
      unLockExportExcel(data).then(res => {
        this.download2(res, '联合惩戒解锁导入失败数据.xls')
      }).catch(req => {
        console.log('下载失败', req)
      })
    },
    download2(data, fileName) {
      if (!data) {
        return
      }
      console.log(data)
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8' }))
      // window.open(url)
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      // document.body.appendChild(link)
      link.click()
    },
    showFailList() {
      this.isShowFailList = true
    },
    remFileCallback() {
      this.isUpload = false
      this.count = ''
      this.failList = []
      this.successList = []
    },
    // 上传数据
    uploadData() {
      if (this.successList.length === 0) return this.$message.warning('无可导入数据')
      this.uploadDataLoading = true
      saveAcceptByUpload(this.successList).then(res => {
        this.uploadDataLoading = false
        if (res.code === 0) {
          this.$router.push({ path: '/punish/remove/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.uploadDataLoading = false
      })
    },
    checkNum(files, fileList) {
      return this.$message.warning('只能上传单个文件')
    },
    uploadCheck(file) {
      if (this.measure === '') {
        this.$message.warning('请先选择惩戒措施')
        return false
      }
    },
    uploadCallback(res, file) {
      if (res.code === 0) {
        // this.$router.push({ path: '/punish/remove/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
        this.successList = res.data.successList
        this.failList = res.data.failList
        this.count = res.data.count
        this.isUpload = true
        this.calcPageData(this.failList)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 模板下载
    downLoadTemp() {
      const name = 'unlock_list.xls'
      window.open(process.env.NODE_ENV === '"development"' ? `/${name}` : `/aiccs/${name}`)
    },
    dateTimeFormat(row) {
      return this.$util.formatDate.format(new Date(Date.parse(row.lockTime || row.lockstartdate)), 'yyyy-MM-dd hh:mm:ss')
    },
    lockTypeFormat(row) {
      let name = ''
      this.lockTypeOptions.forEach(each => {
        if (each.value === row.locktype) {
          name = each.label
        }
      })
      return name
    },
    departmentFormat(row) {
      return this.$util.enumFormatter(this.departmentList, row.department)
    },
    punishFromFormat(row) {
      let name = ''
      this.punishFromList.forEach(each => {
        if (each.value === row.punishFrom) {
          name = each.label
        }
      })
      return name
    },
    // 启动待办
    startTask() {
      if (this.selection.length === 0) return this.$message.error('请至少选择一个企业以开启待办')
      this.$confirm('是否确认启动待办', '提示').then(() => {
        let ids = ''
        debugger
        this.selection.forEach(each => {
          if (each.elid !== null) {
            ids += (each.elid + ';')
          }
          if (each.plid !== null) {
            ids += (each.plid + ';')
          }
        })
        saveUnlockAccept(ids.substring(0, ids.length - 1)).then(res => {
          if (res.code === 0) {
            this.$router.push({ path: '/punish/remove/accept', query: { tasklistid: res.data.tasklistid, bizseq: res.data.bizseq, workflowId: res.data.workflowId }})
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    // 搜索
    search() {
      this.pageParam.customParamMap = this.searchForm
      this.pageParam.curPage = 1
      this.loadPage()
    },
    // 分页多选插件回调
    removeCallback(index, row) {
      this.$refs.multipleTable.toggleRowSelection(row, false)
    },
    // 全选按钮事件
    selectAll() {
      const table = this.$refs.multipleTable
      for (const i in table.data) {
        const each = table.data[i]
        table.toggleRowSelection(each, true)
      }
    },
    // 选项变更事件
    handleSelectionChange(selectData) {
      const cancel = []
      if (selectData.length !== this.tableData.length) {
        // 找出没有选中的内容
        this.tableData.forEach(each => {
          for (const i in selectData) {
            const atom = selectData[i]
            if (atom.pripid === each.pripid) {
              return
            }
          }
          cancel.push(each)
        })
      }
      // 取消选中的内容
      for (const i in cancel) {
        const each = cancel[i]
        let index
        for (const j in this.selection) {
          const select = this.selection[j]
          if (select.pripid === each.pripid) {
            index = parseInt(j)
            break
          }
        }
        if (index !== undefined) {
          this.selection.splice(index, 1)
        }
      }
      // 增加选中内容
      for (const i in selectData) {
        const each = selectData[i]
        let exist = false
        for (const j in this.selection) {
          const select = this.selection[j]
          if (select.pripid === each.pripid) {
            exist = true
            break
          }
        }
        if (!exist) {
          this.selection.push(each)
        }
      }
    },
    // 当前分页改变
    pageIndexChange(curPage) {
      this.pageParam.curPage = curPage
      this.loadPage()
    },
    // 分页大小改变
    pageSizeChange(pageSize) {
      this.pageParam.pageSize = pageSize
      this.loadPage()
    },
    // 加载分页
    loadPage() {
      if (this.loading) return
      this.loading = true
      toUnLockEntListPage(this.pageParam).then(res => {
        debugger
        this.loading = false
        const list = []
        let i = 1
        const pageStart = (this.pageParam.curPage - 1) * this.pageParam.pageSize
        res.data.records.forEach(each => {
          debugger
          each.index = pageStart + i++
          each.uscc = each.uniscid || each.regno
          if (each.punishFrom === null) {
            each.punishFrom = 9
          }
          queryOrgDept(each.lockuserunitid).then(res => {
            if (res.data !== null) {
              each.orgunit = res.data.orgUnitName
            }
          })
          list.push(each)
        })
        this.tableData = list
        this.pageParam.total = res.data.total
        const selection = JSON.parse(JSON.stringify(this.selection))
        this.$nextTick(() => {
          for (const i in list) {
            const each = list[i]
            for (const j in selection) {
              if (each.pripid === selection[j].pripid) {
                this.$refs.multipleTable.toggleRowSelection(each, true)
              }
            }
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-content{
  background: #fff;
  padding: 10px;
  .content-header{
    background: white;
    .label-name {
      text-align: right;
      display: inline-block;
      width: 120px;
      font-size: $table-content-font-size;
    }
    .search-input-box{
      display: inline-block;
      width: calc(100% - 150px);
    }
    .search-input{
      cursor: pointer;
    }
    .body{
      padding: 20px 0 ;
      border-top:none;
      margin-bottom: 40PX;
    }
  }
  .content-body{
    background:white;
  }
  .header{
    /* height:50PX; */
    /* padding:15PX 10PX; */
    .title{
      font-weight: 600;
      font-size: 1.2rem;
    }
  }
    .icon{
    font-size: 50px;
    color: rgb(24, 144, 255);
  }
  .page-box{
    margin:10PX;
    .el-pagination{
      text-align: right;
    }
  }
}
/deep/.el-input__inner{
  height: 28px;
}
/deep/.label-name{
  text-align: right;
}
</style>
