<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>

    <!-- 添加个案主体办理按钮 -->
    <div style="margin-bottom: 16px;">
      <el-button
        v-if="type === 'todo'"
        type="primary"
        icon="el-icon-plus"
        @click="handleIndividualCase"
      >
        个案主体办理
      </el-button>
    </div>

    <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: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="individualCaseDialogVisible"
      width="500px"
      :before-close="handleIndividualCaseClose"
    >
      <el-form
        ref="individualCaseForm"
        :model="individualCaseForm"
        :rules="individualCaseRules"
        label-width="130px"
      >
        <el-form-item label="统一社会信用代码" prop="uniscId">
          <el-input v-model="individualCaseForm.uniscId" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="注册号" prop="regNo">
          <el-input v-model="individualCaseForm.regNo" placeholder="请输入注册号" />
        </el-form-item>
        <el-form-item label="主体名称" prop="entName">
          <el-input v-model="individualCaseForm.entName" placeholder="请输入主体名称" />
        </el-form-item>
        <el-form-item label="登记机关" prop="regOrg">
          <el-cascader
            v-model="individualCaseForm.regOrg"
            :options="orgs"
            :props="{ checkStrictly: true, value: 'orgUnitId', label: 'label' }"
            placeholder="请选择登记机关"
            clearable
            filterable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="法人" prop="leRep">
          <el-input v-model="individualCaseForm.leRep" placeholder="请输入法人" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleIndividualCaseClose">取 消</el-button>
        <el-button type="primary" @click="submitIndividualCase">提 交</el-button>
      </div>
    </el-dialog>
    <Doc ref="doc" />
  </div>
</template>

<script>
import {
  eOtIlldisdetailEnterTaskList,
  eOtIlldisdetailEnterFinishedList,
  eOtIlldisdetailEnterCaseHandle,
  eOtIlldisdetailNullify,
  userGetOrgunits,
  eOtIlldisdetailPrintTSWrit
} from '@/api/auto-baseapi'
import Doc from './doc.vue'
import { isTaskCreater } from '@/api'
export default {
  components: {
    Doc
  },
  data() {
    return {
      type: this.$route.meta.type,
      authItemMap: [],
      data: [],
      orgs: [],
      // 添加个案主体办理相关数据
      individualCaseDialogVisible: false,
      individualCaseForm: {
        uniscId: '',
        regNo: '',
        entName: '',
        regOrg: '',
        leRep: ''
      },
      individualCaseRules: {
        uniscId: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
        ],
        regNo: [
          { required: true, message: '请输入注册号', trigger: 'blur' }
        ],
        entName: [
          { required: true, message: '请输入主体名称', trigger: 'blur' }
        ]
      },
      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: 'dedocnum',
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'history'
          },
          tableProps: {
            width: '160px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '单位名称',
          prop: 'busname',
          span: 6,
          tableProps: {
            minWidth: '250px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'date-picker',
          label: '创建日期',
          prop: 'createTime',
          tableSort: 4,
          span: 12,
          showInForm: false,
          showInTable: () => {
            return this.type === 'todo'
          },
          tableProps: {
            width: '120px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '列入日期',
          prop: 'abntime',
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'history'
          },
          tableProps: {
            width: '120px',
            showOverflowTooltip: true
          }
        },
        {
          type: (scope) => {
            const { isSearchForm } = scope.meta
            return isSearchForm ? 'select' : 'slot'
          },
          slotName: 'bus-status',
          label: '业务状态',
          prop: 'busstatus',
          span: 6,
          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/inclusion/${val}`
      })
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$refs.EditTable.search({ reset: true })
      vm.type = vm.$route.meta.type
    })
  },
  methods: {
    // 添加个案主体办理相关方法
    handleIndividualCase() {
      this.individualCaseDialogVisible = true
      this.individualCaseForm = {
        uniscId: '',
        regNo: '',
        entName: '',
        regOrg: '',
        leRep: ''
      }
      // 加载登记机关树
      this.loadOrgunits()
      this.$nextTick(() => {
        this.$refs.individualCaseForm && this.$refs.individualCaseForm.clearValidate()
      })
    },
    loadOrgunits() {
      if (this.orgs.length > 0) return
      userGetOrgunits({}).then(response => {
        if (response.code === 0) {
          this.orgs = response.data || []
        }
      })
    },
    handleIndividualCaseClose() {
      this.individualCaseDialogVisible = false
    },
    submitIndividualCase() {
      this.$refs.individualCaseForm.validate((valid) => {
        if (valid) {
          this.$message.info('正在创建业务，请稍后...')
          // 处理 regOrg，el-cascader 返回的是数组，取最后一个值
          const regorg = Array.isArray(this.individualCaseForm.regOrg)
            ? this.individualCaseForm.regOrg[this.individualCaseForm.regOrg.length - 1]
            : this.individualCaseForm.regOrg
          // 调用 enterCaseHandle 接口创建业务
          eOtIlldisdetailEnterCaseHandle({
            uniscid: this.individualCaseForm.uniscId,
            regno: this.individualCaseForm.regNo,
            entname: this.individualCaseForm.entName,
            regorg: regorg,
            name: this.individualCaseForm.leRep
          }).then((response) => {
            if (response.code !== 0) {
              this.$message.error(response.msg || '业务创建失败')
              return
            }
            const data = response.data || {}
            this.individualCaseDialogVisible = false
            this.$message.success('业务创建成功')
            // 跳转到详情页面
            this.$router.push({
              path: `/illegal/externalUnit/inclusion/${this.type}/handle`,
              query: {
                bizSeqNo: data.bizseq,
                tasklistid: data.tasklistid,
                workflowid: data.workflowId
              }
            })
          }).catch((error) => {
            this.$message.error('业务创建失败: ' + (error.message || '未知错误'))
          })
        }
      })
    },
    searchLoader(pageParam, parseSearchFormData, instance) {
      const isTodo = this.$route.meta.type === 'todo'
      const api = isTodo ? eOtIlldisdetailEnterTaskList : eOtIlldisdetailEnterFinishedList
      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.inBizseq,
            workflowid: item.inWorkflowId,
            createTime: item.abntime
          }
        })
        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.inBizseq
        const workflowid = row.workflowid || row.inWorkflowId
        if (!illid) {
          this.$message.error('记录ID不存在，无法查看')
          return
        }
        return this.$router.push({
          path: `/illegal/externalUnit/inclusion/${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/inclusion/${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.inWorkflowId
      if (!illid) {
        this.$message.error('记录ID不存在，无法打印')
        return
      }
      // 调用打印文书接口
      eOtIlldisdetailPrintTSWrit({
        illid: illid,
        printstatus: '1', // 1-决定书，3-审批表
        type: 'enter', // enter-列入
        workflowid: workflowid
      }).then((response) => {
        if (response.code !== 0) {
          this.$message.error(response.msg || '获取文书数据失败')
          return
        }
        const result = response.data || {}
        // 将接口返回数据映射为 doc.vue 需要的格式
        const docData = {
          // 决定书数据
          incAbnDecisionMap: {
            areaName: result.decorgString || '',
            writsNo: result.wrirsno || '',
            entName: result.ename || result.detail?.entname || '',
            content: result.detail?.serreasons || result.lostCreditExplain || '',
            abnTime: result.detail?.abntime || ''
          },
          // 审批表数据
          entname: result.ename || result.detail?.entname || '',
          uniscid: result.detail?.uniscid || '',
          lostCreditExplain: result.detail?.serreasons || result.lostCreditExplain || '',
          serillrea: result.detail?.serillrea || '',
          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 bizSeqNo = row.bizseqid || row.inBizseq
      const tasklistid = row.tasklistid
      const busname = row.busname || row.entname
      if (!tasklistid) {
        this.$message.warning('该记录无法作废')
        return
      }
      isTaskCreater({
        bizSeqNo: bizSeqNo
      }).then((data) => {
        if (data) {
          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 })
              })
            }
          })
        } else {
          this.$message.warning(`当前用户不是该业务的发起人，无法删除该业务`)
        }
      })
    }
  }
}
</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>
