<template>
  <div class="page">
    <el-tabs v-model="type" type="card">
      <el-tab-pane label="拟强制注销业务待办" name="todo" />
      <el-tab-pane label="拟强制注销业务记录" name="history" />
    </el-tabs>
    <edit-table
      ref="EditTable"
      v-model="data"
      :table-prop="tableProp"
      :fields="fields"
      :show-search-form="true"
      row-key="id"
      :search-form-prop="searchFormProp"
      :search-loader="searchLoader"
      @update:selected="(value)=>{selected = value}"
    >
      <template v-slot:table-top="EditTable">
        <div style="margin-bottom: 16px;">
          <el-button
            v-if="type === 'todo'"
            type="primary"
            @click="$refs.entlist.open()"
          >
            个案主体办理
          </el-button>
          <el-button
            v-if="type === 'todo'"
            style="background: #48B86E;"
            type="primary"
            @click="templateDialog = true"
          >
            批量导入办理
          </el-button>
        </div>
      </template>
      <template v-slot:bus-status="{ row, field, formatter }">
        <span
          :class="{
            ['bus-status-'+row[field.prop]]: true
          }"
        >
          {{ formatter(row[field.prop]) }}
        </span>
      </template>
    </edit-table>
    <el-dialog
      title="批量导入办理"
      :visible.sync="templateDialog"
      width="30%"
    >
      <el-button
        style="font-size: medium"
        type="primary"
        @click="downLoadTemp"
      >下载模板</el-button>
      <div style="margin-top: 10px">  模板下载，通过下载的模板，填写信息后导入！</div>
      <el-upload
        :action="uploadPath"
        :data="{type: type}"
        :on-success="uploadCallback"
        :on-error="errorCallback"
        :before-upload="beforeUpload"
        accept=".xls,.xlsx"
        multiple
        :file-list="fileList"
        class="templateUpload"
        :show-file-list="false"
      >
        <el-button
          style="font-size: medium;margin-top: 10px"
          type="primary"
        >上传文件
        </el-button>
      </el-upload>
      <div style="margin-top: 10px">  上传文件，填写好的模板，然后点击上传！</div>
      <FakeProgress v-if="showFakeProgress" ref="FakeProgress" style="margin-top: 10px;" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="templateDialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <EntList ref="entlist" :type="$route.meta.type" @confirm="onSelectEnt" />
    <Doc ref="doc" />
  </div>
</template>

<script>
import {
  getOrgunits
} from '@/api/abnormal'
import Doc from './doc.vue'
import EntList from '../component/EntList.vue'
import {
  xrForceDeregisterSpeSaveIvdAcceptNew,
  xrForceDeregisterSpeList,
  xrForceDeregisterSpeProcessControl, xrForceDeregisterGetApprovalFormByBizSeqNo, isTaskCreater
} from '@/api/force'
import FakeProgress from '@/components/FakeProgress'
import axios from 'axios'
export default {
  components: {
    FakeProgress,
    Doc,
    EntList
  },
  data() {
    return {
      orgs: [],
      type: this.$route.meta.type,
      authItemMap: [],
      data: [],
      isExSearch: false,
      templateDialog: false,
      showFakeProgress: false,
      fileList: [],
      uploadPath: process.env.VUE_APP_BASE_API + '/XrForceDeregisterSpe/fileParamExplainLr',
      tableProp: {
        emitLoadOnCreate: true,
        tableConfig: {
          showIndex: true,
          indexWidth: '100px',
          handlerWidth: '120px',
          showPagination: true,
          tableProps: {
            headerCellStyle: { background: '#F5F5F5!important', color: '#333333!important', padding: '0px' },
            headerRowStyle: { height: '48px' },
            rowStyle: { height: '48px' },
            cellStyle: { padding: '16px 0', color: '#333' }
          }
        },
        buttons: [
          {
            label: '办理',
            type: 'text',
            show: () => {
              return this.type === 'todo'
            },
            handler: (scope, { row }) => {
              this.handle(row)
            }
          },
          {
            label: '详细',
            type: 'text',
            show: () => {
              return this.type === 'history'
            },
            handler: (scope, { row }) => {
              this.handle(row)
            }
          },
          {
            label: '查看公告',
            type: 'text',
            show: (scope, { row }) => {
              return this.type === 'history'
            },
            handler: (scope, { row }) => {
              this.print(row)
            }
          },
          {
            label: '作废',
            type: 'text',
            show: () => {
              return this.type === 'todo'
            },
            handler: (scope, { row }) => {
              this.cancel(row)
            }
          }
        ]
      },
      searchFormProp: {
        formConfig: {
          labelWidth: '100px',
          labelPosition: 'right',
          gutter: 32
        }
      },
      fields: [
        {
          type: 'input',
          label: '统一社会信用代码/注册号',
          prop: 'searchUscc',
          span: 6,
          tableSort: 1,
          tableProps: {
            width: '180px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.uniscId || row.regNo}`
            }
          },
          showInTable: () => {
            return this.type === 'history'
          }
        },
        {
          type: 'input',
          label: '主体名称',
          prop: 'entName',
          span: 6,
          tableProps: {
            width: '200px',
            showOverflowTooltip: true
          },
          showInTable: () => {
            return this.type === 'history'
          }
        },
        {
          type: 'input',
          label: '受理号',
          prop: 'acceptNo',
          span: 6,
          tableProps: {
            showOverflowTooltip: true
          },
          showInTable: () => {
            return this.type === 'todo'
          },
          showInForm: false
        },
        {
          type: 'input',
          label: '业务名称',
          prop: 'busName',
          span: 6,
          tableProps: {
            showOverflowTooltip: true
          },
          showInTable: () => {
            return this.type === 'todo'
          },
          showInForm: false
        },
        {
          type: 'date-picker',
          label: '发起日期',
          prop: 'applyTime',
          tableSort: 4,
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'todo'
          }
        },
        {
          type: 'date-picker',
          label: '拟强制注销结果日期',
          prop: 'forceResDate',
          tableSort: 4,
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'history'
          }
        },
        {
          type: 'select',
          label: '法定事由',
          prop: 'forceRra',
          span: 6,
          tableProps: {
            showOverflowTooltip: true
          },
          optionsBaseCode: 'C13042'
        },
        {
          type: 'buttons',
          showInTable: false,
          hiddenLabel: true,
          label: '搜索操作',
          prop: '搜索操作',
          span: 6,
          formItemProp: {
            labelWidth: '0px'
          },
          buttons: [
            {
              label: (scope) => {
                return this.isExSearch ? '收起' : '展开'
              },
              rightIcon: (scope) => {
                return this.isExSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              },
              type: 'text',
              handler: (scope) => {
                this.isExSearch = !this.isExSearch
              }
            },
            {
              label: '查询',
              type: 'primary',
              handler: (scope) => {
                const { meta } = scope
                const { _editTable } = meta
                const { editTableInstance } = _editTable
                editTableInstance.search()
              }
            },
            {
              label: '重置',
              type: 'primary',
              buttonProps: {
                plain: true
              },
              handler: (scope) => {
                const { meta } = scope
                const { _editTable } = meta
                const { editTableInstance } = _editTable
                editTableInstance.search({
                  reset: true
                })
              }
            }
          ]
        },
        {
          type: (scope) => {
            const { isSearchForm } = scope.meta
            return isSearchForm ? 'select' : 'slot'
          },
          slotName: 'bus-status',
          label: '业务状态',
          prop: 'status',
          span: 6,
          showInForm: () => {
            return this.isExSearch
          },
          options: () => {
            return [
              { label: '待受理', value: '0' },
              { label: '待审核', value: '1' },
              { label: '待审批', value: '2' },
              { label: '已通过', value: '3' },
              { label: '未通过', value: '4' },
              { label: '已作废', value: '5' },
              { label: '转办', value: '6' }
            ]
          }
        },
        {
          type: 'input',
          label: '决定机关',
          prop: 'judauthCn',
          showInTable: () => {
            return this.type === 'history'
          },
          showInForm: false
        }
      ],
      selected: []
    }
  },
  watch: {
    type(val) {
      this.$router.replace({
        path: `/forceNotice/inclusion/${val}`
      })
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$refs.EditTable.search({ reset: true })
      vm.type = vm.$route.meta.type
    })
  },
  created() {
    this.getOrgunits()
  },
  methods: {
    getOrgunits() {
      getOrgunits().then(res => {
        this.orgs = res
      })
    },
    searchLoader(pageParam, parseSearchFormData, instance) {
      return xrForceDeregisterSpeList({
        size: pageParam.size,
        current: pageParam.current,
        entity: {
          ...parseSearchFormData,
          busType: this.$route.meta.type,
          forceType: '1'
        }
      }).then((data) => {
        return {
          tableData: data.records,
          total: data.total
        }
      })
    },
    onSelectEnt(entlist) {
      if (entlist.length > 0) {
        this.$confirm('是否确认启动拟强制注销业务', '提示', {
          type: 'info',
          customClass: 'type-1',
          confirmHandlerPromise: () => {
            return xrForceDeregisterSpeSaveIvdAcceptNew({
              pripIdList: entlist.map((item) => {
                return item.pripId
              }),
              busType: 'inclusion'
            }).then((data) => {
              return this.$router.push({
                path: `/forceNotice/inclusion/${this.$route.meta.type}/handle`,
                query: {
                  bizSeqNo: data.bizSeqId
                }
              })
            })
          }
        })
      } else {
        this.$message.warning(`请选择至少一个主体`)
      }
    },
    handle(row) {
      if (row.status === '6') {
        this.$confirm(`该业务由${row.openName}转到本单位，转办原因：${row.transferReason}`, '提示', {
          type: 'info',
          customClass: 'type-1',
          confirmHandlerPromise: () => {
            this.$message.error('业务创建失败:未知错误')
          }
        })
      } else {
        return this.$router.push({
          path: `/forceNotice/inclusion/${this.$route.meta.type}/handle`,
          query: {
            bizSeqNo: row.bizSeqNo
          }
        })
      }
    },
    print(row) {
      xrForceDeregisterGetApprovalFormByBizSeqNo({
        bizSeqNo: row.bizSeqNo,
        forceSpeId: row.forceSpeId
      }).then((data = {}) => {
        this.$refs.doc.open(data)
      })
    },
    cancel(row) {
      isTaskCreater({
        bizSeqNo: row.bizSeqNo
      }).then((data) => {
        if (data) {
          this.$confirm('是否确定删除该业务', '提示', {
            type: 'info',
            customClass: 'type-1',
            confirmHandlerPromise: () => {
              return xrForceDeregisterSpeProcessControl({
                xrForceDeregisterSpe: row,
                forceType: '1',
                bizSeqNo: row.bizSeqNo,
                nextNodeID: 'nullify',
                nextPerformerIds: [],
                opinion: {
                  opinionContent: '业务作废'
                }
              }).then((data) => {
                this.$message.success(`已完成对“${row.busName}”的业务作废！`)
                this.$router.go(0)
              })
            }
          })
        } else {
          this.$message.warning(`当前用户不是该业务的发起人，无法删除该业务`)
        }
      })
    },
    // 模板下载
    downLoadTemp() {
      const name = 'revokeImport.xls'
      window.open(`/aiccs-pc/${name}`)
    },
    errorCallback(file) {
      this.$refs.FakeProgress.error()
      this.showFakeProgress = false
      this.$message.warning('上传文件失败，请检查文件格式或数据，再重新上传，或联系管理员')
    },
    // 上传模板格式Excel之前校验
    beforeUpload(file) {
      this.showFakeProgress = true
      return new Promise((resolve, reject) => {
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if (!extension && !extension2) {
          this.$message({
            message: '上传文件只能是 xls、xlsx格式！',
            type: 'warning'
          })
          this.showFakeProgress = false
          reject()
        } else {
          // 大小判断
          const isLt10M = file.size / 1024 / 1024 < 10
          if (!isLt10M) {
            this.$message({
              message: '上传文件大小不能超过 10MB！',
              type: 'warning'
            })
            this.showFakeProgress = false
            reject()
          } else {
            resolve()
          }
        }
      })
    },
    uploadCallback(res, file) {
      if (res.code === 0) {
        this.$refs.FakeProgress.success()
        setTimeout(() => {
          this.templateDialog = false
          this.showFakeProgress = false
          this.$confirm(`可导数量：${res.data.enableSize} 不可导数量：${res.data.disableSize}`, '导入筛选结果', {
            confirmButtonText: '查看失败清单',
            cancelButtonText: '启动待办',
            distinguishCancelAndClose: true,
            beforeClose: (action, instance, done) => {
              if (action === 'confirm') {
                if (res.data.disableSize === 0) {
                  return this.$message.error('导入失败的数量为0')
                }
                instance.confirmButtonLoading = true
                instance.confirmButtonText = '正在载入，请稍等'
                const baseApi = process.env.VUE_APP_BASE_API
                axios.post(baseApi + '/xrBizSpeList/downLoadDisableList', {
                  disableList: res.data.disableList
                }, {
                  responseType: 'blob' // 指定响应类型为二进制流
                }).then(response => {
                  // 创建一个 Blob 对象
                  const url = window.URL.createObjectURL(new Blob([response.data]))
                  // 创建一个 <a> 标签并设置下载属性
                  const link = document.createElement('a')
                  link.href = url
                  link.setAttribute('download', '导入失败原因清单.xlsx') // 设置下载文件名
                  document.body.appendChild(link)
                  link.click() // 触发下载
                  document.body.removeChild(link) // 移除 <a> 标签
                  instance.confirmButtonLoading = false
                  instance.confirmButtonText = '失败原因清单下载完成'
                }).catch(error => {
                  console.error('下载失败', error)
                })
              } else if (action === 'cancel') {
                if (res.data.enableSize === 0) {
                  return this.$message.error('清单数据为0，无法保存')
                }
                setTimeout(() => {
                  this.onSelectEnt(res.data.enableList)
                })
                done()
              } else if (action === 'close') {
                done()
              }
            }
          })
        }, 1000)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/abnormal-list";
.excel-import{
  margin: 0 auto;
  background: #F9F9F9;
  width: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 24px;
  .excel-tmp-download{
    margin-bottom: 17px;
    .el-button{
      color: #999999;
      margin-right: 24px;
    }
  }
  .filelist-info{
    width: calc(100% - 48px);
    font-size: 16px;
  }
}
.bus-status-0{
  color: #2A8CE3;
}
.bus-status-1{
  color: #32BBD6;
}
.bus-status-2{
  color: #5E7AEB;
}
.bus-status-3{
  color: #48B86E;
}
.bus-status-4{
  color: #F4222D;
}
</style>
