<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px" class="query-form">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="姓名">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入姓名"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身份证号">
            <el-input
              v-model="queryParams.idCard"
              placeholder="请输入身份证号"
              clearable
              style="width: 100%"
              @keyup.enter.native="handleQuery"
            />
          </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-upload2" size="mini" @click="openUploadDialog">批量上传征信HTML</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table :data="creditInfoList" v-loading="loading">
      <el-table-column label="姓名" prop="name" align="center" />
      <el-table-column label="身份证号" prop="idCard" align="center" />
      <el-table-column label="最近征信查询日期" align="center" width="160">
        <template slot-scope="scope">
          {{ formatQueryDate(scope.row.queryDate) }}
        </template>
      </el-table-column>
      <el-table-column label="负债笔数" prop="debtCount" align="center" width="100" />
      <el-table-column label="负债总额" prop="debtTotalAmount" align="center" width="140" />
      <el-table-column label="民事案件笔数" prop="civilCnt" align="center" width="120" />
      <el-table-column label="强制执行笔数" prop="enforceCnt" align="center" width="120" />
      <el-table-column label="行政处罚笔数" prop="admCnt" align="center" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</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="批量上传征信HTML" :visible.sync="uploadDialogVisible" width="720px" append-to-body>
      <el-upload
        ref="upload"
        action=""
        :auto-upload="false"
        :file-list="uploadFileList"
        :before-upload="beforeUpload"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        multiple
      >
        <el-button type="primary" size="small">选择文件</el-button>
        <div slot="tip" class="el-upload__tip">仅支持 .html / .htm 文件，可一次选择多个文件</div>
      </el-upload>

      <div class="upload-result" v-if="uploadResult.totalCount || failureList.length">
        <div class="section-title">上传结果</div>
        <el-row :gutter="16" class="upload-summary">
          <el-col :span="8">
            <div class="summary-item">
              <span class="summary-label">总文件数</span>
              <span class="summary-value">{{ uploadResult.totalCount }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="summary-item">
              <span class="summary-label">成功数</span>
              <span class="summary-value">{{ uploadResult.successCount }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="summary-item">
              <span class="summary-label">失败数</span>
              <span class="summary-value">{{ uploadResult.failureCount }}</span>
            </div>
          </el-col>
        </el-row>

        <el-table v-if="failureList.length" :data="failureList" size="mini">
          <el-table-column label="失败文件名" prop="fileName" min-width="180" />
          <el-table-column label="身份证号" prop="personId" min-width="180" />
          <el-table-column label="姓名" prop="personName" min-width="120" />
          <el-table-column label="原因" prop="reason" min-width="220" show-overflow-tooltip />
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="uploadSubmitting" @click="handleUploadSubmit">上 传</el-button>
      </div>
    </el-dialog>

    <el-dialog title="征信详情" :visible.sync="detailDialogVisible" width="960px" append-to-body>
      <credit-info-detail :detail="detailForm" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteCreditInfo,
  getCreditInfoDetail,
  listCreditInfo,
  uploadCreditHtml,
} from "@/api/ccdiCreditInfo";
import CreditInfoDetail from "./components/CreditInfoDetail.vue";
import { createEmptyCreditDetail, normalizeCreditDetail } from "./components/creditDetailViewModel.js";

export default {
  name: "CcdiCreditInfo",
  components: {
    CreditInfoDetail,
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      creditInfoList: [],
      uploadDialogVisible: false,
      uploadSubmitting: false,
      uploadFileList: [],
      uploadResult: {
        totalCount: 0,
        successCount: 0,
        failureCount: 0,
      },
      failureList: [],
      detailDialogVisible: false,
      detailForm: createEmptyCreditDetail(),
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        idCard: undefined,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      return listCreditInfo(this.queryParams)
        .then((response) => {
          const rows = response.rows || (response.data && response.data.rows) || [];
          const total = response.total || (response.data && response.data.total) || 0;
          this.creditInfoList = rows;
          this.total = total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        idCard: undefined,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    openUploadDialog() {
      this.uploadDialogVisible = true;
    },
    beforeUpload(file) {
      const fileName = file.name.toLowerCase();
      const passed = fileName.endsWith(".html") || fileName.endsWith(".htm");
      if (!passed) {
        this.$modal.msgError("仅支持上传 .html 或 .htm 文件");
      }
      return passed;
    },
    handleFileChange(file, fileList) {
      const currentFile = file.raw || file;
      if (!this.beforeUpload(currentFile)) {
        this.uploadFileList = fileList.filter((item) => {
          const name = (item.name || "").toLowerCase();
          return name.endsWith(".html") || name.endsWith(".htm");
        });
        return;
      }
      this.uploadFileList = fileList;
    },
    handleFileRemove(file, fileList) {
      this.uploadFileList = fileList;
    },
    handleUploadSubmit() {
      if (!this.uploadFileList.length) {
        this.$modal.msgError("请先选择征信 HTML 文件");
        return;
      }
      const files = this.uploadFileList.map((file) => file.raw || file);
      this.uploadSubmitting = true;
      return uploadCreditHtml(files)
        .then((response) => {
          const data = response.data || {};
          this.uploadResult = {
            totalCount: data.totalCount || 0,
            successCount: data.successCount || 0,
            failureCount: data.failureCount || 0,
          };
          this.failureList = data.failures || [];
          this.$modal.msgSuccess(response.msg || "上传成功");
          this.uploadFileList = [];
          if (this.$refs.upload) {
            this.$refs.upload.clearFiles();
          }
          this.getList();
        })
        .finally(() => {
          this.uploadSubmitting = false;
        });
    },
    handleDetail(row) {
      return getCreditInfoDetail(row.idCard).then((response) => {
        const data = response.data || {};
        this.detailForm = normalizeCreditDetail(data, row);
        this.detailDialogVisible = true;
      });
    },
    handleDelete(row) {
      const personId = row.idCard;
      this.$modal
        .confirm("确认删除该征信对象当前已维护的征信信息吗？")
        .then(() => {
          return deleteCreditInfo(personId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.detailDialogVisible = false;
          this.getList();
        });
    },
    formatQueryDate(value) {
      if (!value) {
        return "-";
      }
      if (typeof value === "string") {
        const matched = value.match(/^(\d{4}-\d{2}-\d{2})/);
        if (matched) {
          return matched[1];
        }
      }
      return this.parseTime(value, "{y}-{m}-{d}") || "-";
    },
  },
};
</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;
}

.upload-result {
  margin-top: 20px;
}

.section-title {
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.upload-summary {
  margin-bottom: 16px;
}

.detail-summary {
  margin-bottom: 16px;
  line-height: 32px;
}

.summary-item {
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.summary-label {
  display: block;
  margin-bottom: 4px;
  color: #909399;
}

.summary-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}
</style>
