<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="cerType">
          <el-select v-model="individualCaseForm.cerType" placeholder="请选择证件类型" style="width: 100%">
            <el-option label="身份证" value="1" />
            <el-option label="护照" value="2" />
            <el-option label="港澳台居民居住证" value="3" />
            <el-option label="其他" value="9" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="cerNo">
          <el-input v-model="individualCaseForm.cerNo" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="姓名" prop="inv">
          <el-input v-model="individualCaseForm.inv" 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 {
  xrSeriousIllegalPersonSpeListList,
  xrSeriousIllegalPersonSpeListSaveIvdAcceptList,
  xrSeriousIllegalPersonSpeListNullify
} from '@/api/auto-baseapi'
import Doc from './doc.vue'
export default {
  components: {
    Doc
  },
  data() {
    return {
      type: this.$route.meta.type,
      authItemMap: [],
      data: [],
      // 添加个案主体办理相关数据
      individualCaseDialogVisible: false,
      individualCaseForm: {
        cerType: '',
        cerNo: '',
        inv: ''
      },
      individualCaseRules: {
        cerType: [
          { required: true, message: '请选择证件类型', trigger: 'change' }
        ],
        cerNo: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ],
        inv: [
          { 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: 'inv',
          span: 6,
          tableProps: {
            minWidth: '250px',
            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: 'status',
          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/naturalPerson/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 = {
        cerType: '',
        cerNo: '',
        inv: ''
      }
      this.$nextTick(() => {
        this.$refs.individualCaseForm && this.$refs.individualCaseForm.clearValidate()
      })
    },
    handleIndividualCaseClose() {
      this.individualCaseDialogVisible = false
    },
    submitIndividualCase() {
      this.$refs.individualCaseForm.validate((valid) => {
        if (valid) {
          this.$message.info('正在创建业务，请稍后...')
          // 调用 saveIvdAcceptList 接口创建业务
          xrSeriousIllegalPersonSpeListSaveIvdAcceptList({
            cerNo: this.individualCaseForm.cerNo,
            inv: this.individualCaseForm.inv,
            cerType: this.individualCaseForm.cerType
          }).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/naturalPerson/inclusion/${this.type}/handle`,
              query: {
                bizSeqNo: data.bizSeqId,
                cerNo: this.individualCaseForm.cerNo
              }
            })
          }).catch((error) => {
            this.$message.error('业务创建失败: ' + (error.message || '未知错误'))
          })
        }
      })
    },
    searchLoader(pageParam, parseSearchFormData, instance) {
      const isTodo = this.$route.meta.type === 'todo'
      return xrSeriousIllegalPersonSpeListList({
        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 || []
        return {
          tableData: records,
          total: data.total || 0
        }
      })
    },
    handle(row) {
      // 跳转到办理/查看页面，使用 bizSeqNo 作为业务号
      const bizSeqNo = row.bizSeqNo
      if (!bizSeqNo) {
        this.$message.error('业务号不存在，无法查看')
        return
      }
      return this.$router.push({
        path: `/illegal/naturalPerson/inclusion/${this.type}/handle`,
        query: {
          bizSeqNo: bizSeqNo,
          cerNo: row.cerNo
        }
      })
    },
    print(row) {
      // 打印功能：通过 getApprovalFormByBizSeqNo 获取数据
      // TODO: 调用 xrSeriousIllegalPersonSpeListGetApprovalFormByBizSeqNo 获取审批表数据
      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 xrSeriousIllegalPersonSpeListNullify({
          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>
