<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="128px" class="query-form">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="员工姓名" prop="personName">
            <el-input
              v-model="queryParams.personName"
              placeholder="请输入员工姓名"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关系类型" prop="relationType">
            <el-select v-model="queryParams.relationType" placeholder="请选择关系类型" clearable style="width: 100%">
              <el-option
                v-for="item in relationTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关系人姓名" prop="relationName">
            <el-input
              v-model="queryParams.relationName"
              placeholder="请输入关系人姓名"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关系人身份证号" prop="relationCertNo">
            <el-input
              v-model="queryParams.relationCertNo"
              placeholder="请输入关系人身份证号"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100%">
              <el-option label="有效" :value="1" />
              <el-option label="无效" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <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:staffFmyRelation: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:staffFmyRelation:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5" v-if="showFailureButton">
        <el-tooltip
          :content="getLastImportTooltip()"
          placement="top"
        >
          <el-button
            type="warning"
            plain
            icon="el-icon-warning"
            size="mini"
            @click="viewImportFailures"
          >查看导入失败记录</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5" v-if="assetShowFailureButton">
        <el-tooltip
          :content="getLastAssetImportTooltip()"
          placement="top"
        >
          <el-button
            type="warning"
            plain
            icon="el-icon-warning-outline"
            size="mini"
            @click="viewAssetImportFailures"
          >查看亲属资产导入失败记录</el-button>
        </el-tooltip>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="relationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工姓名" align="center" prop="personName" :show-overflow-tooltip="true"/>
      <el-table-column label="员工身份证号" align="center" prop="personId" width="190" :show-overflow-tooltip="true"/>
      <el-table-column label="关系类型" align="center" prop="relationType" width="100">
        <template slot-scope="scope">
          <enum-tag type="relationType" :value="scope.row.relationType"/>
        </template>
      </el-table-column>
      <el-table-column label="关系人姓名" align="center" prop="relationName" :show-overflow-tooltip="true"/>
      <el-table-column label="关系人身份证号" align="center" prop="relationCertNo" width="190" :show-overflow-tooltip="true"/>
      <el-table-column label="家庭成员年收入" align="center" prop="annualIncome" width="160"/>
      <el-table-column label="性别" align="center" prop="gender" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ccdi_indiv_gender" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="mobilePhone1" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '有效' : '无效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['ccdi:staffFmyRelation:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ccdi:staffFmyRelation:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ccdi:staffFmyRelation:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body class="relation-edit-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="员工身份证号" prop="personId">
              <el-select
                v-model="form.personId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入身份证号搜索员工"
                :remote-method="searchStaff"
                :loading="staffLoading"
                :disabled="!isAdd"
                @focus="handleSelectFocus"
                style="width: 100%"
              >
                <el-option
                  v-for="item in staffOptions"
                  :key="item.idCard"
                  :label="item.idCard + ' - ' + item.name"
                  :value="item.idCard"
                >
                  <span style="float: left">{{ item.idCard }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关系类型" prop="relationType">
              <el-select v-model="form.relationType" placeholder="请选择关系类型" style="width: 100%">
                <el-option
                  v-for="item in relationTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="关系人姓名" prop="relationName">
              <el-input v-model="form.relationName" placeholder="请输入关系人姓名" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.ccdi_indiv_gender"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="关系人证件类型" prop="relationCertType">
              <el-select v-model="form.relationCertType" placeholder="请选择证件类型" style="width: 100%" :disabled="!isAdd">
                <el-option
                  v-for="item in certTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关系人证件号码" prop="relationCertNo">
              <el-input v-model="form.relationCertNo" placeholder="请输入证件号码" maxlength="100" :disabled="!isAdd" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码1" prop="mobilePhone1">
              <el-input v-model="form.mobilePhone1" placeholder="请输入手机号码1" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="手机号码2" prop="mobilePhone2">
              <el-input v-model="form.mobilePhone2" placeholder="请输入手机号码2" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭成员年收入" prop="annualIncome">
              <el-input v-model="form.annualIncome" placeholder="请输入家庭成员年收入（元/年）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="微信名称1" prop="wechatNo1">
              <el-input v-model="form.wechatNo1" placeholder="请输入微信名称1" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="微信名称2" prop="wechatNo2">
              <el-input v-model="form.wechatNo2" placeholder="请输入微信名称2" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信名称3" prop="wechatNo3">
              <el-input v-model="form.wechatNo3" placeholder="请输入微信名称3" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="状态" prop="status" v-if="!isAdd">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">有效</el-radio>
                <el-radio :label="0">无效</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isAdd">
            <!-- 占位,保持布局对齐 -->
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="form.effectiveDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期" prop="invalidDate">
              <el-date-picker
                v-model="form.invalidDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详细联系地址" prop="contactAddress">
          <el-input v-model="form.contactAddress" type="textarea" :rows="2" placeholder="请输入详细联系地址" />
        </el-form-item>
        <el-form-item label="关系详细描述" prop="relationDesc">
          <el-input v-model="form.relationDesc" type="textarea" :rows="2" placeholder="请输入关系详细描述" />
        </el-form-item>
        <div class="asset-section-header">
          <span>亲属资产信息</span>
          <el-tooltip :disabled="canAddAsset" content="请先填写关系人证件信息" placement="top">
            <span>
              <el-button type="primary" plain size="mini" icon="el-icon-plus" :disabled="!canAddAsset" @click="handleAddAsset">新增资产</el-button>
            </span>
          </el-tooltip>
        </div>
        <el-form-item label-width="0" prop="assetInfoList">
          <div v-if="!form.assetInfoList || !form.assetInfoList.length" class="empty-assets">
            <i class="el-icon-office-building"></i>
            <span>暂无亲属资产信息，请点击新增资产</span>
          </div>
          <div v-else class="assets-table-wrapper">
            <el-table :data="form.assetInfoList" border class="assets-table">
              <el-table-column label="资产大类" min-width="140">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.assetMainType" placeholder="请输入资产大类" />
                </template>
              </el-table-column>
              <el-table-column label="资产小类" min-width="140">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.assetSubType" placeholder="请输入资产小类" />
                </template>
              </el-table-column>
              <el-table-column label="资产名称" min-width="160">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.assetName" placeholder="请输入资产名称" />
                </template>
              </el-table-column>
              <el-table-column label="产权占比" min-width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.ownershipRatio" placeholder="请输入产权占比" />
                </template>
              </el-table-column>
              <el-table-column label="购买/评估日期" min-width="160">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.purchaseEvalDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="资产原值" min-width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.originalValue" placeholder="请输入资产原值" />
                </template>
              </el-table-column>
              <el-table-column label="当前估值" min-width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.currentValue" placeholder="请输入当前估值" />
                </template>
              </el-table-column>
              <el-table-column label="估值截止日期" min-width="160">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.valuationDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="资产状态" min-width="140">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.assetStatus" placeholder="请选择资产状态" style="width: 100%">
                    <el-option
                      v-for="option in assetStatusOptions"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remarks" placeholder="请输入备注" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="90" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" icon="el-icon-delete" @click="handleRemoveAsset(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="员工亲属关系详情" :visible.sync="detailOpen" width="80%" append-to-body class="relation-detail-dialog">
      <div class="detail-container">
        <el-divider content-position="left">基本信息</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="员工姓名">{{ relationDetail.personName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="员工身份证号">{{ relationDetail.personId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="关系类型">
            <enum-tag type="relationType" :value="relationDetail.relationType"/>
          </el-descriptions-item>
          <el-descriptions-item label="关系人姓名">{{ relationDetail.relationName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            <dict-tag :options="dict.type.ccdi_indiv_gender" :value="relationDetail.gender"/>
          </el-descriptions-item>
          <el-descriptions-item label="关系人证件类型">
            <enum-tag type="certType" :value="relationDetail.relationCertType"/>
          </el-descriptions-item>
          <el-descriptions-item label="关系人证件号码" :span="2">{{ relationDetail.relationCertNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ relationDetail.birthDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="手机号码1">{{ relationDetail.mobilePhone1 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="手机号码2">{{ relationDetail.mobilePhone2 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="家庭成员年收入">
            {{ relationDetail.annualIncome !== null && relationDetail.annualIncome !== undefined && relationDetail.annualIncome !== '' ? relationDetail.annualIncome : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="微信名称1">{{ relationDetail.wechatNo1 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="微信名称2">{{ relationDetail.wechatNo2 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="微信名称3">{{ relationDetail.wechatNo3 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="详细联系地址" :span="2">{{ relationDetail.contactAddress || '-' }}</el-descriptions-item>
          <el-descriptions-item label="关系详细描述" :span="2">{{ relationDetail.relationDesc || '-' }}</el-descriptions-item>
          <el-descriptions-item label="生效日期">{{ relationDetail.effectiveDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="失效日期">{{ relationDetail.invalidDate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="relationDetail.status === 1 ? 'success' : 'danger'">
              {{ relationDetail.status === 1 ? '有效' : '无效' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="数据来源">{{ relationDetail.dataSource || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ relationDetail.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">亲属资产信息</el-divider>
        <div v-if="!relationDetail.assetInfoList || !relationDetail.assetInfoList.length" class="empty-assets-detail">
          暂无亲属资产信息
        </div>
        <el-table v-else :data="relationDetail.assetInfoList" border class="detail-assets-table">
          <el-table-column label="资产大类" prop="assetMainType" min-width="140" />
          <el-table-column label="资产小类" prop="assetSubType" min-width="140" />
          <el-table-column label="资产名称" prop="assetName" min-width="160" />
          <el-table-column label="产权占比" prop="ownershipRatio" min-width="120" />
          <el-table-column label="购买/评估日期" prop="purchaseEvalDate" min-width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.purchaseEvalDate ? parseTime(scope.row.purchaseEvalDate, '{y}-{m}-{d}') : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="资产原值" prop="originalValue" min-width="120" />
          <el-table-column label="当前估值" min-width="120">
            <template slot-scope="scope">
              <span>{{ formatWanAmount(scope.row.currentValue) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="估值截止日期" prop="valuationDate" min-width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.valuationDate ? parseTime(scope.row.valuationDate, '{y}-{m}-{d}') : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="资产状态" prop="assetStatus" min-width="120" />
          <el-table-column label="备注" prop="remarks" min-width="180" show-overflow-tooltip />
        </el-table>

        <el-divider content-position="left">审计信息</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="创建时间">
            {{ relationDetail.createTime ? parseTime(relationDetail.createTime) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建人">{{ relationDetail.createdBy || '-' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ relationDetail.updateTime ? parseTime(relationDetail.updateTime) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="更新人">{{ relationDetail.updatedBy || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false" icon="el-icon-close">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      @close="handleImportDialogClose"
      v-loading="upload.isUploading"
      element-loading-text="正在导入数据,请稍候..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.7)"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" slot="tip">
          <span>模板包含“员工亲属关系信息”和“亲属资产信息”两个Sheet，可单独填写其中一个，也可同时填写两个。</span>
        </div>
        <div class="el-upload__tip" slot="tip">
          <span>仅允许导入"xls"或"xlsx"格式文件；亲属资产Sheet将根据关系人证件号自动识别归属员工。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入失败记录对话框 -->
    <el-dialog
      title="导入失败记录"
      :visible.sync="failureDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-alert
        v-if="lastImportInfo"
        :title="lastImportInfo"
        type="info"
        :closable="false"
        style="margin-bottom: 15px"
      />

      <el-table :data="failureList" v-loading="failureLoading">
        <el-table-column label="Sheet" prop="sheetName" align="center" min-width="120"/>
        <el-table-column label="Excel行号" prop="rowNum" align="center" width="100"/>
        <el-table-column label="员工身份证号" prop="personId" align="center" width="180"/>
        <el-table-column label="关系类型" prop="relationType" align="center" width="100"/>
        <el-table-column label="关系人姓名" prop="relationName" align="center" width="120"/>
        <el-table-column label="家庭成员年收入" prop="annualIncome" align="center" width="160"/>
        <el-table-column label="失败原因" prop="errorMessage" align="center" min-width="200" :show-overflow-tooltip="true" />
      </el-table>

      <pagination
        v-show="failureTotal > 0"
        :total="failureTotal"
        :page.sync="failureQueryParams.pageNum"
        :limit.sync="failureQueryParams.pageSize"
        @pagination="getFailureList"
      />

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

    <el-dialog
      title="亲属资产导入失败记录"
      :visible.sync="assetFailureDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-alert
        v-if="lastAssetImportInfo"
        :title="lastAssetImportInfo"
        type="info"
        :closable="false"
        style="margin-bottom: 15px"
      />

      <el-table :data="assetFailureList" v-loading="assetFailureLoading">
        <el-table-column label="Sheet" prop="sheetName" align="center" min-width="120" />
        <el-table-column label="Excel行号" prop="rowNum" align="center" width="100" />
        <el-table-column label="关系人证件号" prop="personId" align="center" min-width="180" />
        <el-table-column label="资产大类" prop="assetMainType" align="center" min-width="120" />
        <el-table-column label="资产小类" prop="assetSubType" align="center" min-width="120" />
        <el-table-column label="资产名称" prop="assetName" align="center" min-width="150" />
        <el-table-column label="当前估值" align="center" min-width="120">
          <template slot-scope="scope">
            <span>{{ formatWanAmount(scope.row.currentValue) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="资产状态" prop="assetStatus" align="center" min-width="120" />
        <el-table-column label="失败原因" prop="errorMessage" align="center" min-width="220" :show-overflow-tooltip="true" />
      </el-table>

      <pagination
        v-show="assetFailureTotal > 0"
        :total="assetFailureTotal"
        :page.sync="assetFailureQueryParams.pageNum"
        :limit.sync="assetFailureQueryParams.pageSize"
        @pagination="getAssetFailureList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="assetFailureDialogVisible = false">关闭</el-button>
        <el-button type="danger" plain @click="clearAssetImportHistory">清除资产导入历史</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addRelation,
  delRelation,
  getImportFailures,
  getImportStatus,
  getRelation,
  listRelation,
  updateRelation
} from "@/api/ccdiStaffFmyRelation";
import {
  getAssetImportFailures,
  getAssetImportStatus
} from "@/api/ccdiAssetInfo";
import {listBaseStaff} from "@/api/ccdiBaseStaff";
import {getToken} from "@/utils/auth";
import EnumTag from '@/components/EnumTag'

export default {
  name: "StaffFmyRelation",
  dicts: ['ccdi_indiv_gender'],
  components: {
    EnumTag
  },
  data() {
    return {
      // 枚举选项
      relationTypeOptions: [],
      certTypeOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工亲属关系表格数据
      relationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 员工亲属关系详情
      relationDetail: {},
      // 是否为新增操作
      isAdd: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personName: null,
        relationType: null,
        relationName: null,
        relationCertNo: null,
        status: null
      },
      // 表单参数
      form: {},
      assetStatusOptions: [
        { label: "正常", value: "正常" },
        { label: "冻结", value: "冻结" },
        { label: "处置中", value: "处置中" },
        { label: "报废", value: "报废" }
      ],
      // 表单校验
      rules: {
        personId: [
          { required: true, message: "员工身份证号不能为空", trigger: "blur" },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: "请输入正确的18位身份证号", trigger: "blur" }
        ],
        relationType: [
          { required: true, message: "关系类型不能为空", trigger: "change" }
        ],
        relationName: [
          { required: true, message: "关系人姓名不能为空", trigger: "blur" }
        ],
        relationCertType: [
          { required: true, message: "关系人证件类型不能为空", trigger: "change" }
        ],
        relationCertNo: [
          { required: true, message: "关系人证件号码不能为空", trigger: "blur" }
        ],
        mobilePhone1: [
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        mobilePhone2: [
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        annualIncome: [
          { validator: (rule, value, callback) => this.validateAnnualIncomeRule(value, callback, "家庭成员年收入"), trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ccdi/staffFmyRelation/importData"
      },
      // 导入轮询定时器
      importPollingTimer: null,
      // 是否显示查看失败记录按钮
      showFailureButton: false,
      // 当前导入任务ID
      currentTaskId: null,
      // 失败记录对话框
      failureDialogVisible: false,
      failureList: [],
      failureLoading: false,
      failureTotal: 0,
      failureQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      assetImportPollingTimer: null,
      assetShowFailureButton: false,
      assetCurrentTaskId: null,
      assetFailureDialogVisible: false,
      assetFailureList: [],
      assetFailureLoading: false,
      assetFailureTotal: 0,
      assetFailureQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 员工选项
      staffOptions: [],
      staffLoading: false
    };
  },
  computed: {
    /**
     * 上次导入信息摘要
     */
    lastImportInfo() {
      const savedTask = this.getImportTaskFromStorage();
      if (savedTask && savedTask.totalCount) {
        return `导入时间: ${this.parseTime(savedTask.saveTime)} | 总数: ${savedTask.totalCount}条 | 成功: ${savedTask.successCount}条 | 失败: ${savedTask.failureCount}条`;
      }
      return '';
    },
    lastAssetImportInfo() {
      const savedTask = this.getAssetImportTaskFromStorage();
      if (savedTask && savedTask.totalCount) {
        return `导入时间: ${this.parseTime(savedTask.saveTime)} | 总数: ${savedTask.totalCount}条 | 成功: ${savedTask.successCount}条 | 失败: ${savedTask.failureCount}条`;
      }
      return '';
    },
    canAddAsset() {
      return Boolean(this.form.relationCertType && String(this.form.relationCertNo || '').trim())
    }
  },
  created() {
    this.getList();
    this.restoreImportState();
    this.restoreAssetImportState();
    this.loadEnumOptions();
  },
  beforeDestroy() {
    if (this.importPollingTimer) {
      clearInterval(this.importPollingTimer);
      this.importPollingTimer = null;
    }
    if (this.assetImportPollingTimer) {
      clearInterval(this.assetImportPollingTimer);
      this.assetImportPollingTimer = null;
    }
  },
  methods: {
    /**
     * 加载枚举选项
     */
    async loadEnumOptions() {
      try {
        this.relationTypeOptions = await this.$store.dispatch('ccdiEnum/getRelationTypeOptions')
        this.certTypeOptions = await this.$store.dispatch('ccdiEnum/getCertTypeOptions')
      } catch (error) {
        console.error('加载枚举选项失败:', error)
      }
    },
    /** 查询员工亲属关系列表 */
    getList() {
      this.loading = true;
      listRelation(this.queryParams).then(response => {
        this.relationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索员工 */
    searchStaff(query) {
      this.staffLoading = true;
      // 如果输入为空，查询所有员工；否则根据身份证号模糊查询
      const params = query !== '' ? { idCard: query, pageNum: 1, pageSize: 10 } : { pageNum: 1, pageSize: 10 };
      listBaseStaff(params).then(response => {
        this.staffOptions = response.rows;
        this.staffLoading = false;
      }).catch(() => {
        this.staffLoading = false;
      });
    },
    /** 下拉框获得焦点时加载员工列表 */
    handleSelectFocus() {
      // 如果选项列表为空，自动加载所有员工
      if (!this.staffOptions || this.staffOptions.length === 0) {
        this.searchStaff('');
      }
    },
    /**
     * 恢复导入状态
     */
    restoreImportState() {
      const savedTask = this.getImportTaskFromStorage();
      if (!savedTask) {
        this.showFailureButton = false;
        this.currentTaskId = null;
        return;
      }
      if (savedTask.hasFailures && savedTask.taskId) {
        this.currentTaskId = savedTask.taskId;
        this.showFailureButton = true;
      }
    },
    restoreAssetImportState() {
      const savedTask = this.getAssetImportTaskFromStorage();
      if (!savedTask) {
        this.assetShowFailureButton = false;
        this.assetCurrentTaskId = null;
        return;
      }
      if (savedTask.hasFailures && savedTask.taskId) {
        this.assetCurrentTaskId = savedTask.taskId;
        this.assetShowFailureButton = true;
      }
    },
    /**
     * 获取上次导入的提示信息
     */
    getLastImportTooltip() {
      const savedTask = this.getImportTaskFromStorage();
      if (savedTask && savedTask.saveTime) {
        const date = new Date(savedTask.saveTime);
        const timeStr = this.parseTime(date, '{y}-{m}-{d} {h}:{i}');
        return `上次导入: ${timeStr}`;
      }
      return '';
    },
    getLastAssetImportTooltip() {
      const savedTask = this.getAssetImportTaskFromStorage();
      if (savedTask && savedTask.saveTime) {
        const date = new Date(savedTask.saveTime);
        const timeStr = this.parseTime(date, '{y}-{m}-{d} {h}:{i}');
        return `上次亲属资产导入: ${timeStr}`;
      }
      return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        personId: null,
        relationType: null,
        relationName: null,
        gender: null,
        birthDate: null,
        relationCertType: null,
        relationCertNo: null,
        mobilePhone1: null,
        mobilePhone2: null,
        annualIncome: null,
        wechatNo1: null,
        wechatNo2: null,
        wechatNo3: null,
        contactAddress: null,
        relationDesc: null,
        effectiveDate: null,
        invalidDate: null,
        status: 1,
        remark: null,
        assetInfoList: []
      };
      this.staffOptions = [];
      this.resetForm("form");
    },
    formatWanAmount(value) {
      if (value === null || value === undefined || value === "") {
        return "-";
      }
      const amount = Number(value);
      if (!Number.isFinite(amount)) {
        return "-";
      }
      return `${(amount / 10000).toLocaleString("zh-CN", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })} 万元`;
    },
    normalizeAnnualIncome(value) {
      if (value === null || value === undefined) {
        return null;
      }
      const normalized = String(value).trim();
      return normalized === "" ? null : normalized;
    },
    validateAnnualIncome(value, fieldLabel = "家庭成员年收入") {
      const normalized = this.normalizeAnnualIncome(value);
      if (normalized === null) {
        return true;
      }
      if (!/^\d+(\.\d{1,2})?$/.test(normalized)) {
        this.$modal.msgError(`${fieldLabel}格式不正确，需为非负金额且最多保留2位小数`);
        return false;
      }
      return true;
    },
    validateAnnualIncomeRule(value, callback, fieldLabel = "家庭成员年收入") {
      const normalized = this.normalizeAnnualIncome(value);
      if (normalized === null) {
        callback();
        return;
      }
      if (!/^\d+(\.\d{1,2})?$/.test(normalized)) {
        callback(new Error(`${fieldLabel}格式不正确，需为非负金额且最多保留2位小数`));
        return;
      }
      callback();
    },
    createEmptyAssetRow() {
      return {
        assetMainType: "",
        assetSubType: "",
        assetName: "",
        ownershipRatio: "",
        purchaseEvalDate: "",
        originalValue: "",
        currentValue: "",
        valuationDate: "",
        assetStatus: "",
        remarks: ""
      };
    },
    hasAssetContent(row) {
      if (!row || typeof row !== "object") {
        return false;
      }
      return Object.keys(row).some(key => {
        const value = row[key];
        return value !== null && value !== undefined && String(value).trim() !== "";
      });
    },
    normalizeAssetInfoList() {
      const assetInfoList = Array.isArray(this.form.assetInfoList)
        ? this.form.assetInfoList
        : [];
      return assetInfoList.filter(item => this.hasAssetContent(item));
    },
    validateAssetInfoList(assetInfoList) {
      const requiredFields = [
        { key: "assetMainType", label: "资产大类" },
        { key: "assetSubType", label: "资产小类" },
        { key: "assetName", label: "资产名称" },
        { key: "currentValue", label: "当前估值" },
        { key: "assetStatus", label: "资产状态" }
      ];
      const numericFields = [
        { key: "ownershipRatio", label: "产权占比" },
        { key: "originalValue", label: "资产原值" },
        { key: "currentValue", label: "当前估值" }
      ];

      for (let index = 0; index < assetInfoList.length; index++) {
        const asset = assetInfoList[index];
        const rowNo = index + 1;

        for (const field of requiredFields) {
          const value = asset[field.key];
          if (value === null || value === undefined || String(value).trim() === "") {
            this.$modal.msgError(`第${rowNo}条资产的${field.label}不能为空`);
            return false;
          }
        }

        for (const field of numericFields) {
          const value = asset[field.key];
          if (value !== null && value !== undefined && String(value).trim() !== "") {
            if (!/^-?\d+(\.\d+)?$/.test(String(value).trim())) {
              this.$modal.msgError(`第${rowNo}条资产的${field.label}格式不正确`);
              return false;
            }
          }
        }

        if (!this.assetStatusOptions.some(option => option.value === asset.assetStatus)) {
          this.$modal.msgError(`第${rowNo}条资产的资产状态不在允许范围内`);
          return false;
        }
      }

      return true;
    },
    handleAddAsset() {
      if (!this.canAddAsset) {
        this.$modal.msgWarning("请先填写关系人证件信息");
        return;
      }
      if (!Array.isArray(this.form.assetInfoList)) {
        this.form.assetInfoList = [];
      }
      this.form.assetInfoList.push(this.createEmptyAssetRow());
    },
    handleRemoveAsset(index) {
      if (!Array.isArray(this.form.assetInfoList)) {
        return;
      }
      this.form.assetInfoList.splice(index, 1);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    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 = "添加员工亲属关系";
      this.isAdd = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getRelation(id).then(response => {
        this.form = {
          ...response.data,
          assetInfoList: response.data.assetInfoList || []
        };
        this.form.annualIncome = response.data.annualIncome;
        // 加载员工信息以支持下拉显示
        if (this.form.personId) {
          this.searchStaff(this.form.personId);
        }
        this.open = true;
        this.title = "修改员工亲属关系";
        this.isAdd = false;
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const id = row.id;
      getRelation(id).then(response => {
        this.relationDetail = {
          ...response.data,
          assetInfoList: response.data.assetInfoList || []
        };
        this.detailOpen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.assetInfoList = this.normalizeAssetInfoList();
          if (!this.validateAssetInfoList(this.form.assetInfoList)) {
            return;
          }

          const payload = {
            ...this.form,
            assetInfoList: this.form.assetInfoList.map(item => ({ ...item }))
          };
          payload.annualIncome = this.normalizeAnnualIncome(payload.annualIncome);
          if (!this.validateAnnualIncome(payload.annualIncome, "家庭成员年收入")) {
            return;
          }
          payload.assetInfoList.forEach((asset, index) => {
            delete payload.assetInfoList[index].familyId;
            delete payload.assetInfoList[index].personId;
            delete asset.familyId;
            delete asset.personId;
          });

          if (this.isAdd) {
            addRelation(payload).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          } else {
            updateRelation(payload).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delRelation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "员工亲属关系维护导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('ccdi/staffFmyRelation/importTemplate', {}, `员工亲属关系维护导入模板_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.upload.open = false;

      if (response.code !== 200) {
        this.$modal.msgError(response.msg);
        return;
      }

      const importResult = response.data || {}
      const relationTaskId = importResult.relationTaskId
      const assetTaskId = importResult.assetTaskId

      if (!relationTaskId && !assetTaskId) {
        this.$modal.msgError('导入任务创建失败:缺少任务ID');
        this.upload.open = true;
        return;
      }

      if (relationTaskId) {
        if (this.importPollingTimer) {
          clearInterval(this.importPollingTimer);
          this.importPollingTimer = null;
        }

        this.clearImportTaskFromStorage();
        this.saveImportTaskToStorage({
          taskId: relationTaskId,
          status: 'PROCESSING',
          timestamp: Date.now(),
          hasFailures: false
        });
        this.showFailureButton = false;
        this.currentTaskId = relationTaskId;
        this.startImportStatusPolling(relationTaskId);
      }

      if (assetTaskId) {
        if (this.assetImportPollingTimer) {
          clearInterval(this.assetImportPollingTimer);
          this.assetImportPollingTimer = null;
        }

        this.clearAssetImportTaskFromStorage();
        this.saveAssetImportTaskToStorage({
          taskId: assetTaskId,
          status: 'PROCESSING',
          timestamp: Date.now(),
          hasFailures: false
        });
        this.assetShowFailureButton = false;
        this.assetCurrentTaskId = assetTaskId;
        this.startAssetImportStatusPolling(assetTaskId);
      }

      this.$notify({
        title: '导入任务已提交',
        message: importResult.message || '正在后台处理中,处理完成后将通知您',
        type: 'info',
        duration: 3000
      });
    },
    /** 开始轮询导入状态 */
    startImportStatusPolling(taskId) {
      let pollCount = 0;
      const maxPolls = 150;

      this.importPollingTimer = setInterval(async () => {
        try {
          pollCount++;

          if (pollCount > maxPolls) {
            clearInterval(this.importPollingTimer);
            this.$modal.msgWarning('导入任务处理超时,请联系管理员');
            return;
          }

          const response = await getImportStatus(taskId);

          if (response.data && response.data.status !== 'PROCESSING') {
            clearInterval(this.importPollingTimer);
            this.handleImportComplete(response.data);
          }
        } catch (error) {
          clearInterval(this.importPollingTimer);
          this.$modal.msgError('查询导入状态失败: ' + error.message);
        }
      }, 2000);
    },
    startAssetImportStatusPolling(taskId) {
      let pollCount = 0;
      const maxPolls = 150;

      this.assetImportPollingTimer = setInterval(async () => {
        try {
          pollCount++;

          if (pollCount > maxPolls) {
            clearInterval(this.assetImportPollingTimer);
            this.$modal.msgWarning('亲属资产导入任务处理超时,请联系管理员');
            return;
          }

          const response = await getAssetImportStatus(taskId);

          if (response.data && response.data.status !== 'PROCESSING') {
            clearInterval(this.assetImportPollingTimer);
            this.handleAssetImportComplete(response.data);
          }
        } catch (error) {
          clearInterval(this.assetImportPollingTimer);
          this.$modal.msgError('查询亲属资产导入状态失败: ' + error.message);
        }
      }, 2000);
    },
    /** 查询失败记录列表 */
    getFailureList() {
      this.failureLoading = true;
      getImportFailures(
        this.currentTaskId,
        this.failureQueryParams.pageNum,
        this.failureQueryParams.pageSize
      ).then(response => {
        this.failureList = response.rows;
        this.failureTotal = response.total;
        this.failureLoading = false;
      }).catch(error => {
        this.failureLoading = false;
        if (error.response && error.response.status === 404) {
          this.$modal.msgWarning('导入记录已过期,无法查看失败记录');
          this.clearImportTaskFromStorage();
          this.showFailureButton = false;
          this.currentTaskId = null;
          this.failureDialogVisible = false;
        } else {
          this.$modal.msgError('查询失败记录失败');
        }
      });
    },
    getAssetFailureList() {
      this.assetFailureLoading = true;
      getAssetImportFailures(
        this.assetCurrentTaskId,
        this.assetFailureQueryParams.pageNum,
        this.assetFailureQueryParams.pageSize
      ).then(response => {
        this.assetFailureList = response.rows;
        this.assetFailureTotal = response.total;
        this.assetFailureLoading = false;
      }).catch(error => {
        this.assetFailureLoading = false;
        if (error.response && error.response.status === 404) {
          this.$modal.msgWarning('亲属资产导入记录已过期,无法查看失败记录');
          this.clearAssetImportTaskFromStorage();
          this.assetShowFailureButton = false;
          this.assetCurrentTaskId = null;
          this.assetFailureDialogVisible = false;
        } else if (error.response && error.response.status === 500) {
          this.$modal.msgError('服务器错误,请稍后重试');
        } else if (error.request) {
          this.$modal.msgError('网络连接失败,请检查网络');
        } else {
          this.$modal.msgError('查询亲属资产失败记录失败');
        }
      });
    },
    /** 查看导入失败记录 */
    viewImportFailures() {
      this.failureDialogVisible = true;
      this.getFailureList();
    },
    viewAssetImportFailures() {
      this.assetFailureDialogVisible = true;
      this.getAssetFailureList();
    },
    /** 处理导入完成 */
    handleImportComplete(statusResult) {
      this.saveImportTaskToStorage({
        taskId: statusResult.taskId,
        status: statusResult.status,
        hasFailures: statusResult.failureCount > 0,
        totalCount: statusResult.totalCount,
        successCount: statusResult.successCount,
        failureCount: statusResult.failureCount
      });

      if (statusResult.status === 'SUCCESS') {
        this.$notify({
          title: '导入完成',
          message: `全部成功!共导入${statusResult.totalCount}条数据`,
          type: 'success',
          duration: 5000
        });
        this.showFailureButton = false;
        this.getList();
      } else if (statusResult.failureCount > 0) {
        this.$notify({
          title: '导入完成',
          message: `成功${statusResult.successCount}条,失败${statusResult.failureCount}条`,
          type: 'warning',
          duration: 5000
        });
        this.showFailureButton = true;
        this.currentTaskId = statusResult.taskId;
        this.getList();
      }
    },
    handleAssetImportComplete(statusResult) {
      this.saveAssetImportTaskToStorage({
        taskId: statusResult.taskId,
        status: statusResult.status,
        hasFailures: statusResult.failureCount > 0,
        totalCount: statusResult.totalCount,
        successCount: statusResult.successCount,
        failureCount: statusResult.failureCount
      });

      if (statusResult.status === 'SUCCESS') {
        this.$notify({
          title: '亲属资产导入完成',
          message: `全部成功!共导入${statusResult.totalCount}条数据`,
          type: 'success',
          duration: 5000
        });
        this.assetShowFailureButton = false;
        this.getList();
      } else if (statusResult.failureCount > 0) {
        this.$notify({
          title: '亲属资产导入完成',
          message: `成功${statusResult.successCount}条,失败${statusResult.failureCount}条`,
          type: 'warning',
          duration: 5000
        });
        this.assetShowFailureButton = true;
        this.assetCurrentTaskId = statusResult.taskId;
        this.getList();
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 关闭导入对话框
    handleImportDialogClose() {
      this.upload.isUploading = false;
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      });
    },
    /**
     * 保存导入任务到localStorage
     */
    saveImportTaskToStorage(taskData) {
      try {
        const data = {
          ...taskData,
          saveTime: Date.now()
        };
        localStorage.setItem('staff_fmy_relation_import_last_task', JSON.stringify(data));
      } catch (error) {
        console.error('保存导入任务状态失败:', error);
      }
    },
    saveAssetImportTaskToStorage(taskData) {
      try {
        const data = {
          ...taskData,
          saveTime: Date.now()
        };
        localStorage.setItem('staff_fmy_asset_import_last_task', JSON.stringify(data));
      } catch (error) {
        console.error('保存亲属资产导入任务状态失败:', error);
      }
    },
    /**
     * 从localStorage读取导入任务
     */
    getImportTaskFromStorage() {
      try {
        const data = localStorage.getItem('staff_fmy_relation_import_last_task');
        if (!data) return null;

        const task = JSON.parse(data);
        if (!task || !task.taskId) {
          this.clearImportTaskFromStorage();
          return null;
        }

        const sevenDays = 7 * 24 * 60 * 60 * 1000;
        if (Date.now() - task.saveTime > sevenDays) {
          this.clearImportTaskFromStorage();
          return null;
        }

        return task;
      } catch (error) {
        console.error('读取导入任务状态失败:', error);
        this.clearImportTaskFromStorage();
        return null;
      }
    },
    getAssetImportTaskFromStorage() {
      try {
        const data = localStorage.getItem('staff_fmy_asset_import_last_task');
        if (!data) return null;

        const task = JSON.parse(data);
        if (!task || !task.taskId) {
          this.clearAssetImportTaskFromStorage();
          return null;
        }

        const sevenDays = 7 * 24 * 60 * 60 * 1000;
        if (Date.now() - task.saveTime > sevenDays) {
          this.clearAssetImportTaskFromStorage();
          return null;
        }

        return task;
      } catch (error) {
        console.error('读取亲属资产导入任务状态失败:', error);
        this.clearAssetImportTaskFromStorage();
        return null;
      }
    },
    /**
     * 清除导入历史记录
     */
    clearImportHistory() {
      this.$confirm('确认清除上次导入记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearImportTaskFromStorage();
        this.showFailureButton = false;
        this.currentTaskId = null;
        this.failureDialogVisible = false;
        this.$message.success('已清除');
      }).catch(() => {});
    },
    clearAssetImportHistory() {
      this.$confirm('确认清除上次亲属资产导入记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearAssetImportTaskFromStorage();
        this.assetShowFailureButton = false;
        this.assetCurrentTaskId = null;
        this.assetFailureDialogVisible = false;
        this.$message.success('已清除');
      }).catch(() => {});
    },
    /**
     * 清除localStorage中的导入任务
     */
    clearImportTaskFromStorage() {
      try {
        localStorage.removeItem('staff_fmy_relation_import_last_task');
      } catch (error) {
        console.error('清除导入任务状态失败:', error);
      }
    },
    clearAssetImportTaskFromStorage() {
      try {
        localStorage.removeItem('staff_fmy_asset_import_last_task');
      } catch (error) {
        console.error('清除亲属资产导入任务状态失败:', error);
      }
    }
  }
};
</script>

<style scoped>
.query-form ::v-deep .el-row {
  display: flex;
  flex-wrap: wrap;
}

.query-form ::v-deep .el-col {
  float: none;
}

.query-form ::v-deep .el-form-item {
  margin-right: 0;
}

.query-form ::v-deep .el-form-item__label {
  white-space: nowrap;
}

.query-form ::v-deep .el-form-item__content {
  min-width: 0;
}

.detail-container {
  padding: 0 20px;
}

.relation-detail-dialog .detail-assets-table {
  margin-bottom: 16px;
}

.relation-detail-dialog .empty-assets-detail {
  padding: 32px 0;
  margin-bottom: 16px;
  text-align: center;
  color: #909399;
  background: #fff;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}

.asset-section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 8px 0 12px;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.assets-table-wrapper {
  width: 100%;
}

.assets-table {
  width: 100%;
}

.assets-table .el-input,
.assets-table .el-date-editor,
.assets-table .el-select {
  width: 100%;
}

.empty-assets {
  padding: 30px 0;
  text-align: center;
  color: #909399;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background: #fafafa;
}

.empty-assets i {
  display: block;
  margin-bottom: 8px;
  font-size: 30px;
  color: #c0c4cc;
}

.empty-assets span {
  font-size: 13px;
}
</style>
