export const mockOverviewData = {
  summary: {
    title: "风险总览",
    subtitle: "集中展示项目风险统计与命中人员总览",
    actions: [],
    stats: [
      { key: "people", label: "总人数", value: 500, icon: "el-icon-user", tone: "blue" },
      { key: "riskPeople", label: "高风险", value: 10, icon: "el-icon-warning-outline", tone: "red" },
      { key: "medium", label: "中风险", value: 20, icon: "el-icon-s-opportunity", tone: "amber" },
      { key: "low", label: "低风险", value: 38, icon: "el-icon-data-line", tone: "green" },
      { key: "count", label: "无风险", value: 432, icon: "el-icon-s-data", tone: "blue" },
    ],
  },
  riskPeople: {
    rows: [
      {
        name: "李四",
        idNo: "331081199003230321",
        department: "信息二部",
        riskCount: 5,
        riskLevel: "高风险",
        riskLevelType: "danger",
        modelCount: 3,
        riskPoint: "跨地域转账频繁交易",
        riskPointTagList: [
          { modelCode: "LARGE_TRANSACTION", modelName: "大额交易", ruleName: "跨地域转账", riskLevel: "HIGH" },
          { modelCode: "ABNORMAL_TRANSACTION", modelName: "异常交易", ruleName: "频繁交易", riskLevel: "HIGH" },
        ],
        actionLabel: "查看详情",
      },
      {
        name: "王五",
        idNo: "331081199003231077",
        department: "办公室",
        riskCount: 2,
        riskLevel: "中风险",
        riskLevelType: "warning",
        modelCount: 2,
        riskPoint: "多工资转入频繁交易",
        riskPointTagList: [
          { modelCode: "SUSPICIOUS_PART_TIME", modelName: "可疑兼职", ruleName: "多工资转入", riskLevel: "MEDIUM" },
          { modelCode: "ABNORMAL_BEHAVIOR", modelName: "异常行为", ruleName: "频繁交易", riskLevel: "MEDIUM" },
        ],
        actionLabel: "查看详情",
      },
      {
        name: "赵六",
        idNo: "331081199003231099",
        department: "信息五部",
        riskCount: 2,
        riskLevel: "低风险",
        riskLevelType: "info",
        modelCount: 1,
        riskPoint: "频繁小额转账",
        riskPointTagList: [
          { modelCode: "SUSPICIOUS_GAMBLING", modelName: "疑似赌博", ruleName: "频繁小额转账", riskLevel: "LOW" },
        ],
        actionLabel: "查看详情",
      },
    ],
  },
  riskModels: {
    cardList: [
      { key: "large", title: "大额交易频繁", count: 45, peopleCount: 9 },
      { key: "salary", title: "可疑部门产薪异常", count: 32, peopleCount: 6 },
      { key: "transfer", title: "频繁转账交易", count: 28, peopleCount: 5 },
    ],
    filterOptions: {},
    filterValues: {},
    peopleList: [
      {
        name: "黄明",
        idNo: "331081199403150329",
        department: "风险管理部",
        warningType: "高风险",
        modelName: "大额交易频繁",
        actionLabel: "查看详情",
      },
      {
        name: "王江",
        idNo: "331081199102031209",
        department: "运营管理部",
        warningType: "中风险",
        modelName: "频繁转账交易",
        actionLabel: "查看详情",
      },
    ],
  },
  riskDetails: {
    projectId: 1,
    suspiciousType: "ALL",
    total: 2,
    suspiciousTransactionList: [
      {
        bankStatementId: 1,
        trxDate: "2024-01-15 10:00:00",
        suspiciousPersonName: "孙七",
        relatedPersonName: "孙七",
        relatedStaffName: "孙七",
        relatedStaffCode: "809901",
        relationType: "本人",
        userMemo: "",
        cashType: "转账",
        displayAmount: 500000,
        actionLabel: "查看详情",
      },
      {
        bankStatementId: 2,
        trxDate: "2024-01-10 09:20:00",
        suspiciousPersonName: "王五",
        relatedPersonName: "孙七",
        relatedStaffName: "孙七",
        relatedStaffCode: "809901",
        relationType: "配偶",
        userMemo: "零钱商户消费",
        cashType: "",
        displayAmount: -200000,
        actionLabel: "查看详情",
      },
    ],
    employeeCreditNegativeTotal: 2,
    employeeCreditNegativeList: [
      {
        personName: "李四",
        personId: "331081199003230321",
        queryDate: "2026-03-20",
        civilCnt: 1,
        civilLmt: 120000,
        enforceCnt: 0,
        enforceLmt: 0,
        admCnt: 0,
        admLmt: 0,
      },
      {
        personName: "王五",
        personId: "331081199003231077",
        queryDate: "2026-03-18",
        civilCnt: 0,
        civilLmt: 0,
        enforceCnt: 2,
        enforceLmt: 50000,
        admCnt: 1,
        admLmt: 2000,
      },
    ],
    transactionList: [
      {
        tradeDate: "2024-01-15",
        counterparty: "李七",
        direction: "转出",
        accountNo: "李七(08901)",
        summary: "转账",
        amount: 500000,
        actionLabel: "查看详情",
      },
      {
        tradeDate: "2024-01-16",
        counterparty: "王五",
        direction: "转出",
        accountNo: "王五(08901)",
        summary: "转账",
        amount: -200000,
        actionLabel: "查看详情",
      },
    ],
    abnormalAccountList: [
      {
        accountNo: "62209****1234",
        accountName: "李四",
        bankName: "中国农业银行",
        abnormalType: "异常转账",
        abnormalTime: "2024-01-15",
        status: "已核查",
      },
      {
        accountNo: "62209****5678",
        accountName: "王五",
        bankName: "中国工商银行",
        abnormalType: "频繁交易",
        abnormalTime: "2024-01-10",
        status: "待核查",
      },
    ],
  },
};

export const projectAnalysisTabs = [
  {
    key: "abnormalDetail",
    label: "异常明细",
    description: "展示异常交易、频繁转账账户与关联交易的分析摘要。",
  },
  {
    key: "assetAnalysis",
    label: "资产分析",
    description: "展示员工家庭资产负债专项核查资产详情。",
  },
  {
    key: "creditDetail",
    label: "征信详情",
    description: "展示征信信息维护中的征信详情。",
  },
  {
    key: "relationshipGraph",
    label: "关系图谱",
    description: "静态承载关系图谱页签内容，本轮不接入新接口。",
  },
  {
    key: "fundFlow",
    label: "资金流向",
    description: "静态承载资金流向页签内容，本轮不接入新接口。",
  },
];

const projectAnalysisTransactionTemplate = [
  {
    tradeTime: "2024-02-18 10:24:11",
    ownAccountName: "本人尾号 6222 / 工资卡",
    counterpartyName: "张某某 / 6222****9087",
    tradeType: "转账汇款",
    tradeAmount: "128,000.00",
    markStatus: "已标记关注",
  },
  {
    tradeTime: "2024-02-20 16:40:32",
    ownAccountName: "本人尾号 6217 / 二类户",
    counterpartyName: "某贸易公司 / 对公账户",
    tradeType: "往来款",
    tradeAmount: "86,500.00",
    markStatus: "待复核",
  },
];

const projectAnalysisFrequentTransferTemplate = [
  {
    accountNo: "6222****1234",
    description: "近 30 日出现多次短周期往返转账，交易对象集中于关联人员与外部中介账户。",
  },
  {
    accountNo: "6217****2288",
    description: "同日多笔拆分入账后快速转出，摘要模式高度相似。",
  },
];

const projectAnalysisRelatedTradeTemplate = [
  {
    title: "关联人员往来",
    description: "存在与同部门人员、历史共同项目人员的高频资金往来记录。",
  },
  {
    title: "项目相关交易",
    description: "部分交易时间靠近项目关键节点，需结合业务资料进一步核验。",
  },
];

function normalizeProjectAnalysisTags(person) {
  const sourceTags = Array.isArray(person && person.riskPointTagList)
    ? person.riskPointTagList
    : Array.isArray(person && person.hitTagList)
      ? person.hitTagList
      : [];

  return sourceTags
    .map((item) => {
      if (typeof item === "string") {
        return item;
      }
      if (item && typeof item === "object") {
        return item.ruleName || item.label || item.name || "";
      }
      return "";
    })
    .filter(Boolean);
}

function resolveCurrentModel(person, source) {
  if (source === "riskModelPeople") {
    if (Array.isArray(person && person.modelNames) && person.modelNames.length) {
      return person.modelNames.join("、");
    }
    return person && person.modelName ? person.modelName : "-";
  }

  const firstTag = Array.isArray(person && person.riskPointTagList) ? person.riskPointTagList[0] : null;
  if (firstTag && firstTag.modelName) {
    return firstTag.modelName;
  }
  return "-";
}

export function buildProjectAnalysisDialogData({ person, source = "riskPeople", projectName = "" } = {}) {
  const safePerson = person || {};
  const riskTags = normalizeProjectAnalysisTags(safePerson);
  const currentModelValue = resolveCurrentModel(safePerson, source);
  const displayName = safePerson.name || safePerson.staffName || "-";

  return {
    tabs: projectAnalysisTabs,
    sidebar: {
      basicInfo: {
        name: safePerson.name || safePerson.staffName || "-",
        staffCode: safePerson.staffCode || "-",
        department: safePerson.department || "-",
        riskLevel: safePerson.riskLevel || safePerson.warningType || "-",
        projectName: projectName || safePerson.projectName || "-",
      },
      modelSummary: {
        modelCount: safePerson.modelCount || (Array.isArray(safePerson.modelNames) ? safePerson.modelNames.length : "-"),
        hasRiskTags: riskTags.length > 0,
        riskTags,
      },
      recordSummary: "排查记录摘要为静态承载内容，本轮用于展示统一工作台侧栏结构。",
    },
    sourceSummary: {
      showCurrentModel: source === "riskModelPeople",
      currentModelLabel: "当前命中模型",
      currentModelValue,
    },
    abnormalDetail: {
      groups: [
        {
          groupCode: "BANK_STATEMENT",
          groupName: "流水异常明细",
          groupType: "BANK_STATEMENT",
          records: projectAnalysisTransactionTemplate.map((item, index) => ({
            bankStatementId: index + 1,
            trxDate: item.tradeTime,
            leAccountNo: item.ownAccountName,
            leAccountName: index === 0 ? displayName : "关联账户",
            customerAccountName: item.counterpartyName,
            customerAccountNo: item.counterpartyName,
            userMemo: item.tradeType,
            cashType: item.tradeType,
            hitTags: [],
            displayAmount: item.tradeAmount,
          })),
        },
        {
          groupCode: "RELATED_OBJECT",
          groupName: "异常对象摘要",
          groupType: "OBJECT",
          records: [
            {
              title: projectAnalysisRelatedTradeTemplate[0].title,
              subtitle: projectAnalysisFrequentTransferTemplate[0]
                ? projectAnalysisFrequentTransferTemplate[0].accountNo
                : "异常对象",
              riskTags: [],
              reasonDetail: "命中高频往来异常规则，系统已截取对象型异常原因快照用于辅助研判。",
              summary: "高频往来",
              extraFields: [],
            },
            {
              title: projectAnalysisRelatedTradeTemplate[0].title,
              subtitle: projectAnalysisFrequentTransferTemplate[0]
                ? projectAnalysisFrequentTransferTemplate[0].accountNo
                : "异常对象",
              riskTags: [],
              reasonDetail: "命中关键时间点异常关联规则，系统已截取对象型异常原因快照用于辅助研判。",
              summary: "关键时间点异常关联",
              extraFields: [],
            },
            {
              title: projectAnalysisRelatedTradeTemplate[1].title,
              subtitle: projectAnalysisFrequentTransferTemplate[1]
                ? projectAnalysisFrequentTransferTemplate[1].accountNo
                : "异常对象",
              riskTags: [],
              reasonDetail: "命中项目相关交易异常规则，系统已截取对象型异常原因快照用于辅助研判。",
              summary: "项目相关交易",
              extraFields: [],
            },
          ],
        },
      ],
    },
  };
}

const summaryStatMetaMap = mockOverviewData.summary.stats.reduce((acc, item) => {
  acc[item.key] = {
    icon: item.icon,
    tone: item.tone,
  };
  return acc;
}, {});

function normalizeSummaryStats(stats) {
  if (!Array.isArray(stats)) {
    return [];
  }
  return stats.map((item) => ({
    ...summaryStatMetaMap[item.key],
    ...item,
  }));
}

function normalizeRiskModelCards(cardList) {
  if (!Array.isArray(cardList)) {
    return [];
  }
  return cardList.map((item) => ({
    key: item.modelCode,
    title: item.modelName,
    count: item.warningCount,
    peopleCount: item.peopleCount,
  }));
}

function normalizeSuspiciousTransactions(rows) {
  if (!Array.isArray(rows)) {
    return [];
  }
  return rows.map((item) => ({
    ...item,
    actionLabel: item.actionLabel || "查看详情",
  }));
}

function normalizeEmployeeCreditNegativeRows(rows) {
  if (!Array.isArray(rows)) {
    return [];
  }
  return rows.map((item) => ({
    ...item,
  }));
}

export function createOverviewLoadedData({
  projectId,
  dashboardData,
  riskPeopleData,
  riskModelCardsData,
  suspiciousData,
  creditNegativeData,
  externalRiskSummary,
} = {}) {
  return {
    ...mockOverviewData,
    summary: {
      ...mockOverviewData.summary,
      ...(dashboardData || {}),
      actions: mockOverviewData.summary.actions,
      stats: normalizeSummaryStats(dashboardData && dashboardData.stats),
      externalRiskSummary: externalRiskSummary || {},
    },
    riskPeople: {
      ...mockOverviewData.riskPeople,
      rows: Array.isArray(riskPeopleData && riskPeopleData.rows)
        ? riskPeopleData.rows
        : [],
      total: riskPeopleData && riskPeopleData.total ? riskPeopleData.total : 0,
      pageNum: riskPeopleData && riskPeopleData.pageNum ? riskPeopleData.pageNum : 1,
      pageSize: riskPeopleData && riskPeopleData.pageSize ? riskPeopleData.pageSize : 5,
    },
    riskModels: {
      ...mockOverviewData.riskModels,
      projectId,
      cardList: normalizeRiskModelCards(riskModelCardsData && riskModelCardsData.cardList),
      peopleList: [],
      total: 0,
    },
    riskDetails: {
      ...mockOverviewData.riskDetails,
      projectId,
      riskModelOptions: normalizeRiskModelCards(riskModelCardsData && riskModelCardsData.cardList),
      suspiciousTransactionList: normalizeSuspiciousTransactions(suspiciousData && suspiciousData.rows),
      suspiciousType: "ALL",
      total: suspiciousData && suspiciousData.total ? suspiciousData.total : 0,
      employeeCreditNegativeList: normalizeEmployeeCreditNegativeRows(creditNegativeData && creditNegativeData.rows),
      employeeCreditNegativeTotal: creditNegativeData && creditNegativeData.total ? creditNegativeData.total : 0,
      transactionList: normalizeSuspiciousTransactions(suspiciousData && suspiciousData.rows),
      abnormalAccountList: [],
    },
  };
}

export const mockOverviewStateData = {
  loaded: mockOverviewData,
  empty: {
    summary: {
      ...mockOverviewData.summary,
      stats: mockOverviewData.summary.stats.map((item) => ({
        ...item,
        value: 0,
      })),
    },
    riskPeople: {
      rows: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
    },
    riskModels: {
      ...mockOverviewData.riskModels,
      cardList: [],
      peopleList: [],
    },
    riskDetails: {
      suspiciousTransactionList: [],
      suspiciousType: "ALL",
      total: 0,
      employeeCreditNegativeList: [],
      employeeCreditNegativeTotal: 0,
      transactionList: [],
      abnormalAccountList: [],
    },
  },
  loading: mockOverviewData,
};
