<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="信贷客户身份证号" prop="personId">
        <el-input
          v-model="queryParams.personId"
          placeholder="请输入信贷客户身份证号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关系类型" prop="relationType">
        <el-select v-model="queryParams.relationType" placeholder="请选择关系类型" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.ccdi_relation_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关系人姓名" prop="relationName">
        <el-input
          v-model="queryParams.relationName"
          placeholder="请输入关系人姓名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <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:custFmyRelation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ccdi:custFmyRelation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ccdi:custFmyRelation:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['ccdi:custFmyRelation:import']"
        >导入</el-button>
      </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="序号" type="index" width="50" align="center" />
      <el-table-column label="信贷客户身份证号" align="center" prop="personId" width="180"/>
      <el-table-column label="关系类型" align="center" prop="relationType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ccdi_relation_type" :value="scope.row.relationType"/>
        </template>
      </el-table-column>
      <el-table-column label="关系人姓名" align="center" prop="relationName" width="120"/>
      <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="relationCertNo" width="180"/>
      <el-table-column label="手机号码" align="center" prop="mobilePhone1" width="120"/>
      <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"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ccdi:custFmyRelation:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ccdi:custFmyRelation: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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="信贷客户身份证号" prop="personId">
              <el-input
                v-model="form.personId"
                placeholder="请输入信贷客户身份证号"
                :disabled="!isAdd"
                maxlength="18"
              />
            </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="dict in dict.type.ccdi_relation_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关系人姓名" prop="relationName">
              <el-input v-model="form.relationName" placeholder="请输入关系人姓名" />
            </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-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="关系人证件类型" prop="relationCertType">
              <el-select v-model="form.relationCertType" placeholder="请选择证件类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.ccdi_certificate_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.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="请输入证件号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码1" prop="mobilePhone1">
              <el-input v-model="form.mobilePhone1" placeholder="请输入手机号码1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码2" prop="mobilePhone2">
              <el-input v-model="form.mobilePhone2" placeholder="请输入手机号码2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信名称1" prop="wechatNo1">
              <el-input v-model="form.wechatNo1" placeholder="请输入微信名称1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信名称2" prop="wechatNo2">
              <el-input v-model="form.wechatNo2" placeholder="请输入微信名称2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信名称3" prop="wechatNo3">
              <el-input v-model="form.wechatNo3" placeholder="请输入微信名称3" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细联系地址" prop="contactAddress">
              <el-input v-model="form.contactAddress" type="textarea" placeholder="请输入详细联系地址" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关系详细描述" prop="relationDesc">
              <el-input v-model="form.relationDesc" type="textarea" placeholder="请输入关系详细描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="form.effectiveDate"
                type="datetime"
                placeholder="选择生效日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                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="datetime"
                placeholder="选择失效日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :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 text-center" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的关系数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align:baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入状态对话框 -->
    <el-dialog title="导入结果" :visible.sync="importResultDialogVisible" width="800px" append-to-body>
      <el-alert
        :title="importResult.title"
        :type="importResult.type"
        :description="importResult.description"
        :closable="false"
        show-icon>
      </el-alert>
      <div v-if="importResult.failures.length > 0" style="margin-top: 20px;">
        <el-divider content-position="left">失败记录</el-divider>
        <el-table :data="importResult.failures" max-height="400">
          <el-table-column label="行号" prop="rowNum" width="80" align="center"/>
          <el-table-column label="信贷客户身份证号" prop="personId" width="180"/>
          <el-table-column label="关系类型" prop="relationType" width="100"/>
          <el-table-column label="关系人姓名" prop="relationName" width="120"/>
          <el-table-column label="错误信息" prop="errorMessage" show-overflow-tooltip/>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importResultDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRelation, getRelation, addRelation, updateRelation, delRelation, exportRelation, importTemplate, importData, getImportStatus, getImportFailures } from "@/api/ccdiCustFmyRelation";
import { getToken } from "@/utils/auth";

const STORAGE_KEY = 'cust_fmy_relation_import_last_task';

export default {
  name: "CustFmyRelation",
  dicts: ['ccdi_relation_type', 'ccdi_indiv_gender', 'ccdi_certificate_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 信贷客户家庭关系表格数据
      relationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为新增操作
      isAdd: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personId: null,
        relationType: null,
        relationName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        personId: [
          { required: true, message: "信贷客户身份证号不能为空", 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" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ccdi/custFmyRelation/importData"
      },
      // 导入结果对话框
      importResultDialogVisible: false,
      importResult: {
        title: '',
        type: 'success',
        description: '',
        failures: []
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询信贷客户家庭关系列表 */
    getList() {
      this.loading = true;
      listRelation(this.queryParams).then(response => {
        this.relationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    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,
        wechatNo1: null,
        wechatNo2: null,
        wechatNo3: null,
        contactAddress: null,
        relationDesc: null,
        status: 1,
        effectiveDate: null,
        invalidDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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.isAdd = true;
      this.title = "添加信贷客户家庭关系";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getRelation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.isAdd = false;
        this.title = "修改信贷客户家庭关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRelation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRelation(this.form).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(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ccdi/custFmyRelation/export', {
        ...this.queryParams
      }, `信贷客户家庭关系_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "信贷客户家庭关系导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('ccdi/custFmyRelation/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;
      this.$modal.msgSuccess("导入任务已提交,正在后台处理...");

      // 保存任务ID并轮询状态
      const taskId = response.data || response.taskId;
      if (taskId) {
        localStorage.setItem(STORAGE_KEY, taskId);
        this.pollImportStatus(taskId);
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 轮询导入状态
    pollImportStatus(taskId) {
      const poll = async () => {
        try {
          const status = await getImportStatus(taskId);
          const statusData = status.data;

          if (statusData && statusData.startsWith('COMPLETED')) {
            const parts = statusData.split(':');
            const successCount = parseInt(parts[1]);
            const failureCount = parseInt(parts[2]);

            // 获取失败记录
            if (failureCount > 0) {
              const failures = await getImportFailures(taskId, 1, 1000);
              this.showImportResult(successCount, failureCount, failures.data || []);
            } else {
              this.showImportResult(successCount, failureCount, []);
            }

            this.getList();
            localStorage.removeItem(STORAGE_KEY);
          } else if (statusData && statusData.startsWith('FAILED')) {
            this.$modal.msgError("导入失败:" + statusData.substring(6));
            localStorage.removeItem(STORAGE_KEY);
          } else {
            // 继续轮询
            setTimeout(poll, 2000);
          }
        } catch (error) {
          console.error('查询导入状态失败', error);
        }
      };

      poll();
    },
    // 显示导入结果
    showImportResult(successCount, failureCount, failures) {
      this.importResult.failures = failures;

      if (failureCount === 0) {
        this.importResult.title = '导入成功';
        this.importResult.type = 'success';
        this.importResult.description = `成功导入 ${successCount} 条数据`;
      } else {
        this.importResult.title = '导入完成';
        this.importResult.type = 'warning';
        this.importResult.description = `成功 ${successCount} 条,失败 ${failureCount} 条`;
      }

      this.importResultDialogVisible = true;
    }
  },
  mounted() {
    // 检查是否有未完成的导入任务
    const lastTaskId = localStorage.getItem(STORAGE_KEY);
    if (lastTaskId) {
      this.pollImportStatus(lastTaskId);
    }
  }
};
</script>
