<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" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col>
      <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="handleOpenPersonImport"
          v-hasPermi="['ccdi:intermediary:import']"
        >导入中介和亲属信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-connection"
          size="mini"
          @click="handleOpenEnterpriseRelationImport"
          v-hasPermi="['ccdi:intermediary:import']"
        >导入中介实体关联关系</el-button>
      </el-col>
      <el-col :span="1.5" v-if="personImportTask && personImportTask.failureCount > 0">
        <el-button
          type="warning"
          plain
          icon="el-icon-warning"
          size="mini"
          @click="viewPersonImportFailures"
        >查看中介和亲属信息导入失败记录</el-button>
      </el-col>
      <el-col :span="1.5" v-if="enterpriseRelationImportTask && enterpriseRelationImportTask.failureCount > 0">
        <el-button
          type="warning"
          plain
          icon="el-icon-warning-outline"
          size="mini"
          @click="viewEnterpriseRelationImportFailures"
        >查看中介实体关联关系导入失败记录</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </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="personDialogVisible"
      :title="personDialogTitle"
      :form="personForm"
      :person-sub-type-options="relationTypeOptions"
      :indiv-type-options="indivTypeOptions"
      :gender-options="genderOptions"
      :cert-type-options="certTypeOptions"
      @submit="submitPersonForm"
      @close="resetPersonForm"
    />

    <relative-edit-dialog
      :visible.sync="relativeDialogVisible"
      :title="relativeDialogTitle"
      :form="relativeForm"
      :owner-name="currentOwnerName"
      :readonly="relativeDialogReadonly"
      :relation-type-options="relationTypeOptions"
      :indiv-type-options="indivTypeOptions"
      :gender-options="genderOptions"
      :cert-type-options="certTypeOptions"
      @submit="submitRelativeForm"
      @close="resetRelativeForm"
    />

    <enterprise-relation-edit-dialog
      :visible.sync="enterpriseRelationDialogVisible"
      :title="enterpriseRelationDialogTitle"
      :form="enterpriseRelationForm"
      :owner-name="currentOwnerName"
      :readonly="enterpriseRelationDialogReadonly"
      @submit="submitEnterpriseRelationForm"
      @close="resetEnterpriseRelationForm"
    />

    <detail-dialog
      :visible.sync="detailOpen"
      :detail-data="detailData"
      :relative-list="relativeList"
      :enterprise-relation-list="enterpriseRelationList"
      @edit-person="handleEditPersonFromDetail"
      @add-relative="handleAddRelative"
      @edit-relative="handleEditRelativeFromDetail"
      @delete-relative="handleDelete"
      @add-enterprise-relation="handleAddEnterpriseRelation"
      @edit-enterprise-relation="handleEditEnterpriseRelationFromDetail"
      @delete-enterprise-relation="handleDelete"
    />

    <import-dialog
      :visible.sync="importDialogVisible"
      :title="importDialogTitle"
      :scene="importScene"
      @task-created="handleImportTaskCreated"
      @success="handleImportDialogSuccess"
      @import-complete="handleImportComplete"
      @clear-import-history="handleClearImportHistory"
    />

    <el-dialog
      title="中介和亲属信息导入失败记录"
      :visible.sync="personFailureDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-alert
        v-if="personLastImportInfo"
        :title="personLastImportInfo"
        type="info"
        :closable="false"
        style="margin-bottom: 15px"
      />

      <el-table :data="personFailureList" v-loading="personFailureLoading">
        <el-table-column label="姓名" prop="name" align="center" />
        <el-table-column label="人员子类型" prop="personSubType" align="center" />
        <el-table-column label="证件号码" prop="personId" align="center" min-width="180" />
        <el-table-column label="关联中介本人证件号码" prop="relatedNumId" align="center" min-width="180" />
        <el-table-column label="失败原因" prop="errorMessage" align="center" min-width="220" :show-overflow-tooltip="true" />
      </el-table>

      <pagination
        v-show="personFailureTotal > 0"
        :total="personFailureTotal"
        :page.sync="personFailureQueryParams.pageNum"
        :limit.sync="personFailureQueryParams.pageSize"
        @pagination="getPersonFailureList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="personFailureDialogVisible = false">关闭</el-button>
        <el-button type="danger" plain @click="clearPersonImportHistory">清除历史记录</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="中介实体关联关系导入失败记录"
      :visible.sync="enterpriseRelationFailureDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-alert
        v-if="enterpriseRelationLastImportInfo"
        :title="enterpriseRelationLastImportInfo"
        type="info"
        :closable="false"
        style="margin-bottom: 15px"
      />

      <el-table :data="enterpriseRelationFailureList" v-loading="enterpriseRelationFailureLoading">
        <el-table-column label="中介本人证件号码" prop="ownerPersonId" align="center" min-width="180" />
        <el-table-column label="统一社会信用代码" prop="socialCreditCode" align="center" min-width="180" />
        <el-table-column label="关联人职务" prop="relationPersonPost" align="center" />
        <el-table-column label="失败原因" prop="errorMessage" align="center" min-width="220" :show-overflow-tooltip="true" />
      </el-table>

      <pagination
        v-show="enterpriseRelationFailureTotal > 0"
        :total="enterpriseRelationFailureTotal"
        :page.sync="enterpriseRelationFailureQueryParams.pageNum"
        :limit.sync="enterpriseRelationFailureQueryParams.pageSize"
        @pagination="getEnterpriseRelationFailureList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="enterpriseRelationFailureDialogVisible = false">关闭</el-button>
        <el-button type="danger" plain @click="clearEnterpriseRelationImportHistory">清除历史记录</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addIntermediaryEnterpriseRelation,
  addIntermediaryRelative,
  addPersonIntermediary,
  delIntermediary,
  delIntermediaryEnterpriseRelation,
  delIntermediaryRelative,
  getEnterpriseRelationImportFailures,
  getEnterpriseRelationImportStatus,
  getIntermediaryEnterpriseRelation,
  getIntermediaryRelative,
  getPersonImportFailures,
  getPersonImportStatus,
  getPersonIntermediary,
  listIntermediary,
  listIntermediaryEnterpriseRelations,
  listIntermediaryRelatives,
  updateIntermediaryEnterpriseRelation,
  updateIntermediaryRelative,
  updatePersonIntermediary
} from "@/api/ccdiIntermediary";
import {
  getCertTypeOptions,
  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 RelativeEditDialog from "./components/RelativeEditDialog";
import EnterpriseRelationEditDialog from "./components/EnterpriseRelationEditDialog";
import ImportDialog from "./components/ImportDialog";

const PERSON_SCENE = "person";
const ENTERPRISE_RELATION_SCENE = "enterpriseRelation";

export default {
  name: "Intermediary",
  components: {
    SearchForm,
    DataTable,
    EditDialog,
    DetailDialog,
    RelativeEditDialog,
    EnterpriseRelationEditDialog,
    ImportDialog
  },
  data() {
    return {
      loading: true,
      ids: [],
      showSearch: true,
      total: 0,
      intermediaryList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        certificateNo: null,
        recordType: null,
        relatedIntermediaryKeyword: null
      },
      indivTypeOptions: [],
      genderOptions: [],
      certTypeOptions: [],
      relationTypeOptions: [],
      personDialogVisible: false,
      personDialogTitle: "",
      personForm: {},
      relativeDialogVisible: false,
      relativeDialogTitle: "",
      relativeDialogReadonly: false,
      relativeForm: {},
      enterpriseRelationDialogVisible: false,
      enterpriseRelationDialogTitle: "",
      enterpriseRelationDialogReadonly: false,
      enterpriseRelationForm: {},
      detailOpen: false,
      detailData: {},
      relativeList: [],
      enterpriseRelationList: [],
      currentIntermediaryId: null,
      currentOwnerName: "",
      importDialogVisible: false,
      importDialogTitle: "",
      importScene: PERSON_SCENE,
      personImportTask: null,
      enterpriseRelationImportTask: null,
      personImportPollingTimer: null,
      enterpriseRelationImportPollingTimer: null,
      personFailureDialogVisible: false,
      personFailureList: [],
      personFailureLoading: false,
      personFailureTotal: 0,
      personFailureQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      personLastImportInfo: "",
      enterpriseRelationFailureDialogVisible: false,
      enterpriseRelationFailureList: [],
      enterpriseRelationFailureLoading: false,
      enterpriseRelationFailureTotal: 0,
      enterpriseRelationFailureQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      enterpriseRelationLastImportInfo: ""
    };
  },
  created() {
    this.resetPersonForm();
    this.resetRelativeForm();
    this.resetEnterpriseRelationForm();
    this.getList();
    this.loadEnumOptions();
    this.restoreImportTasks();
  },
  beforeDestroy() {
    this.clearImportPolling(PERSON_SCENE);
    this.clearImportPolling(ENTERPRISE_RELATION_SCENE);
  },
  methods: {
    loadEnumOptions() {
      Promise.all([
        getIndivTypeOptions(),
        getGenderOptions(),
        getCertTypeOptions(),
        getRelationTypeOptions()
      ]).then(([indivTypeRes, genderRes, certTypeRes, relationTypeRes]) => {
        this.indivTypeOptions = indivTypeRes.data || [];
        this.genderOptions = genderRes.data || [];
        this.certTypeOptions = certTypeRes.data || [];
        this.relationTypeOptions = relationTypeRes.data || [];
      });
    },
    getList() {
      this.loading = true;
      listIntermediary(this.queryParams).then(response => {
        this.intermediaryList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        certificateNo: null,
        recordType: null,
        relatedIntermediaryKeyword: null
      };
      this.getList();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId);
    },
    resetPersonForm() {
      this.personForm = {
        bizId: null,
        name: null,
        personType: null,
        personSubType: "本人",
        gender: null,
        idType: null,
        personId: null,
        mobile: null,
        wechatNo: null,
        contactAddress: null,
        company: null,
        socialCreditCode: null,
        position: null,
        relatedNumId: null,
        remark: null
      };
    },
    resetRelativeForm() {
      this.relativeDialogReadonly = false;
      this.relativeForm = {
        bizId: null,
        name: null,
        personType: null,
        personSubType: null,
        gender: null,
        idType: null,
        personId: null,
        mobile: null,
        wechatNo: null,
        contactAddress: null,
        company: null,
        socialCreditCode: null,
        position: null,
        remark: null
      };
    },
    resetEnterpriseRelationForm() {
      this.enterpriseRelationDialogReadonly = false;
      this.enterpriseRelationForm = {
        id: null,
        socialCreditCode: null,
        relationPersonPost: null,
        remark: null
      };
    },
    handleAdd() {
      this.resetPersonForm();
      this.personDialogTitle = "新增中介本人";
      this.personDialogVisible = true;
    },
    handleOpenPersonImport() {
      this.importScene = PERSON_SCENE;
      this.importDialogTitle = "导入中介和亲属信息";
      this.importDialogVisible = true;
    },
    handleOpenEnterpriseRelationImport() {
      this.importScene = ENTERPRISE_RELATION_SCENE;
      this.importDialogTitle = "导入中介实体关联关系";
      this.importDialogVisible = true;
    },
    handleImportDialogSuccess() {
      // 导入任务创建后由任务轮询负责状态更新
    },
    handleImportTaskCreated(payload) {
      const task = {
        ...payload,
        failureCount: 0,
        successCount: 0,
        totalCount: 0,
        saveTime: Date.now()
      };
      this.setImportTask(payload.scene, task);
      this.saveImportTaskToStorage(payload.scene, task);
    },
    handleImportComplete(payload) {
      const task = {
        ...payload,
        status: payload.hasFailures ? "PARTIAL_SUCCESS" : "SUCCESS",
        saveTime: Date.now()
      };
      this.setImportTask(payload.scene, task);
      this.saveImportTaskToStorage(payload.scene, task);
      if (payload.scene === PERSON_SCENE) {
        this.personLastImportInfo = this.buildImportSummary(task);
      } else {
        this.enterpriseRelationLastImportInfo = this.buildImportSummary(task);
      }
      this.getList();
      this.refreshCurrentDetail();
    },
    handleClearImportHistory(scene) {
      this.clearImportTaskFromStorage(scene);
      this.setImportTask(scene, null);
      if (scene === PERSON_SCENE) {
        this.personFailureList = [];
        this.personFailureTotal = 0;
        this.personLastImportInfo = "";
      } else {
        this.enterpriseRelationFailureList = [];
        this.enterpriseRelationFailureTotal = 0;
        this.enterpriseRelationLastImportInfo = "";
      }
    },
    setImportTask(scene, task) {
      if (scene === PERSON_SCENE) {
        this.personImportTask = task;
        return;
      }
      this.enterpriseRelationImportTask = task;
    },
    getImportTask(scene) {
      return scene === PERSON_SCENE ? this.personImportTask : this.enterpriseRelationImportTask;
    },
    getImportStorageKey(scene) {
      if (scene === PERSON_SCENE) {
        return "ccdi_intermediary_person_import_task";
      }
      return "ccdi_intermediary_enterprise_relation_import_task";
    },
    saveImportTaskToStorage(scene, task) {
      try {
        localStorage.setItem(this.getImportStorageKey(scene), JSON.stringify(task));
      } catch (error) {
        console.error("保存中介导入任务状态失败:", error);
      }
    },
    getImportTaskFromStorage(scene) {
      try {
        const raw = localStorage.getItem(this.getImportStorageKey(scene));
        return raw ? JSON.parse(raw) : null;
      } catch (error) {
        console.error("读取中介导入任务状态失败:", error);
        return null;
      }
    },
    clearImportTaskFromStorage(scene) {
      try {
        localStorage.removeItem(this.getImportStorageKey(scene));
      } catch (error) {
        console.error("清除中介导入任务状态失败:", error);
      }
      this.clearImportPolling(scene);
    },
    restoreImportTasks() {
      [PERSON_SCENE, ENTERPRISE_RELATION_SCENE].forEach((scene) => {
        const task = this.getImportTaskFromStorage(scene);
        if (!task) {
          return;
        }
        this.setImportTask(scene, task);
        if (scene === PERSON_SCENE) {
          this.personLastImportInfo = this.buildImportSummary(task);
        } else {
          this.enterpriseRelationLastImportInfo = this.buildImportSummary(task);
        }
        if (task.status === "PROCESSING") {
          this.resumeImportPolling(scene, task.taskId);
        }
      });
    },
    resumeImportPolling(scene, taskId) {
      this.clearImportPolling(scene);
      const timerKey = scene === PERSON_SCENE ? "personImportPollingTimer" : "enterpriseRelationImportPollingTimer";
      const getStatus = scene === PERSON_SCENE ? getPersonImportStatus : getEnterpriseRelationImportStatus;
      let pollCount = 0;
      this[timerKey] = setInterval(async () => {
        pollCount++;
        if (pollCount > 150) {
          this.clearImportPolling(scene);
          return;
        }
        const response = await getStatus(taskId);
        if (response.data && response.data.status !== "PROCESSING") {
          this.clearImportPolling(scene);
          this.handleImportComplete({
            scene,
            taskId: response.data.taskId,
            hasFailures: response.data.failureCount > 0,
            totalCount: response.data.totalCount,
            successCount: response.data.successCount,
            failureCount: response.data.failureCount
          });
        }
      });
    },
    clearImportPolling(scene) {
      const timerKey = scene === PERSON_SCENE ? "personImportPollingTimer" : "enterpriseRelationImportPollingTimer";
      if (this[timerKey]) {
        clearInterval(this[timerKey]);
        this[timerKey] = null;
      }
    },
    buildImportSummary(task) {
      if (!task) {
        return "";
      }
      return `任务ID: ${task.taskId}，总数 ${task.totalCount || 0} 条，成功 ${task.successCount || 0} 条，失败 ${task.failureCount || 0} 条`;
    },
    viewPersonImportFailures() {
      this.personFailureDialogVisible = true;
      this.personFailureQueryParams.pageNum = 1;
      this.personLastImportInfo = this.buildImportSummary(this.personImportTask);
      this.getPersonFailureList();
    },
    getPersonFailureList() {
      if (!this.personImportTask) {
        return;
      }
      this.personFailureLoading = true;
      getPersonImportFailures(
        this.personImportTask.taskId,
        this.personFailureQueryParams.pageNum,
        this.personFailureQueryParams.pageSize
      ).then((response) => {
        this.personFailureList = response.rows || [];
        this.personFailureTotal = response.total || 0;
      }).finally(() => {
        this.personFailureLoading = false;
      });
    },
    clearPersonImportHistory() {
      this.personFailureDialogVisible = false;
      this.handleClearImportHistory(PERSON_SCENE);
    },
    viewEnterpriseRelationImportFailures() {
      this.enterpriseRelationFailureDialogVisible = true;
      this.enterpriseRelationFailureQueryParams.pageNum = 1;
      this.enterpriseRelationLastImportInfo = this.buildImportSummary(this.enterpriseRelationImportTask);
      this.getEnterpriseRelationFailureList();
    },
    getEnterpriseRelationFailureList() {
      if (!this.enterpriseRelationImportTask) {
        return;
      }
      this.enterpriseRelationFailureLoading = true;
      getEnterpriseRelationImportFailures(
        this.enterpriseRelationImportTask.taskId,
        this.enterpriseRelationFailureQueryParams.pageNum,
        this.enterpriseRelationFailureQueryParams.pageSize
      ).then((response) => {
        this.enterpriseRelationFailureList = response.rows || [];
        this.enterpriseRelationFailureTotal = response.total || 0;
      }).finally(() => {
        this.enterpriseRelationFailureLoading = false;
      });
    },
    clearEnterpriseRelationImportHistory() {
      this.enterpriseRelationFailureDialogVisible = false;
      this.handleClearImportHistory(ENTERPRISE_RELATION_SCENE);
    },
    handleDetail(row) {
      if (row.recordType === "INTERMEDIARY") {
        this.openIntermediaryDetail(row.recordId);
        return;
      }
      if (row.recordType === "RELATIVE") {
        this.openRelativeDialog(row.recordId, row.relatedIntermediaryName, "查看中介亲属");
        return;
      }
      this.openEnterpriseRelationDialog(row.recordId, row.relatedIntermediaryName, "查看关联机构", true);
    },
    handleUpdate(row) {
      if (row.recordType === "INTERMEDIARY") {
        getPersonIntermediary(row.recordId).then(response => {
          this.personForm = { ...response.data };
          this.personDialogTitle = "修改中介本人";
          this.personDialogVisible = true;
        });
        return;
      }
      if (row.recordType === "RELATIVE") {
        this.openRelativeDialog(row.recordId, row.relatedIntermediaryName, "编辑中介亲属");
        return;
      }
      this.openEnterpriseRelationDialog(row.recordId, row.relatedIntermediaryName, "编辑关联机构", false);
    },
    handleDelete(row) {
      const deleteAction = row.recordType === "RELATIVE"
        ? () => delIntermediaryRelative(row.bizId || row.recordId)
        : row.recordType === "ENTERPRISE_RELATION"
          ? () => delIntermediaryEnterpriseRelation(row.id || row.recordId)
          : () => delIntermediary(row.recordId);
      const targetName = row.name || row.enterpriseName || "当前记录";
      this.$modal.confirm(`确认删除"${targetName}"吗？`).then(() => {
        return deleteAction();
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
        this.refreshCurrentDetail();
      }).catch(() => {});
    },
    submitPersonForm(form) {
      const request = form.bizId ? updatePersonIntermediary(form) : addPersonIntermediary(form);
      request.then(() => {
        this.$modal.msgSuccess(form.bizId ? "修改成功" : "新增成功");
        const personId = form.personId;
        this.personDialogVisible = false;
        this.resetPersonForm();
        this.getList();
        if (form.bizId) {
          if (this.currentIntermediaryId === form.bizId) {
            this.openIntermediaryDetail(form.bizId);
          }
          return;
        }
        this.locateAndOpenDetailByPersonId(personId);
      });
    },
    locateAndOpenDetailByPersonId(personId) {
      listIntermediary({
        pageNum: 1,
        pageSize: 1,
        certificateNo: personId,
        recordType: "INTERMEDIARY"
      }).then(response => {
        const row = response.rows && response.rows[0];
        if (row) {
          this.openIntermediaryDetail(row.recordId);
        }
      });
    },
    openIntermediaryDetail(bizId) {
      Promise.all([
        getPersonIntermediary(bizId),
        listIntermediaryRelatives(bizId),
        listIntermediaryEnterpriseRelations(bizId)
      ]).then(([detailRes, relativeRes, enterpriseRelationRes]) => {
        this.currentIntermediaryId = bizId;
        this.detailData = detailRes.data || {};
        this.relativeList = relativeRes.data || [];
        this.enterpriseRelationList = enterpriseRelationRes.data || [];
        this.currentOwnerName = this.detailData.name || "";
        this.detailOpen = true;
      });
    },
    refreshCurrentDetail() {
      if (this.detailOpen && this.currentIntermediaryId) {
        this.openIntermediaryDetail(this.currentIntermediaryId);
      }
    },
    handleEditPersonFromDetail() {
      this.personForm = { ...this.detailData };
      this.personDialogTitle = "修改中介本人";
      this.personDialogVisible = true;
    },
    handleAddRelative() {
      this.resetRelativeForm();
      this.currentOwnerName = this.detailData.name || "";
      this.relativeDialogTitle = "新增中介亲属";
      this.relativeDialogReadonly = false;
      this.relativeDialogVisible = true;
    },
    handleEditRelativeFromDetail(row) {
      this.openRelativeDialog(row.bizId || row.recordId, this.detailData.name, "编辑中介亲属");
    },
    openRelativeDialog(relativeBizId, ownerName, title) {
      getIntermediaryRelative(relativeBizId).then(response => {
        this.relativeForm = { ...response.data };
        this.currentOwnerName = ownerName || "";
        this.relativeDialogTitle = title;
        this.relativeDialogReadonly = title === "查看中介亲属";
        this.relativeDialogVisible = true;
      });
    },
    submitRelativeForm(form) {
      const request = form.bizId
        ? updateIntermediaryRelative(form)
        : addIntermediaryRelative(this.currentIntermediaryId, form);
      request.then(() => {
        this.$modal.msgSuccess(form.bizId ? "修改成功" : "新增成功");
        this.relativeDialogVisible = false;
        this.resetRelativeForm();
        this.getList();
        this.refreshCurrentDetail();
      });
    },
    handleAddEnterpriseRelation() {
      this.resetEnterpriseRelationForm();
      this.currentOwnerName = this.detailData.name || "";
      this.enterpriseRelationDialogTitle = "新增关联机构";
      this.enterpriseRelationDialogReadonly = false;
      this.enterpriseRelationDialogVisible = true;
    },
    handleEditEnterpriseRelationFromDetail(row) {
      this.openEnterpriseRelationDialog(row.id || row.recordId, this.detailData.name, "编辑关联机构", false);
    },
    openEnterpriseRelationDialog(id, ownerName, title, readonly = false) {
      getIntermediaryEnterpriseRelation(id).then(response => {
        this.enterpriseRelationForm = { ...response.data };
        this.currentOwnerName = ownerName || "";
        this.enterpriseRelationDialogTitle = title;
        this.enterpriseRelationDialogReadonly = readonly;
        this.enterpriseRelationDialogVisible = true;
      });
    },
    submitEnterpriseRelationForm(form) {
      const request = form.id
        ? updateIntermediaryEnterpriseRelation(form)
        : addIntermediaryEnterpriseRelation(this.currentIntermediaryId, form);
      request.then(() => {
        this.$modal.msgSuccess(form.id ? "修改成功" : "新增成功");
        this.enterpriseRelationDialogVisible = false;
        this.resetEnterpriseRelationForm();
        this.getList();
        this.refreshCurrentDetail();
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  min-height: calc(100vh - 84px);
  padding: 24px;
  background: #f5f6f8;
}

.mb8 {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 16px;
  padding: 14px 20px;
  border: 1px solid #dde3ec;
  border-radius: 3px;
  background: #ffffff;
}

.mb8 ::v-deep .el-button {
  border-radius: 4px;
}

.mb8 ::v-deep .top-right-btn {
  margin-left: auto;
}

::v-deep .el-dialog {
  border-radius: 6px;
  overflow: hidden;
}

::v-deep .el-dialog__header {
  border-bottom: 1px solid #dde3ec;
  background: #ffffff;
}

::v-deep .el-dialog__body {
  background: #f8fafc;
}
</style>
