<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="90vw"
    top="153px"
    custom-class="dialog-abnormal-list"
  >
    <div class="dialog-container">
      <!-- 左侧表格 -->
      <div class="left-panel">
        <edit-table
          v-if="visible"
          v-model="tableData"
          :table-prop="tableProp"
          :fields="fields"
          :show-search-form="true"
          row-key="pripid"
          :search-form-prop="searchFormProp"
          :search-loader="searchLoader"
          :selected.sync="selected"
        />
        <!-- 当没有输入条件时显示提示 -->
        <!--        <div v-if="showNoDataMessage" class="no-data-message">请输入条件进行查询！</div>-->
      </div>

      <!-- 右侧已选择主体显示区域 -->
      <div class="right-panel">
        <div class="selected-title">已选择主体</div>
        <div v-if="selected.length === 0" class="empty-tip">暂无选择</div>
        <div v-else class="selected-list">
          <div
            v-for="(entity, index) in selected"
            :key="entity.pripid"
            class="selected-item"
          >
            <div class="item-info">
              <div class="item-name">{{ entity.entname }}</div>
              <div class="item-code">{{ entity.uniscid || entity.regno }}</div>
            </div>
            <i class="el-icon-close remove-btn" @click="removeEntity(index)" />
          </div>
        </div>
      </div>
    </div>

    <div slot="footer">
      <el-button type="primary" plain @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirm">办理</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { baseinfoListByRegOrg, getIsUserProp } from '@/api/force'
import { getBaseCodeList } from '@/api/constant'
export default {
  props: {
    type: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      visible: false,
      isExSearch: false,
      tableData: [],
      selected: [],
      selectedEntities: [], // 已选择主体列表
      showNoDataMessage: false, // 新增属性
      INDUSTRYPHYList: [], // 存储行业门类数据
      fields: [
        {
          type: 'input',
          label: '统一社会信用代码/注册号',
          prop: 'searchUscc',
          span: 10,
          tableProps: {
            width: `210px`,
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.uniscid || row.regno || ''}`
            }
          }
        },
        {
          type: 'input',
          label: ({ meta }) => {
            return meta.isSearchForm ? '主体名称（模糊）' : '主体名称'
          },
          prop: 'entName',
          span: 10,
          tableProps: {
            width: `210px`,
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return `${row.entname || ''}`
            }
          }
        },
        {
          type: 'input',
          label: '登记机关',
          prop: 'regorgCn',
          span: 6,
          isView: false,
          tableProps: {
            width: '180px',
            formatter: (row, column, cellValue, index) => {
              return `${row.regorgCn || ''}`
            }
          },
          showInForm: false
        },
        {
          type: 'select',
          label: '主体类型',
          prop: 'enterType',
          span: 7,
          defaultValue: 'company', // 拟强制注销公告仅限公司类型（企业类型1、5、6、2开头）
          options: [
            { label: '企业', value: 'company' }
          ],
          showInForm: false, // 仅有企业类型，无需展示选择框
          tableProps: {
            width: '90px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              const typeMap = {
                company: '企业'
              }
              return typeMap[cellValue] || ''
            }
          }
        },
        {
          type: 'select',
          label: '行业门类',
          prop: 'industryphy',
          span: 9,
          options: [],
          tableProps: {
            width: '150px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              const industryMap = this.INDUSTRYPHYList?.reduce((map, item) => {
                map[item.code] = item.name // 使用 code 作为 key，name 作为 value
                return map
              }, {})
              return industryMap?.[cellValue] || '' // 匹配 cellValue 并返回对应中文
            }
          }
        },
        {
          type: 'select',
          label: '是否列异',
          prop: 'isException',
          span: 7,
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '0' }
          ],
          tableProps: {
            width: '90px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              const map = { '1': '是', '0': '否' }
              return map[row.isException] || ''
            }
          }
        },
        {
          type: 'select',
          label: '是否列严',
          prop: 'isSerious',
          span: 7,
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '0' }
          ],
          tableProps: {
            width: '90px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              const map = { '1': '是', '0': '否' }
              return map[row.isSerious] || ''
            }
          }
        },
        {
          type: 'date-picker',
          label: '吊销日期自',
          prop: 'revStartDate',
          span: 8,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          },
          placeholder: '请选择开始日期',
          showInTable: false
        },
        {
          type: 'date-picker',
          label: '吊销日期至',
          prop: 'revEndDate',
          span: 8,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          },
          placeholder: '请选择结束日期',
          showInTable: false
        },
        {
          type: 'input',
          label: '吊销时间',
          prop: 'revDate',
          tableProps: {
            width: '120px',
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return row.revDate || ''
            }
          },
          showInForm: false
        },
        {
          type: 'buttons',
          showInTable: false,
          hiddenLabel: true,
          label: '搜索操作',
          prop: '搜索操作',
          span: 8,
          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
                })
              }
            }
          ]
        }
      ],
      searchFormProp: {
        formConfig: {
          labelWidth: '100px',
          labelPosition: 'right',
          gutter: 32
        }
      },
      tableProp: {
        emitLoadOnCreate: true,
        tableConfig: {
          selection: true,
          // eslint-disable-next-line no-mixed-spaces-and-tabs
      	  tableSelectionProps: {
            reserveSelection: true
            // eslint-disable-next-line no-mixed-spaces-and-tabs
		      },
          disableSelectAll: false,
          showIndex: true,
          indexWidth: '100px',
          showPagination: true,
          rowKey: 'pripid',
          tableProps: {
            headerCellStyle: { background: '#F5F5F5!important', color: '#333333!important', padding: '0px' },
            headerRowStyle: { height: '48px' },
            rowStyle: { height: '48px' },
            cellStyle: { padding: '16px 0', color: '#333' }
          }
        }
      }
    }
  },
  computed: {
    title() {
      return '经营主体信息'
    }
  },
  created() {
    // 判断是否是管理员
    getIsUserProp().then(res => {
      this.data = {
        ...this.data,
        userProp: res.userProp
      }
    })
  },
  mounted() {
    getBaseCodeList('CA05').then(res => {
      if (res.code === 0) {
        this.INDUSTRYPHYList = res.data
        // 使用 $set 更新 fields 中的 options
        const industryFieldIndex = this.fields.findIndex(field => field.prop === 'industryphy')
        if (industryFieldIndex !== -1) {
          this.$set(this.fields[industryFieldIndex], 'options', this.INDUSTRYPHYList.map(item => ({
            label: item.name,
            value: item.code
          })))
        }
      }
    })
  },
  methods: {
    open() {
      this.selected = []
      this.selectedEntities = []
      this.visible = true
    },
    handleSelectionChange(selection) {
      this.$set(this, 'selectedEntities', [...selection])
    },
    removeEntity(index) {
      this.selected.splice(index, 1)
    },
    searchLoader(pageParam, parseSearchFormData, instance) {
      const { searchUscc, entName, revStartDate, revEndDate } = parseSearchFormData
      // 校验吊销日期自和吊销日期至是否同时选择
      if ((revStartDate && !revEndDate) || (!revStartDate && revEndDate)) {
        this.$message.warning('吊销日期自 和 吊销日期至 需同时选择！')
        return Promise.reject() // 阻止查询
      }

      return baseinfoListByRegOrg({
        size: pageParam.size,
        current: pageParam.current,
        entity: {
          ...parseSearchFormData,
          revStartDate, // 开始时间
          revEndDate // 结束时间
        }
      }).then((data) => {
        this.showNoDataMessage = !searchUscc && !entName
        return {
          tableData: data.dataPage.records,
          total: data.dataPage.total
        }
      })
    },
    confirm() {
      this.$emit('confirm', this.selected) // 提交已选择主体信息
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-container {
  display: flex;
  height: 60vh;

  .left-panel {
    flex: 1;
    overflow-y: auto;
    border-right: 1px solid #ebeef5;
    padding-right: 16px;
  }

  .right-panel {
    width: 300px;
    padding-left: 16px;
    overflow-y: auto;

    .selected-title {
      font-weight: bold;
      margin-bottom: 10px;
    }

    .empty-tip {
      color: #999;
      text-align: center;
      margin-top: 20px;
    }

    .selected-list {
      max-height: 50vh;
      overflow-y: auto;

      .selected-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        margin-bottom: 8px;

        .item-info {
          flex: 1;

          .item-name {
            font-weight: bold;
          }

          .item-code {
            font-size: 12px;
            color: #999;
          }
        }

        .remove-btn {
          cursor: pointer;
          color: #f56c6c;
        }
      }
    }
  }
}

.no-data-message {
  color: red;
  text-align: center;
  font-size: 16px;
  margin-top: 20px;
}
</style>

