<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.naturalPersonList.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>
    <NaturalPersonList ref="naturalPersonList" :type="$route.meta.type" @confirm="onSelectEnt" />
    <Doc ref="doc" />
  </div>
</template>

<script>
import Doc from './doc.vue'
import NaturalPersonList from '../components/NaturalPersonList.vue'
import {
  xrSeriousIllegalPersonRemListList,
  xrSeriousIllegalPersonRemListSaveIvdAccept,
  xrSeriousIllegalPersonRemListNullify,
  userGetOrgunits
} from '@/api/auto-baseapi'

export default {
  components: {
    NaturalPersonList,
    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: 'remWritId',
          span: 6,
          showInForm: false,
          showInTable: () => {
            return this.type === 'history'
          },
          tableProps: {
            width: '160px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '证件号码',
          prop: 'cerNo',
          span: 8,
          showInForm: false,
          tableProps: {
            minWidth: '180px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '自然人姓名',
          prop: 'inv',
          span: 8,
          tableProps: {
            minWidth: '150px',
            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: 'status',
          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/naturalPerson/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(naturalPersonList) {
      if (naturalPersonList.length > 0) {
        // 获取选中的第一条记录
        const item = naturalPersonList[0]
        this.$confirm('是否确认启动待办', '提示', {
          type: 'info',
          customClass: 'type-1',
          confirmHandlerPromise: () => {
            return xrSeriousIllegalPersonRemListSaveIvdAccept({
              cerNo: item.cerNo,
              inv: item.inv,
              illegalListId: item.illegalListId,
              cerType: '1'
            }).then((response) => {
              if (response.code !== 0) {
                this.$message.error(response.msg || '业务创建失败')
                return
              }
              const data = response.data || {}
              return this.$router.push({
                path: `/illegal/naturalPerson/remove/${this.$route.meta.type}/handle`,
                query: {
                  bizSeqNo: data.bizSeqId,
                  tasklistid: data.taskListId,
                  workflowid: data.workflowId,
                  cerNo: item.cerNo
                }
              })
            })
          }
        })
      } else {
        this.$message.warning(`请选择至少一个主体`)
      }
    },
    searchLoader(pageParam, parseSearchFormData, instance) {
      const isTodo = this.$route.meta.type === 'todo'
      return xrSeriousIllegalPersonRemListList({
        size: pageParam.size,
        current: pageParam.current,
        entity: {
          ...parseSearchFormData,
          busType: isTodo ? 'todo' : 'history'
        }
      }).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) => {
          return item
        })
        return {
          tableData: mappedRecords,
          total: data.total || 0
        }
      })
    },
    handle(row) {
      // 历史记录传递 illid、bizSeqNo、workflowid
      if (this.type === 'history') {
        const illid = row.illegalListId
        const bizSeqNo = row.bizSeqNo
        const workflowid = row.workflowId
        if (!illid) {
          this.$message.error('记录ID不存在，无法查看')
          return
        }
        return this.$router.push({
          path: `/illegal/naturalPerson/remove/${this.type}/handle`,
          query: {
            illid: illid,
            bizSeqNo: bizSeqNo,
            workflowid: workflowid,
            cerNo: row.cerNo
          }
        })
      }
      if (row.status === '6') {
        this.$confirm(`该业务由${row.sendername}转到本单位，转办原因：${row.remarks}`, '提示', {
          type: 'info',
          customClass: 'type-1',
          confirmHandlerPromise: () => {
            this.$message.error('业务创建失败:未知错误')
          }
        })
      } else {
        return this.$router.push({
          path: `/illegal/naturalPerson/remove/${this.type}/handle`,
          query: {
            bizSeqNo: row.bizSeqNo,
            tasklistid: row.tasklistid,
            workflowid: row.workflowid,
            cerNo: row.cerNo
          }
        })
      }
    },
    print(row) {
      // TODO: 调用 xrSeriousIllegalPersonRemListGetApprovalFormByBizSeqNo 获取审批表数据进行打印
      this.$message.info('打印功能待实现')
    },
    cancel(row) {
      this.$prompt('请输入作废原因', '作废确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'type-1',
        inputType: 'textarea',
        inputPlaceholder: '请输入作废原因',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '作废原因不能为空'
          }
          return true
        }
      }).then(({ value }) => {
        return xrSeriousIllegalPersonRemListNullify({
          bizSeqNo: row.bizSeqNo,
          reason: value.trim()
        }).then((response) => {
          if (response.code !== 0) {
            this.$message.error(response.msg || '作废失败')
            return
          }
          this.$message.success('作废成功')
          this.$refs.EditTable.search()
        })
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</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>
