import type { CustomerRecord } from '../types';
import type {
  CustomerRiskTag,
  MockUser,
  RiskTagApplyForm,
  RiskTagOperationLog,
  RiskTagsByCustomer,
  RiskTagLifecycleStatus,
} from '../types/riskTag';
import { HIGH_RISK_LEVELS, TAG_CATALOG_MAP } from './riskTagConstants';
import seedOperationLogs from '../data/risk-tag-operation-logs.json';

let idCounter = 1000;

export function nextId(prefix: string): string {
  idCounter += 1;
  return `${prefix}-${idCounter}`;
}

export function formatNow(): string {
  const now = new Date();
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
}

export function todayDate(): string {
  return formatNow().slice(0, 10);
}

export function defaultEffectiveTo(): string {
  const d = new Date();
  d.setFullYear(d.getFullYear() + 1);
  return d.toISOString().slice(0, 10);
}

export function resolveInitialStatus(riskLevel: CustomerRiskTag['riskLevel']): RiskTagLifecycleStatus {
  return HIGH_RISK_LEVELS.includes(riskLevel) ? '待审批' : '生效中';
}

export function buildSeedRiskTags(records: CustomerRecord[]): RiskTagsByCustomer {
  const map: RiskTagsByCustomer = {};

  records.forEach((record) => {
    if (!record.labels.length) return;

    map[record.id] = record.labels.map((tagName, index) => {
      const catalog = TAG_CATALOG_MAP[tagName];
      const riskLevel = catalog?.defaultLevel ?? '中';
      const createdAt = record.createTime;

      return {
        id: `seed-${record.id}-${index}`,
        customerId: record.id,
        tagName,
        tagType: catalog?.tagType ?? '风控',
        riskLevel,
        reason: '历史数据迁移：列表既有标签自动建档',
        effectiveFrom: createdAt.slice(0, 10),
        effectiveTo: defaultEffectiveTo(),
        attachments: [],
        status: '生效中' as const,
        operator: '系统',
        operatorRole: 'admin' as const,
        createdAt,
        updatedAt: createdAt,
      };
    });
  });

  return map;
}

export function syncRecordLabels(
  records: CustomerRecord[],
  riskTagsByCustomer: RiskTagsByCustomer,
): CustomerRecord[] {
  return records.map((record) => ({
    ...record,
    labels: (riskTagsByCustomer[record.id] ?? [])
      .filter((tag) => tag.status === '生效中')
      .map((tag) => tag.tagName),
  }));
}

export function getActiveTags(tags: CustomerRiskTag[]): CustomerRiskTag[] {
  return tags.filter((tag) => tag.status === '生效中');
}

export function getPendingTags(tags: CustomerRiskTag[]): CustomerRiskTag[] {
  return tags.filter((tag) => tag.status === '待审批' || tag.status === '待确认');
}

export function createOperationLog(
  partial: Omit<RiskTagOperationLog, 'id' | 'createdAt'>,
): RiskTagOperationLog {
  return {
    ...partial,
    id: nextId('log'),
    createdAt: formatNow(),
  };
}

export function buildApplyTag(
  customerId: string,
  form: RiskTagApplyForm,
  user: MockUser,
): CustomerRiskTag {
  const now = formatNow();
  const status = resolveInitialStatus(form.riskLevel);

  return {
    id: nextId('tag'),
    customerId,
    tagName: form.tagName,
    tagType: form.tagType,
    riskLevel: form.riskLevel,
    reason: form.reason.trim(),
    effectiveFrom: form.effectiveFrom || todayDate(),
    effectiveTo: form.effectiveTo || defaultEffectiveTo(),
    attachments: form.attachments,
    status,
    operator: user.name,
    operatorRole: user.role,
    createdAt: now,
    updatedAt: now,
  };
}

export function buildApplyLog(
  tag: CustomerRiskTag,
  customerName: string,
  user: MockUser,
  batchCount?: number,
): RiskTagOperationLog {
  const action = batchCount && batchCount > 1 ? '批量打标' : '新增';
  const approvalHint = tag.status === '待审批' ? '，已进入审批流程' : '';
  const detail = batchCount && batchCount > 1
    ? `批量为 ${batchCount} 个客户提交标签「${tag.tagName}」（${tag.riskLevel}）${approvalHint}`
    : `提交标签「${tag.tagName}」（${tag.tagType}/${tag.riskLevel}）${approvalHint}`;

  return createOperationLog({
    customerId: tag.customerId,
    customerName,
    tagId: tag.id,
    tagName: tag.tagName,
    action: tag.status === '待审批' ? '提交审批' : action,
    detail,
    operator: user.name,
    operatorRole: user.role,
  });
}

export function buildRemoveLog(
  tag: CustomerRiskTag,
  customerName: string,
  user: MockUser,
  reason: string,
): RiskTagOperationLog {
  return createOperationLog({
    customerId: tag.customerId,
    customerName,
    tagId: tag.id,
    tagName: tag.tagName,
    action: '移除',
    detail: `移除标签「${tag.tagName}」，原因：${reason}`,
    operator: user.name,
    operatorRole: user.role,
  });
}

export function buildApprovalLog(
  tag: CustomerRiskTag,
  customerName: string,
  user: MockUser,
  approved: boolean,
  rejectReason?: string,
): RiskTagOperationLog {
  return createOperationLog({
    customerId: tag.customerId,
    customerName,
    tagId: tag.id,
    tagName: tag.tagName,
    action: approved ? '审批通过' : '审批驳回',
    detail: approved
      ? `审批通过标签「${tag.tagName}」，标签已生效`
      : `驳回标签「${tag.tagName}」${rejectReason ? `：${rejectReason}` : ''}`,
    operator: user.name,
    operatorRole: user.role,
  });
}

export function hasDuplicateActiveTag(
  tags: CustomerRiskTag[],
  tagName: string,
): boolean {
  return tags.some(
    (tag) => tag.tagName === tagName && (tag.status === '生效中' || tag.status === '待审批' || tag.status === '待确认'),
  );
}

export const INITIAL_OPERATION_LOGS = seedOperationLogs as RiskTagOperationLog[];

export function catalogDefaultsForTag(tagName: string): Pick<RiskTagApplyForm, 'tagType' | 'riskLevel'> {
  const catalog = TAG_CATALOG_MAP[tagName];
  if (!catalog) {
    return { tagType: '风控', riskLevel: '中' };
  }
  return { tagType: catalog.tagType, riskLevel: catalog.defaultLevel };
}

export function validateApplyForm(form: RiskTagApplyForm): string | null {
  if (!form.tagName.trim()) return '请选择标签名称';
  if (!form.tagType) return '请选择标签类型';
  if (!form.riskLevel) return '请选择风险级别';
  if (!form.reason.trim()) return '请填写原因说明';
  if (form.reason.trim().length < 10) return '原因说明至少 10 个字';
  if (!form.effectiveFrom) return '请选择生效时间';
  if (!form.effectiveTo) return '请选择有效期';
  if (form.effectiveTo < form.effectiveFrom) return '有效期不能早于生效时间';
  return null;
}
