<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"
    >
      <template v-slot:table-top>
        <div v-if="$route.meta.type === 'todo'" style="margin-bottom: 12px;">
          <el-button
            style="background: #32BBD6;"
            type="primary"
            @click="$refs.externalUnitlist.open()"
          >
            个案主体办理
          </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>
    <ExternalUnitList ref="externalUnitlist" :type="$route.meta.type" @confirm="onSelectEnt" />
    <Doc ref="doc" />
  </div>
</template>

<script>
import Doc from './doc.vue'
import ExternalUnitList from '../components/ExternalUnitList.vue'
import {
  eOtIlldisdetailRemoveTaskList,
  eOtIlldisdetailRemoveFinishedList,
  eOtIlldisdetailRemoveCaseHandle,
  eOtIlldisdetailNullify,
  userGetOrgunits,
  eOtIlldisdetailPrintTSWrit
} from '@/api/auto-baseapi'

export default {
  components: {
    ExternalUnitList,
    Doc
  },
  data() {
    return {
      orgs: [],
      type: this.$route.meta.type,
      authItemMap: [],
      data: [],
      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: 'acceptno',
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'todo'
          },
          tableProps: {
            width: '160px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '移出文号',
          prop: 'redocnum',
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'history'
          },
          tableProps: {
            width: '160px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '单位名称',
          prop: 'busname',
          span: 8,
          tableProps: {
            minWidth: '250px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'date-picker',
          label: '创建日期',
          prop: 'createTime',
          tableSort: 4,
          showInForm: false,
          showInTable: () => {
            return this.type === 'todo'
          },
          tableProps: {
            width: '120px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '移出日期',
          prop: 'remdate',
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'history'
          },
          tableProps: {
            width: '120px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'select',
          label: '移出原因',
          prop: 'remexcpres',
          span: 8,
          tableProps: {
            width: '150px',
            showOverflowTooltip: true
          },
          optionsBaseCode: 'CD74'
        },
        {
          type: (scope) => {
            const { isSearchForm } = scope.meta
            return isSearchForm ? 'select' : 'slot'
          },
          slotName: 'bus-status',
          label: '业务状态',
          prop: 'busstatus',
          span: 8,
          showInForm: () => {
            return this.type === 'todo'
          },
          showInTable: () => {
            return this.type === 'todo'
          },
          tableProps: {
            width: '100px',
            showOverflowTooltip: true
          },
          options: () => {
            return [
              { label: '待受理', value: '0' },
              { label: '待审核', value: '1' },
              { label: '待审批', value: '2' },
              { label: '已通过', value: '3' },
              { label: '未通过', value: '4' },
              { label: '已作废', value: '5' },
              { label: '转办', value: '6' },
              { label: '待执法', value: '7' }
            ]
          }
        },
        {
          type: 'buttons',
          showInTable: false,
          hiddenLabel: true,
          label: '搜索操作',
          prop: '搜索操作',
          span: 6,
          formItemProp: {
            labelWidth: '0px'
          },
          buttons: [
            {
              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
                })
              }
            }
          ]
        }
      ],
      selected: []
    }
  },
  watch: {
    type(val) {
      this.$router.replace({
        path: `/illegal/externalUnit/remove/${val}`
      })
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$refs.EditTable.search({ reset: true })
      vm.type = vm.$route.meta.type
    })
  },
  created() {
    this.loadOrgunits()
  },
  methods: {
    loadOrgunits() {
      userGetOrgunits({}).then(response => {
        if (response.code === 0) {
          this.orgs = response.data || []
        }
      })
    },
    onSelectEnt(externalUnitlist) {
      if (externalUnitlist.length > 0) {
        // 获取选中的第一条记录
        const item = externalUnitlist[0]
        this.$confirm('是否确认启动待办', '提示', {
          type: 'info',
          customClass: 'type-1',
          confirmHandlerPromise: () => {
            return eOtIlldisdetailRemoveCaseHandle({
              illid: item.illid || item.illegalListId
            }).then((response) => {
              if (response.code !== 0) {
                this.$message.error(response.msg || '业务创建失败')
                return
              }
              const data = response.data || {}
              return this.$router.push({
                path: `/illegal/externalUnit/remove/${this.$route.meta.type}/handle`,
                query: {
                  bizSeqNo: data.bizseq,
                  tasklistid: data.tasklistid,
                  workflowid: data.workflowId
                }
              })
            })
          }
        })
      } else {
        this.$message.warning(`请选择至少一个主体`)
      }
    },
    searchLoader(pageParam, parseSearchFormData, instance) {
      const isTodo = this.$route.meta.type === 'todo'
      const api = isTodo ? eOtIlldisdetailRemoveTaskList : eOtIlldisdetailRemoveFinishedList
      return api({
        size: pageParam.size,
        current: pageParam.current,
        entity: {
          ...parseSearchFormData
        }
      }).then((response) => {
        if (response.code !== 0) {
          this.$message.error(response.msg || '查询失败')
          return { tableData: [], total: 0 }
        }
        const data = response.data || {}
        const records = data.records || []
        // 对于已办记录，需要映射字段以兼容列表显示和操作
        const mappedRecords = records.map((item) => {
          if (isTodo) {
            return item
          }
          // 历史记录：映射 EOtIlldisdetailTemp对象 字段到列表需要的字段
          return {
            ...item,
            busname: item.entname,
            bizseqid: item.outBizseq,
            workflowid: item.outWorkflowId,
            createTime: item.remdate,
            redocnum: item.redocnum
          }
        })
        return {
          tableData: mappedRecords,
          total: data.total || 0
        }
      })
    },
    handle(row) {
      // 历史记录传递 illid、bizSeqNo、workflowid
      if (this.type === 'history') {
        const illid = row.illid
        const bizSeqNo = row.bizseqid || row.outBizseq
        const workflowid = row.workflowid || row.outWorkflowId
        if (!illid) {
          this.$message.error('记录ID不存在，无法查看')
          return
        }
        return this.$router.push({
          path: `/illegal/externalUnit/remove/${this.type}/handle`,
          query: {
            illid: illid,
            bizSeqNo: bizSeqNo,
            workflowid: workflowid
          }
        })
      }
      if (row.busstatus === '6') {
        this.$confirm(`该业务由${row.sendername}转到本单位，转办原因：${row.remarks}`, '提示', {
          type: 'info',
          customClass: 'type-1',
          confirmHandlerPromise: () => {
            this.$message.error('业务创建失败:未知错误')
          }
        })
      } else {
        return this.$router.push({
          path: `/illegal/externalUnit/remove/${this.type}/handle`,
          query: {
            bizSeqNo: row.bizseqid,
            tasklistid: row.tasklistid,
            workflowid: row.workflowid
          }
        })
      }
    },
    print(row) {
      // 获取 illid 和 workflowid
      const illid = row.illid
      const workflowid = row.workflowid || row.outWorkflowId
      if (!illid) {
        this.$message.error('记录ID不存在，无法打印')
        return
      }
      // 调用打印文书接口
      eOtIlldisdetailPrintTSWrit({
        illid: illid,
        printstatus: '1', // 1-决定书，3-审批表
        type: 'remove', // remove-移出
        workflowid: workflowid
      }).then((response) => {
        if (response.code !== 0) {
          this.$message.error(response.msg || '获取文书数据失败')
          return
        }
        const result = response.data || {}
        // 将接口返回数据映射为 doc.vue 需要的格式
        const docData = {
          // 决定书数据
          repairMap: {
            areaName: result.decorgString || '',
            writsNo: result.wrirsno || '',
            writsName: '移出严重违法失信外单位名单决定书',
            entName: result.ename || result.detail?.entname || '',
            content: result.detail?.remreasons || result.lostCreditExplainrem || '',
            writTime: result.detail?.remdate || ''
          },
          // 审批表数据
          entname: result.ename || result.detail?.entname || '',
          uniscid: result.detail?.uniscid || '',
          lostCreditExplain: result.detail?.remreasons || result.lostCreditExplainrem || '',
          opinion: (result.opinionList || []).map(item => ({
            opinionId: item.opinionid,
            opinionType: item.opiniontype,
            opinionContent: item.opinioncontent,
            handler: item.handler,
            handelDate: item.handledate || item.lauptime
          })),
          remark: result.detail?.remark || ''
        }
        this.$refs.doc.open(docData)
      }).catch((error) => {
        this.$message.error('获取文书数据失败: ' + (error.message || '未知错误'))
      })
    },
    cancel(row) {
      const tasklistid = row.tasklistid
      const busname = row.busname || row.entname
      if (!tasklistid) {
        this.$message.warning('该记录无法作废')
        return
      }
      this.$confirm('是否确定删除该业务', '提示', {
        type: 'info',
        customClass: 'type-1',
        confirmHandlerPromise: () => {
          return eOtIlldisdetailNullify({
            tasklistid: tasklistid,
            reason: '业务作废'
          }).then((response) => {
            if (response.code !== 0) {
              this.$message.error(response.msg || '业务作废失败')
              return
            }
            this.$message.success(`已完成对"${busname}"的业务作废！`)
            this.$refs.EditTable.search({ reset: true })
          })
        }
      })
    }
  }
}
</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>
