<template>
  <div class="page">
    <edit-table
      ref="EditTable"
      v-model="data"
      :table-prop="tableProp"
      :fields="fields"
      :dialog-prop="dialogProp"
      :show-search-form="true"
      row-key="personateId"
      :search-form-prop="searchFormProp"
      :form-prop="formProp"
      :search-loader="searchLoader"
      @update:selected="(value)=>{selected = value}"
    >
      <template v-slot:divider="scope">
        <div class="divider">
          <span class="text">{{ scope.getPropValue(scope.field.label) }}</span>
        </div>
      </template>
      <template v-slot:table-top>
        <div style="margin-bottom: 12px;">
          <el-button
            style="background: #48B86E;"
            type="primary"
            @click="handleAdd"
          >
            新增公告
          </el-button>
        </div>
      </template>
    </edit-table>
    <EntList
      v-if="entListVisible"
      ref="entList"
      @confirm="handleEntSelect"
      @close="entListVisible = false"
    />
  </div>
</template>

<script>
import {
  eSusNateOperRegListSusNateOperReg,
  eSusNateOperRegAddSusNateOperReg,
  eSusNateOperRegUpdateSusNateOperReg,
  eSusNateOperRegDeleteSusNateOperRegPersonateId
} from '@/api/auto-baseapi.js'
import { getOrgTreeList } from '@/api/system.js'
import EntList from './EntList.vue'
export default {
  components: {
    EntList
  },
  data() {
    return {
      data: [],
      selected: [],
      entListVisible: false,
      tableProp: {
        emitLoadOnCreate: true,
        tableConfig: {
          showIndex: true,
          selection: false,
          indexWidth: '80px',
          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' }
          }
          // indexMethod: (index, scope, defaultIndex) => {
          //   const s = String(defaultIndex)
          //   return `${new Array(3 - s.length).fill('0').join('')}${defaultIndex}`
          // }
        },
        buttons: [
          {
            label: '编辑',
            type: 'text',
            show: true,
            handler: (scope, { row }) => {
              this.$refs.EditTable.editReady(row)
            }
          },
          {
            label: '删除',
            type: 'text',
            show: true,
            handler: (scope, { row }) => {
              this.$confirm('是否确认删除该' + row.name + '涉嫌冒用他人身份取得登记信息', '提示', {
                type: 'info',
                customClass: 'type-1',
                confirmHandlerPromise: () => {
                  return eSusNateOperRegDeleteSusNateOperRegPersonateId({
                    personateId: row.personateId
                  }).then(() => {
                    this.$refs.EditTable.search({ reset: true })
                  })
                }
              })
            }
          }
        ]
      },
      searchFormProp: {
        formConfig: {
          labelWidth: '100px',
          labelPosition: 'right',
          gutter: 32
        }
      },
      formProp: {
        formConfig: {
          labelWidth: '210px',
          labelPosition: 'right',
          gutter: 32,
          buttonPosition: 'right'
        },
        buttons: [
          {
            label: '返回',
            type: 'primary',
            buttonProps: {
              plain: true
            },
            handler: (scope, { row }) => {
              this.$refs.EditTable.cancelEdit()
            }
          },
          {
            label: '保存',
            type: 'primary',
            handler: (scope, { row }) => {
              return scope.formInstance.submitForm().then((formData) => {
                if (!formData.uniscid && !formData.regno) {
                  this.$message.warning('统一社会信用代码和注册号必须填写其中一个')
                  return Promise.reject(new Error('统一社会信用代码和注册号必须填写其中一个'))
                }
                return this.$confirm('是否继续提交', '提示', {
                  type: 'info',
                  customClass: 'type-1'
                })
                  .then(() => {
                    return (() => {
                      if (formData._isAdd) {
                        return eSusNateOperRegAddSusNateOperReg
                      } else {
                        return eSusNateOperRegUpdateSusNateOperReg
                      }
                    })()(formData)
                      .then(() => {
                        this.$refs.EditTable.editConfirm(formData)
                        return this.$refs.EditTable.search({ reset: true })
                      })
                      .catch(error => {
                        this.$message.error('保存失败: ' + (error.message || '未知错误'))
                        throw error
                      })
                  })
                  .catch(error => {
                    // 如果只是取消操作，不抛出错误
                    if (error !== 'cancel') {
                      throw error
                    }
                  })
              })
            }
          }
        ]
      },
      dialogProp: {
        title: (scope) => {
          if (scope.editRowClone && scope.editRowClone._isAdd) {
            return !scope.editRowClone.selected ? '新增涉嫌冒用他人身份取得登记信息' : '新增涉嫌冒用他人身份取得登记信息'
          } else if (scope.editRowClone) {
            return '编辑涉嫌冒用他人身份取得登记信息'
          }
          return '涉嫌冒用他人身份取得登记信息'
        },
        width: '1200px',
        customClass: 'dialog-abnormal-list'
      },
      fields: [
        {
          type: 'input',
          label: '统一社会信用代码/注册号',
          prop: 'searchUscc',
          span: 9,
          tableProps: {
            width: '150px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.uniscid || row.regno || ''}`
            }
          },
          showInForm: ({ meta }) => {
            return meta.isSearchForm === true
          },
          showInTable: true
        },
        {
          type: 'input',
          label: '市场主体名称',
          prop: 'searchEntName',
          span: 9,
          showInForm: ({ meta }) => {
            return meta.isSearchForm === true
          },
          showInTable: false
        },
        {
          type: 'buttons',
          showInTable: false,
          showInForm: ({ meta }) => {
            return meta.isSearchForm === true
          },
          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
                })
              }
            }
          ]
        },
        {
          type: 'divider',
          label: '涉嫌冒用他人身份取得登记信息',
          showInTable: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          }
        },
        {
          type: 'input',
          label: '市场主体名称',
          prop: 'entname',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          tableProps: {
            width: '200px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.entname || ''}`
            }
          },
          showInTable: true
        },
        {
          type: 'input',
          label: '社会统一信用代码',
          prop: 'uniscid',
          required: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'input',
          label: '注册号',
          prop: 'regno',
          required: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'cascader',
          label: '登记机关',
          prop: 'regOrg',
          cnProp: 'regOrgCn',
          required: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          formProps: {
            props: { checkStrictly: true, value: 'id', label: 'label', children: 'children' },
            'show-all-levels': false,
            clearable: true,
            filterable: true
          },
          options: () => {
            return this.orgTreeList
          }
        },
        {
          type: 'input',
          label: '姓名（当事人）',
          prop: 'name',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          tableProps: {
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '联系方式（登记机关联系方式）',
          prop: 'tel',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          tableProps: {
            showOverflowTooltip: true
          },
          showInTable: false
        },
        {
          type: 'date-picker',
          label: '公告期自',
          prop: 'noticeFrom',
          required: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          }
        },
        {
          type: 'date-picker',
          label: '公告期至',
          prop: 'noticeTo',
          required: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          }
        },
        {
          type: 'cascader',
          label: '作出决定机关',
          prop: 'judAuth',
          cnProp: 'judAuthCn',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          formProps: {
            props: { checkStrictly: true, value: 'id', label: 'label', children: 'children' },
            'show-all-levels': false,
            clearable: true,
            filterable: true
          },
          options: () => {
            return this.orgTreeList
          }
        },
        {
          type: 'date-picker',
          label: '做出决定日期',
          prop: 'judDate',
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          },
          tableProps: {
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.judDate || ''}`
            }
          }
        },
        {
          type: 'date-picker',
          label: '冒名登记时间',
          prop: 'regTime',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          }
        },
        {
          type: 'input',
          label: '冒名登记事项',
          prop: 'regItem',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'select',
          label: '处理原因',
          prop: 'handlRea',
          cnProp: 'handlReaCN',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false,
          options: () => {
            return this.handleReasonOptions
          }
        },
        {
          type: 'input',
          label: '处理结果',
          prop: 'handlRest',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        }
        // {
        //   type: 'file',
        //   label: '附件上传',
        //   prop: '',
        //   required: true,
        //   showInForm: ({ meta }) => {
        //     return meta.isForm === true
        //   },
        //   showInTable: false
        // }
      ],
      // 机关树形列表
      orgTreeList: [],
      // 处理原因选项
      handleReasonOptions: [
        { value: '101', label: '经登记机关调查认定冒名登记基本事实清楚的；' },
        { value: '102', label: '公司和相关人员无法取得联系或不配合调查且公示期内无利害关系人提出异议，登记机关认为冒名登记成立的' },
        { value: '103', label: '人民法院生效判决或裁定已认定冒名登记事实的' },
        { value: '199', label: '其他应当撤销登记的情形。' },
        { value: '201', label: '有证据证明被冒用人对该次登记知情或事后曾予追认' },
        { value: '202', label: '利害关系人在公示期内对撤销登记提出异议，经登记机关调查基本属实的；' },
        { value: '203', label: '公安、税务、金融、人力资源社会保障等相关部门出具书面意见不同意撤销登记' },
        { value: '204', label: '撤销登记可能对公共利益造成重大损害的' },
        { value: '299', label: '其他不应撤销登记的情形' }
      ]
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 使用 $nextTick 确保组件完全渲染后再调用
      vm.$nextTick(() => {
        if (vm.$refs.EditTable) {
          vm.$refs.EditTable.search({ reset: true })
        }
      })
    })
  },
  created() {
    this.loadOrgTreeList()
  },
  mounted() {
  },
  methods: {
    searchLoader(pageParam, parseSearchFormData, instance) {
      return eSusNateOperRegListSusNateOperReg({
        size: pageParam.size,
        current: pageParam.current,
        entity: {
          ...parseSearchFormData
        }
      }).then((data) => {
        // 确保每条记录都有必要的属性
        const records = data.data.records.map(record => ({
          ...record,
          _isAdd: record._isAdd || false
        }))

        return {
          tableData: records,
          total: data.data.total
        }
      })
    },
    handleAdd() {
      this.entListVisible = true
      this.$nextTick(() => {
        this.$refs.entList.open()
      })
    },
    handleEntSelect(selected) {
      if (selected && selected.length > 0) {
        const ent = selected[0]
        // 获取登记机关的树形路径
        const regOrgPath = ent.regorg ? this.getPathById(this.orgTreeList, ent.regorg) : []
        // 确保所有必需属性都存在
        this.$refs.EditTable.editReady({
          entname: ent.entname,
          uniscid: ent.uniscid,
          regno: ent.regno,
          regOrg: ent.regorg,
          regOrgCn: ent.regorgCn,
          regOrgPath: regOrgPath || [],
          pripid: ent.pripid,
          _isAdd: true
        })
      }
    },
    // 加载机关树形列表
    loadOrgTreeList() {
      getOrgTreeList().then(res => {
        if (res.code === 0) {
          this.orgTreeList = res.data || []
        }
      })
    },
    // 根据id获取从根到该节点的路径
    getPathById(tree, id, path = []) {
      for (const node of tree) {
        const currentPath = [...path, node.id]
        if (node.id === id) {
          return currentPath
        }
        if (node.children && node.children.length > 0) {
          const found = this.getPathById(node.children, id, currentPath)
          if (found) return found
        }
      }
      return null
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/abnormal-list.scss";
</style>
