<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>
      <el-col :span="1.5" v-if="showPersonFailureButton">
        <el-tooltip
          :content="getPersonImportTooltip()"
          placement="top"
        >
          <el-button
            type="warning"
            plain
            icon="el-icon-warning"
            size="mini"
            @click="viewPersonImportFailures"
          >查看个人导入失败记录</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5" v-if="showEntityFailureButton">
        <el-tooltip
          :content="getEntityImportTooltip()"
          placement="top"
        >
          <el-button
            type="warning"
            plain
            icon="el-icon-warning"
            size="mini"
            @click="viewEntityImportFailures"
          >查看实体导入失败记录</el-button>
        </el-tooltip>
      </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"
      @import-complete="handleImportComplete"
    />

    <!-- 个人中介导入失败记录对话框 -->
    <el-dialog
      title="个人中介导入失败记录"
      :visible.sync="personFailureDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-alert
        v-if="getPersonLastImportInfo()"
        :title="getPersonLastImportInfo()"
        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="personId" align="center" />
        <el-table-column label="人员类型" prop="personType" align="center" />
        <el-table-column label="性别" prop="gender" align="center" />
        <el-table-column label="手机号码" prop="mobile" align="center" />
        <el-table-column label="所在公司" prop="company" align="center" />
        <el-table-column
          label="失败原因"
          prop="errorMessage"
          align="center"
          min-width="200"
          :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="entityFailureDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-alert
        v-if="getEntityLastImportInfo()"
        :title="getEntityLastImportInfo()"
        type="info"
        :closable="false"
        style="margin-bottom: 15px"
      />

      <el-table :data="entityFailureList" v-loading="entityFailureLoading">
        <el-table-column label="机构名称" prop="enterpriseName" align="center" />
        <el-table-column label="统一社会信用代码" prop="socialCreditCode" align="center" />
        <el-table-column label="主体类型" prop="enterpriseType" align="center" />
        <el-table-column label="企业性质" prop="enterpriseNature" align="center" />
        <el-table-column label="法定代表人" prop="legalRepresentative" align="center" />
        <el-table-column label="成立日期" prop="establishDate" align="center" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.establishDate">{{ parseTime(scope.row.establishDate, '{y}-{m}-{d}') }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="失败原因"
          prop="errorMessage"
          align="center"
          min-width="200"
          :show-overflow-tooltip="true"
        />
      </el-table>

      <pagination
        v-show="entityFailureTotal > 0"
        :total="entityFailureTotal"
        :page.sync="entityFailureQueryParams.pageNum"
        :limit.sync="entityFailureQueryParams.pageSize"
        @pagination="getEntityFailureList"
      />

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

<script>
import {
  addEntityIntermediary,
  addPersonIntermediary,
  delIntermediary,
  getEntityIntermediary,
  getPersonIntermediary,
  listIntermediary,
  updateEntityIntermediary,
  updatePersonIntermediary,
  getPersonImportFailures,
  getEntityImportFailures
} 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: [],
      // 导入失败记录相关状态
      showPersonFailureButton: false,
      showEntityFailureButton: false,
      currentPersonTaskId: null,
      currentEntityTaskId: null,
      personFailureDialogVisible: false,
      personFailureList: [],
      personFailureLoading: false,
      personFailureTotal: 0,
      personFailureQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      entityFailureDialogVisible: false,
      entityFailureList: [],
      entityFailureLoading: false,
      entityFailureTotal: 0,
      entityFailureQueryParams: {
        pageNum: 1,
        pageSize: 10
      }
    };
  },
  created() {
    this.getList();
    this.loadEnumOptions();
    this.restoreImportState();
  },
  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() {
      // 子组件已处理文件清理
    },
    /** 处理导入完成 */
    handleImportComplete(importData) {
      const { taskId, hasFailures, importType, totalCount, successCount, failureCount } = importData;

      if (importType === 'person') {
        // 保存个人导入任务
        this.savePersonImportTaskToStorage({
          taskId,
          hasFailures,
          totalCount,
          successCount,
          failureCount
        });

        // 更新按钮显示
        this.showPersonFailureButton = hasFailures;
        this.currentPersonTaskId = taskId;

      } else if (importType === 'entity') {
        // 保存实体导入任务
        this.saveEntityImportTaskToStorage({
          taskId,
          hasFailures,
          totalCount,
          successCount,
          failureCount
        });

        // 更新按钮显示
        this.showEntityFailureButton = hasFailures;
        this.currentEntityTaskId = taskId;
      }

      // 刷新列表
      this.getList();
    },
    /** ==================== 个人中介导入任务管理 ==================== */
    /** 保存个人导入任务到localStorage */
    savePersonImportTaskToStorage(taskData) {
      try {
        const data = {
          ...taskData,
          saveTime: Date.now()
        };
        localStorage.setItem('intermediary_person_import_last_task', JSON.stringify(data));
      } catch (error) {
        console.error('保存个人导入任务状态失败:', error);
      }
    },
    /** 从localStorage读取个人导入任务 */
    getPersonImportTaskFromStorage() {
      try {
        const data = localStorage.getItem('intermediary_person_import_last_task');
        if (!data) return null;

        const task = JSON.parse(data);

        // 数据格式校验
        if (!task || !task.taskId) {
          this.clearPersonImportTaskFromStorage();
          return null;
        }

        // 时间戳校验
        if (task.saveTime && typeof task.saveTime !== 'number') {
          this.clearPersonImportTaskFromStorage();
          return null;
        }

        // 过期检查(7天)
        const sevenDays = 7 * 24 * 60 * 60 * 1000;
        if (Date.now() - task.saveTime > sevenDays) {
          this.clearPersonImportTaskFromStorage();
          return null;
        }

        return task;
      } catch (error) {
        console.error('读取个人导入任务状态失败:', error);
        this.clearPersonImportTaskFromStorage();
        return null;
      }
    },
    /** 清除个人导入任务 */
    clearPersonImportTaskFromStorage() {
      try {
        localStorage.removeItem('intermediary_person_import_last_task');
      } catch (error) {
        console.error('清除个人导入任务状态失败:', error);
      }
    },
    /** 获取上次个人导入的提示信息 */
    getPersonImportTooltip() {
      const savedTask = this.getPersonImportTaskFromStorage();
      if (savedTask && savedTask.saveTime) {
        const date = new Date(savedTask.saveTime);
        const timeStr = this.parseTime(date, '{y}-{m}-{d} {h}:{i}');
        return `上次导入: ${timeStr}`;
      }
      return '';
    },
    /** 获取上次个人导入的统计信息 */
    getPersonLastImportInfo() {
      const savedTask = this.getPersonImportTaskFromStorage();
      if (savedTask && savedTask.totalCount) {
        return `导入时间: ${this.parseTime(savedTask.saveTime)} | 总数: ${savedTask.totalCount}条 | 成功: ${savedTask.successCount}条 | 失败: ${savedTask.failureCount}条`;
      }
      return '';
    },
    /** 查看个人导入失败记录 */
    viewPersonImportFailures() {
      this.personFailureDialogVisible = true;
      this.getPersonFailureList();
    },
    /** 查询个人失败记录列表 */
    getPersonFailureList() {
      this.personFailureLoading = true;
      getPersonImportFailures(
        this.currentPersonTaskId,
        this.personFailureQueryParams.pageNum,
        this.personFailureQueryParams.pageSize
      ).then(response => {
        this.personFailureList = response.rows;
        this.personFailureTotal = response.total;
        this.personFailureLoading = false;
      }).catch(error => {
        this.personFailureLoading = false;

        // 处理不同类型的错误
        if (error.response) {
          const status = error.response.status;

          if (status === 404) {
            // 记录不存在或已过期
            this.$modal.msgWarning('导入记录已过期,无法查看失败记录');
            this.clearPersonImportTaskFromStorage();
            this.showPersonFailureButton = false;
            this.currentPersonTaskId = null;
            this.personFailureDialogVisible = false;
          } else if (status === 500) {
            this.$modal.msgError('服务器错误,请稍后重试');
          } else {
            this.$modal.msgError(`查询失败: ${error.response.data.msg || '未知错误'}`);
          }
        } else if (error.request) {
          // 请求发送了但没有收到响应
          this.$modal.msgError('网络连接失败,请检查网络');
        } else {
          this.$modal.msgError('查询失败记录失败: ' + error.message);
        }
      });
    },
    /** 清除个人导入历史记录 */
    clearPersonImportHistory() {
      this.$confirm('确认清除上次导入记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearPersonImportTaskFromStorage();
        this.showPersonFailureButton = false;
        this.currentPersonTaskId = null;
        this.personFailureDialogVisible = false;
        this.$message.success('已清除');
      }).catch(() => {});
    },
    /** ==================== 实体中介导入任务管理 ==================== */
    /** 保存实体导入任务到localStorage */
    saveEntityImportTaskToStorage(taskData) {
      try {
        const data = {
          ...taskData,
          saveTime: Date.now()
        };
        localStorage.setItem('intermediary_entity_import_last_task', JSON.stringify(data));
      } catch (error) {
        console.error('保存实体导入任务状态失败:', error);
      }
    },
    /** 从localStorage读取实体导入任务 */
    getEntityImportTaskFromStorage() {
      try {
        const data = localStorage.getItem('intermediary_entity_import_last_task');
        if (!data) return null;

        const task = JSON.parse(data);

        // 数据格式校验
        if (!task || !task.taskId) {
          this.clearEntityImportTaskFromStorage();
          return null;
        }

        // 时间戳校验
        if (task.saveTime && typeof task.saveTime !== 'number') {
          this.clearEntityImportTaskFromStorage();
          return null;
        }

        // 过期检查(7天)
        const sevenDays = 7 * 24 * 60 * 60 * 1000;
        if (Date.now() - task.saveTime > sevenDays) {
          this.clearEntityImportTaskFromStorage();
          return null;
        }

        return task;
      } catch (error) {
        console.error('读取实体导入任务状态失败:', error);
        this.clearEntityImportTaskFromStorage();
        return null;
      }
    },
    /** 清除实体导入任务 */
    clearEntityImportTaskFromStorage() {
      try {
        localStorage.removeItem('intermediary_entity_import_last_task');
      } catch (error) {
        console.error('清除实体导入任务状态失败:', error);
      }
    },
    /** 获取上次实体导入的提示信息 */
    getEntityImportTooltip() {
      const savedTask = this.getEntityImportTaskFromStorage();
      if (savedTask && savedTask.saveTime) {
        const date = new Date(savedTask.saveTime);
        const timeStr = this.parseTime(date, '{y}-{m}-{d} {h}:{i}');
        return `上次导入: ${timeStr}`;
      }
      return '';
    },
    /** 获取上次实体导入的统计信息 */
    getEntityLastImportInfo() {
      const savedTask = this.getEntityImportTaskFromStorage();
      if (savedTask && savedTask.totalCount) {
        return `导入时间: ${this.parseTime(savedTask.saveTime)} | 总数: ${savedTask.totalCount}条 | 成功: ${savedTask.successCount}条 | 失败: ${savedTask.failureCount}条`;
      }
      return '';
    },
    /** 查看实体导入失败记录 */
    viewEntityImportFailures() {
      this.entityFailureDialogVisible = true;
      this.getEntityFailureList();
    },
    /** 查询实体失败记录列表 */
    getEntityFailureList() {
      this.entityFailureLoading = true;
      getEntityImportFailures(
        this.currentEntityTaskId,
        this.entityFailureQueryParams.pageNum,
        this.entityFailureQueryParams.pageSize
      ).then(response => {
        this.entityFailureList = response.rows;
        this.entityFailureTotal = response.total;
        this.entityFailureLoading = false;
      }).catch(error => {
        this.entityFailureLoading = false;

        // 处理不同类型的错误
        if (error.response) {
          const status = error.response.status;

          if (status === 404) {
            // 记录不存在或已过期
            this.$modal.msgWarning('导入记录已过期,无法查看失败记录');
            this.clearEntityImportTaskFromStorage();
            this.showEntityFailureButton = false;
            this.currentEntityTaskId = null;
            this.entityFailureDialogVisible = false;
          } else if (status === 500) {
            this.$modal.msgError('服务器错误,请稍后重试');
          } else {
            this.$modal.msgError(`查询失败: ${error.response.data.msg || '未知错误'}`);
          }
        } else if (error.request) {
          // 请求发送了但没有收到响应
          this.$modal.msgError('网络连接失败,请检查网络');
        } else {
          this.$modal.msgError('查询失败记录失败: ' + error.message);
        }
      });
    },
    /** 清除实体导入历史记录 */
    clearEntityImportHistory() {
      this.$confirm('确认清除上次导入记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearEntityImportTaskFromStorage();
        this.showEntityFailureButton = false;
        this.currentEntityTaskId = null;
        this.entityFailureDialogVisible = false;
        this.$message.success('已清除');
      }).catch(() => {});
    },
    /** ==================== 导入状态恢复 ==================== */
    /** 恢复导入状态 */
    restoreImportState() {
      // 恢复个人中介导入状态
      const personTask = this.getPersonImportTaskFromStorage();
      if (personTask && personTask.hasFailures && personTask.taskId) {
        this.currentPersonTaskId = personTask.taskId;
        this.showPersonFailureButton = true;
      }

      // 恢复实体中介导入状态
      const entityTask = this.getEntityImportTaskFromStorage();
      if (entityTask && entityTask.hasFailures && entityTask.taskId) {
        this.currentEntityTaskId = entityTask.taskId;
        this.showEntityFailureButton = true;
      }
    }
  }
};
</script>
