<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="id"
      :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="EditTable">
        <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 { ESusNateOperRegList, eSusNateVoUpdate, eSusNateVoSave, eSusNateVoRemove } from '@/api/susnate'
import EntList from './EntList.vue'
import EditTable from '@/plugins/EasyComponent/EditTable'
import { getConstant } from '@/api/system'
export default {
  components: {
    EntList,
    EditTable
  },
  data() {
    return {
      data: [],
      selected: [],
      entListVisible: false,
      tableProp: {
        emitLoadOnCreate: true,
        tableConfig: {
          showIndex: true,
          selection: false,
          indexWidth: '80px',
          handlerWidth: '120px',
          showPagination: true,
          tableSelectionProps: {
            selectable: (row, index) => {
              return row.status === '1'
            }
          },
          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 eSusNateVoRemove({
                    ...row
                  }).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 eSusNateVoSave
                      } else {
                        return eSusNateVoUpdate
                      }
                    })()(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,
                  resetData: {
                    status: '1'
                  }
                })
              }
            }
          ]
        },
        {
          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: 'input',
          label: '登记机关',
          prop: 'regOrg',
          required: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          tableProps: {
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.regOrgCn || ''}`
            }
          },
          showInTable: false
        },
        {
          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
        },
        {
          type: 'date-picker',
          label: '公告期至',
          prop: 'noticeTo',
          required: false,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'input',
          label: '责任人姓名',
          prop: 'resName',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: true
        },
        {
          type: 'input',
          label: '责任人证件号码',
          prop: 'cerNo',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'input',
          label: '作出决定机关',
          prop: 'judAuth',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: true,
          optionConfig: {
            labelKeyName: 'name',
            valueKeyName: 'id',
            isLeaf: (item) => {
              return item.children.length === 0
            }
          },
          options: () => {
            return this.authItemMap
          }
          // tableProps: {
          //   showOverflowTooltip: true,
          //   formatter: (row, column, cellValue, index) => {
          //     return `${row.judAuthCn || ''}`
          //   }
          // }
        },
        {
          type: 'date-picker',
          label: '做出决定日期',
          prop: 'judDate',
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false,
          tableProps: {
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.judDate || ''}`
            }
          }
        },
        {
          type: 'date-picker',
          label: '公告日期',
          prop: 'noticeDate',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: true
        },
        {
          type: 'date-picker',
          label: '冒名登记时间',
          prop: 'regTime',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'input',
          label: '冒名登记事项',
          prop: 'regItem',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'input',
          label: '处理原因',
          prop: 'handlRea',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        // {
        //   type: 'select',
        //   label: '处理原因',
        //   prop: 'handlRea',
        //   required: true,
        //   showInForm: ({ meta }) => {
        //     return meta.isForm === true
        //   },
        //   showInTable: false,
        //   optionsBaseCode: 'CD96'
        // },
        {
          type: 'input',
          label: '处理结果',
          prop: 'handlRest',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        },
        {
          type: 'input',
          label: '公告内容',
          prop: 'noticeContent',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: false
        }
        // {
        //   type: 'file',
        //   label: '附件上传',
        //   prop: '',
        //   required: true,
        //   showInForm: ({ meta }) => {
        //     return meta.isForm === true
        //   },
        //   showInTable: false
        // }
      ]
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 使用 $nextTick 确保组件完全渲染后再调用
      vm.$nextTick(() => {
        if (vm.$refs.EditTable) {
          vm.$refs.EditTable.search({ reset: true })
        }
      })
    })
  },
  created() {
  },
  mounted() {
    // 加载处理原因
    const p1 = getConstant('CD96').then(res => {
      if (res.code === 0) {
        const list = []
        res.data.forEach(each => {
          list.push({
            value: each.code,
            label: each.name
          })
        })
        this.handlreaList = list
      }
    })
    this.fullscreenLoading = true
    Promise.all([p1]).finally(() => {
      this.fullscreenLoading = false
    })
  },
  methods: {
    searchLoader(pageParam, parseSearchFormData, instance) {
      return ESusNateOperRegList({
        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]
        // 确保所有必需属性都存在
        this.$refs.EditTable.editReady({
          entname: ent.entname,
          uniscid: ent.uniscid,
          regno: ent.regno,
          regOrg: ent.regorgCn,
          pripid: ent.pripid,
          _isAdd: true
        })
      }
    }
  }
}
</script>

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