<template>
  <section class="risk-model-section">
    <div class="section-card">
      <div class="block">
        <div class="block-header">
          <div>
            <div class="block-title">模型预警次数统计</div>
            <div class="block-subtitle">按模型汇总预警命中次数与涉及人数</div>
          </div>
          <el-button size="mini" type="text">导出</el-button>
        </div>

        <div v-loading="cardLoading" class="model-card-grid">
          <button
            v-for="item in cards"
            :key="item.key"
            type="button"
            class="model-card"
            :class="{ 'is-active': isModelSelected(item.key) }"
            @click="toggleModelSelection(item.key)"
          >
            <div class="model-card-title">{{ item.title }}</div>
            <div class="model-card-count">{{ item.count }}</div>
            <div class="model-card-meta">涉及 {{ item.peopleCount }} 人</div>
            <div class="model-card-action">
              {{ isModelSelected(item.key) ? "再次点击取消" : "点击加入联动" }}
            </div>
          </button>
        </div>
      </div>

      <div class="block">
        <div class="block-header">
          <div>
            <div class="block-title">命中模型涉及人员</div>
            <div class="block-subtitle">基于筛选条件查看模型命中人员</div>
          </div>
        </div>

        <div class="filter-bar">
          <div class="filter-item filter-item--mode">
            <span class="filter-label">触发方式</span>
            <el-radio-group
              v-model="matchMode"
              size="mini"
              @change="handleMatchModeChange"
            >
              <el-radio-button label="ANY">任意触发</el-radio-button>
              <el-radio-button label="ALL">同时触发</el-radio-button>
            </el-radio-group>
          </div>

          <div class="filter-summary">
            <span class="summary-label">已选模型</span>
            <span class="summary-value">{{ selectedModelText }}</span>
          </div>

          <div class="filter-actions">
            <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
            <el-button size="mini" plain @click="resetQuery">重置</el-button>
          </div>
        </div>

        <el-table v-loading="tableLoading" :data="peopleList" class="model-table">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="idNo" label="身份证号" min-width="180" />
          <el-table-column prop="department" label="所属部门" min-width="140" />
          <el-table-column prop="warningType" label="预警类型" min-width="120" />
          <el-table-column prop="modelName" label="筛查模型" min-width="180" />
          <el-table-column label="操作" width="100" align="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini">{{
                scope.row.actionLabel || "查看详情"
              }}</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-bar">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="pageNum"
            :page-size="pageSize"
            :total="total"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import { getOverviewRiskModelPeople } from "@/api/ccdi/projectOverview";

function normalizePeopleRows(rows) {
  if (!Array.isArray(rows)) {
    return [];
  }
  return rows.map((item) => ({
    ...item,
    name: item.staffName || item.name || "",
    modelName: Array.isArray(item.modelNames) ? item.modelNames.join("、") : item.modelName || "",
    warningType: item.warningType || "-",
  }));
}

export default {
  name: "RiskModelSection",
  props: {
    sectionData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      selectedModelCodes: [],
      matchMode: "ANY",
      keyword: "",
      deptId: undefined,
      pageNum: 1,
      pageSize: 5,
      cardLoading: false,
      tableLoading: false,
      peopleList: [],
      total: 0,
    };
  },
  computed: {
    projectId() {
      return this.sectionData && this.sectionData.projectId;
    },
    cards() {
      if (!Array.isArray(this.sectionData && this.sectionData.cardList)) {
        return [];
      }
      return this.sectionData.cardList.map((item) => ({
        key: item.key || item.modelCode,
        title: item.title || item.modelName,
        count: item.count || item.warningCount || 0,
        peopleCount: item.peopleCount || 0,
      }));
    },
    selectedModelText() {
      if (!this.selectedModelCodes.length) {
        return "全部模型";
      }
      return this.cards
        .filter((item) => this.selectedModelCodes.includes(item.key))
        .map((item) => item.title)
        .join("、");
    },
  },
  watch: {
    projectId: {
      immediate: true,
      handler() {
        this.pageNum = 1;
        this.fetchPeopleList();
      },
    },
  },
  methods: {
    isModelSelected(modelCode) {
      return this.selectedModelCodes.includes(modelCode);
    },
    toggleModelSelection(modelCode) {
      if (this.selectedModelCodes.includes(modelCode)) {
        this.selectedModelCodes = this.selectedModelCodes.filter((item) => item !== modelCode);
      } else {
        this.selectedModelCodes = [...this.selectedModelCodes, modelCode];
      }
      this.pageNum = 1;
      this.fetchPeopleList();
    },
    handleMatchModeChange() {
      this.pageNum = 1;
      this.fetchPeopleList();
    },
    handleQuery() {
      this.pageNum = 1;
      this.fetchPeopleList();
    },
    resetQuery() {
      this.selectedModelCodes = [];
      this.matchMode = "ANY";
      this.keyword = "";
      this.deptId = undefined;
      this.pageNum = 1;
      this.fetchPeopleList();
    },
    handlePageChange(pageNum) {
      this.pageNum = pageNum;
      this.fetchPeopleList();
    },
    buildPeopleParams() {
      return {
        projectId: this.projectId,
        modelCodes: this.selectedModelCodes,
        matchMode: this.matchMode,
        keyword: this.keyword,
        deptId: this.deptId,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
    },
    async fetchPeopleList() {
      if (!this.projectId) {
        this.peopleList = [];
        this.total = 0;
        return;
      }

      this.tableLoading = true;
      try {
        const response = await getOverviewRiskModelPeople(this.buildPeopleParams());
        const data = (response && response.data) || {};
        this.peopleList = normalizePeopleRows(data.rows);
        this.total = Number(data.total || 0);
      } catch (error) {
        this.peopleList = [];
        this.total = 0;
        console.error("加载风险模型命中人员失败", error);
      } finally {
        this.tableLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.risk-model-section {
  margin-bottom: 16px;
}

.section-card {
  padding: 20px;
  border-radius: 0;
  background: #fff;
  box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
}

.block + .block {
  margin-top: 24px;
}

.block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
}

.block-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.block-subtitle {
  margin-top: 4px;
  font-size: 12px;
  color: #94a3b8;
}

.model-card-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 16px;
}

.model-card {
  display: block;
  width: 100%;
  padding: 18px;
  border: 1px solid #e2e8f0;
  border-radius: 0;
  background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
  text-align: left;
  cursor: pointer;
  transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
}

.model-card:hover,
.model-card.is-active {
  border-color: #2563eb;
  box-shadow: 0 12px 24px rgba(37, 99, 235, 0.12);
  transform: translateY(-2px);
}

.model-card-title {
  font-size: 14px;
  font-weight: 600;
  color: #334155;
}

.model-card-count {
  margin-top: 12px;
  font-size: 28px;
  font-weight: 700;
  color: #2563eb;
}

.model-card-meta {
  margin-top: 8px;
  font-size: 12px;
  color: #94a3b8;
}

.model-card-action {
  margin-top: 12px;
  font-size: 12px;
  color: #2563eb;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 14px;
  padding: 14px 16px;
  border-radius: 12px;
  background: #f8fafc;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item--mode {
  flex-wrap: wrap;
}

.filter-label,
.summary-label {
  font-size: 12px;
  color: #64748b;
}

.filter-summary {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
  flex: 1;
}

.summary-value {
  min-width: 0;
  color: #1e293b;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.model-table {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.model-table th) {
  background: #f8fafc;
  color: #64748b;
}

.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
