<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <search-form
      :query-params="queryParams"
      :show-search="showSearch"
      @query="handleQuery"
    />

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ccdi:intermediary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['ccdi:intermediary:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <data-table
      :loading="loading"
      :data-list="intermediaryList"
      :total="total"
      :page-params="queryParams"
      @selection-change="handleSelectionChange"
      @pagination="getList"
      @detail="handleDetail"
      @update="handleUpdate"
      @delete="handleDelete"
    />

    <!-- 编辑对话框 -->
    <edit-dialog
      :visible.sync="open"
      :title="title"
      :form="form"
      :indiv-type-options="indivTypeOptions"
      :gender-options="genderOptions"
      :cert-type-options="certTypeOptions"
      :relation-type-options="relationTypeOptions"
      :corp-type-options="corpTypeOptions"
      :corp-nature-options="corpNatureOptions"
      @submit="submitForm"
      @close="cancel"
    />

    <!-- 详情对话框 -->
    <detail-dialog
      :visible.sync="detailOpen"
      :detail-data="detailData"
    />

    <!-- 导入对话框 -->
    <import-dialog
      :visible.sync="upload.open"
      :title="upload.title"
      @close="handleImportDialogClose"
      @success="getList"
    />
  </div>
</template>

<script>
import {
  addEntityIntermediary,
  addPersonIntermediary,
  delIntermediary,
  getEntityIntermediary,
  getPersonIntermediary,
  listIntermediary,
  updateEntityIntermediary,
  updatePersonIntermediary
} from "@/api/ccdiIntermediary";
import {
  getCertTypeOptions,
  getCorpNatureOptions,
  getCorpTypeOptions,
  getGenderOptions,
  getIndivTypeOptions,
  getRelationTypeOptions
} from "@/api/ccdiEnum";
import SearchForm from "./components/SearchForm";
import DataTable from "./components/DataTable";
import EditDialog from "./components/EditDialog";
import DetailDialog from "./components/DetailDialog";
import ImportDialog from "./components/ImportDialog";

export default {
  name: "Intermediary",
  components: {
    SearchForm,
    DataTable,
    EditDialog,
    DetailDialog,
    ImportDialog
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      intermediaryList: [],
      title: "",
      open: false,
      detailOpen: false,
      detailData: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        certificateNo: null,
        intermediaryType: null
      },
      form: {},
      upload: {
        open: false,
        title: ""
      },
      indivTypeOptions: [],
      genderOptions: [],
      certTypeOptions: [],
      relationTypeOptions: [],
      corpTypeOptions: [],
      corpNatureOptions: []
    };
  },
  created() {
    this.getList();
    this.loadEnumOptions();
  },
  methods: {
    /** 加载枚举选项 */
    loadEnumOptions() {
      getIndivTypeOptions().then(response => {
        this.indivTypeOptions = response.data;
      });
      getGenderOptions().then(response => {
        this.genderOptions = response.data;
      });
      getCertTypeOptions().then(response => {
        this.certTypeOptions = response.data;
      });
      getRelationTypeOptions().then(response => {
        this.relationTypeOptions = response.data;
      });
      getCorpTypeOptions().then(response => {
        this.corpTypeOptions = response.data;
      });
      getCorpNatureOptions().then(response => {
        this.corpNatureOptions = response.data;
      });
    },
    /** 查询中介黑名单列表 */
    getList() {
      this.loading = true;
      listIntermediary(this.queryParams).then(response => {
        this.intermediaryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加中介黑名单";
    },
    /** 表单重置 */
    reset() {
      this.form = {
        bizId: null,
        name: null,
        intermediaryType: "1",
        remark: null,
        // 个人中介字段
        personId: null,
        personType: null,
        personSubType: null,
        relationType: null,
        gender: null,
        idType: null,
        mobile: null,
        wechatNo: null,
        contactAddress: null,
        company: null,
        socialCreditCode: null,
        position: null,
        relatedNumId: null,
        // 实体中介字段
        enterpriseName: null,
        enterpriseType: null,
        enterpriseNature: null,
        industryClass: null,
        industryName: null,
        establishDate: null,
        registerAddress: null,
        legalRepresentative: null,
        legalCertType: null,
        legalCertNo: null,
        shareholder1: null,
        shareholder2: null,
        shareholder3: null,
        shareholder4: null,
        shareholder5: null
      };
      // 注意:不调用 this.resetForm("form")
      // EditDialog 组件会在 visible 变化时自动处理表单验证状态的重置
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 查看详情操作 */
    handleDetail(row) {
      if (row.intermediaryType === '1') {
        // 个人中介 - 使用row.id作为bizId
        getPersonIntermediary(row.id).then(response => {
          this.detailData = response.data;
          this.detailOpen = true;
        });
      } else {
        // 实体中介 - 使用row.id作为socialCreditCode
        getEntityIntermediary(row.id).then(response => {
          this.detailData = response.data;
          this.detailOpen = true;
        });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (row.intermediaryType === '1') {
        // 个人中介 - 使用row.id作为bizId
        getPersonIntermediary(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改中介黑名单";
        });
      } else {
        // 实体中介 - 使用row.id作为socialCreditCode
        getEntityIntermediary(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改中介黑名单";
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.bizId != null) {
        // 修改模式：根据中介类型调用不同的接口
        if (this.form.intermediaryType === '1') {
          // 个人中介
          updatePersonIntermediary(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else if (this.form.intermediaryType === '2') {
          // 机构中介
          updateEntityIntermediary(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        }
      } else {
        // 新增模式：根据中介类型调用不同的接口
        if (this.form.intermediaryType === '1') {
          // 个人中介
          addPersonIntermediary(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        } else if (this.form.intermediaryType === '2') {
          // 机构中介
          addEntityIntermediary(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bizIds = row.id || this.ids.join(',');
      const confirmMsg = row.id
        ? `确认删除中介"${row.name}"（证件号：${row.certificateNo}）吗？`
        : `确认删除选中的 ${this.ids.length} 条中介数据吗？`;
      this.$modal.confirm(confirmMsg).then(function() {
        return delIntermediary(bizIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "中介黑名单数据导入";
      this.upload.open = true;
    },
    /** 导入对话框关闭处理 */
    handleImportDialogClose() {
      // 子组件已处理文件清理
    }
  }
};
</script>
