<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="btns">
        <div v-if="!isComponents" style="margin-bottom: 12px;">
          <el-button type="primary" @click="addData">添加</el-button>
          <el-button icon="el-icon-download" type="primary" @click="downloadTemplate">下载模板</el-button>
          <el-upload
            style="display: inline-block; margin-left: 10px; margin-right: 10px;"
            action=""
            :show-file-list="false"
            :auto-upload="false"
            :on-change="(file) => { batchImport(file) }"
          >
            <el-button
              slot="trigger"
              icon="iconfont icon-tijiao"
              type="primary"
            >批量导入</el-button>
          </el-upload>
        </div>
        <div v-if="isComponents" style="margin-bottom: 12px;">
          <el-button type="primary" @click="confirmRemove">确定除名</el-button>
        </div>
      </template>
    </edit-table>
  </div>
</template>

<script>
import { listExpelled, saveExpelled, batchImportExpelled } from '@/api/expelled'
export default {
  props: {
    isComponents: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data() {
    return {
      data: [],
      selected: [],
      tableProp: {
        emitLoadOnCreate: true,
        tableConfig: {
          showIndex: true,
          selection: this.isComponents,
          indexWidth: '80px',
          handlerWidth: '120px',
          showPagination: true,
          tableProps: {
            headerCellStyle: { background: '#8cc3fb!important', color: '#fff!important', padding: '0px' },
            headerRowStyle: { height: '48px' },
            rowStyle: { height: '48px' },
            cellStyle: { padding: '16px 0', color: '#333' },
            rowClassName: (row) => {
              if (row.rowIndex % 2 === 1) {
                return 'warning-row'
              }
            }
          }
        },
        buttons: [
          {
            label: '编辑',
            type: 'text',
            show: !this.isComponents,
            handler: (scope, { row }) => {
              this.$refs.EditTable.editReady(row)
            }
          },
          {
            label: '删除',
            type: 'text',
            show: !this.isComponents,
            handler: (scope, { row }) => {
              this.$confirm('是否确认删除该' + row.entName + '市场主体拟除名名单信息', '提示', {
                type: 'info',
                customClass: 'type-1'
              })
                .then(() => {
                  return saveExpelled({
                    ...row,
                    isDelete: '1'
                  }).then(() => {
                    this.$message.success('删除成功')
                    this.$refs.EditTable.search({ reset: true })
                  }).catch(error => {
                    this.$message.error('删除失败: ' + (error.message || '未知错误'))
                    throw error
                  })
                })
                .catch(error => {
                  // 如果只是取消操作，不抛出错误
                  if (error !== 'cancel') {
                    throw error
                  }
                })
            }
          }
        ]
      },
      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) => {
                return this.$confirm('是否继续提交', '提示', {
                  type: 'info',
                  customClass: 'type-1'
                })
                  .then(() => {
                    return (() => {
                      return saveExpelled
                    })()(formData)
                      .then(() => {
                        this.$message.success('保存成功')
                        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: '800px',
        customClass: 'dialog-abnormal-list'
      },
      fields: [
        {
          type: 'input',
          label: '市场主体名称',
          prop: 'searchEntName',
          span: 6,
          showInForm: ({ meta }) => {
            return meta.isSearchForm === true
          },
          showInTable: false
        },
        {
          type: 'input',
          label: '统一社会信用代码',
          prop: 'searchUscc',
          span: 6,
          tableProps: {
            width: '150px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.uscc || ''}`
            }
          },
          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: 'uscc',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          showInTable: true
        },
        {
          type: 'input',
          label: '法定代表人（负责人、经营者）',
          prop: 'lerepName',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          tableProps: {
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '住所（经营场所）',
          prop: 'address',
          required: true,
          showInForm: ({ meta }) => {
            return meta.isForm === true
          },
          tableProps: {
            showOverflowTooltip: true
          }
        }
      ]
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 使用 $nextTick 确保组件完全渲染后再调用
      vm.$nextTick(() => {
        if (vm.$refs.EditTable) {
          vm.$refs.EditTable.search({ reset: true })
        }
      })
    })
  },
  methods: {
    searchLoader(pageParam, parseSearchFormData, instance) {
      return listExpelled({
        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
        }
      })
    },
    addData() {
      this.$refs.EditTable.editReady({})
    },
    downloadTemplate() {
      window.open(`${process.env.VUE_APP_BASE_API}/expelled/downloadTemplate`, '_blank')
    },
    batchImport(file) {
      const formData = new FormData()
      formData.append('annex', file.raw)
      return batchImportExpelled(formData).then(() => {
        this.$message.success('导入成功')
        this.$refs.EditTable.search({ reset: true })
      })
    },
    confirmRemove() {
      if (!this.selected || this.selected.length === 0) {
        return this.$message.error('请至少勾选一个主体名单')
      }
      this.$emit('confirm-remove', this.selected)
    }
  }
}
</script>

<style lang="scss" scoped>
// @import "~@/styles/abnormal-list.scss";
.page {
  background: #Fff;
  margin: 20px;
  padding: 20px;
}
</style>
