import type { ChangeLogEntry, SupplierCreateForm, SupplierRecord } from '../types';
import { KEY_FIELD_LABELS } from './constants';

export function recordToForm(record: SupplierRecord): SupplierCreateForm {
  return {
    contractingCompany: record.contractingCompany,
    supplierName: record.supplierName,
    type: record.type,
    coopStatus: record.coopStatus,
    region: record.region,
    provinceCity: record.city,
    cityDisplay: record.cityDisplay,
    detailAddress: record.detailAddress,
    contact: record.contact,
    contactMobile: record.contactMobile,
    contactPhone: record.contactPhone,
    email: record.email,
    creditCodeOrId: record.creditCodeOrId,
    taxId: record.taxId,
    regPhone: record.regPhone,
    regAddress: record.regAddress,
    bankName: record.bankName,
    bankAccount: record.bankAccount,
    remark: record.remark,
    licenses: record.licenses.map((item) => ({ ...item })),
  };
}

export function formToRecord(
  form: SupplierCreateForm,
  base: Partial<SupplierRecord> & Pick<SupplierRecord, 'id' | 'supplierCode'>,
): SupplierRecord {
  const creditCode = form.creditCodeOrId.trim() || base.creditCodeOrId || '';
  return {
    id: base.id,
    supplierCode: base.supplierCode,
    contractingCompany: form.contractingCompany,
    supplierName: form.supplierName.trim(),
    type: form.type as SupplierRecord['type'],
    coopStatus: form.coopStatus as SupplierRecord['coopStatus'],
    region: form.region,
    city: form.provinceCity,
    cityDisplay: form.cityDisplay,
    detailAddress: form.detailAddress,
    creditCodeOrId: creditCode,
    contact: form.contact.trim(),
    contactMobile: form.contactMobile.trim(),
    contactPhone: form.contactPhone.trim() || '-',
    email: form.email.trim(),
    taxId: form.taxId.trim(),
    regPhone: form.regPhone.trim(),
    regAddress: form.regAddress.trim(),
    bankName: form.bankName.trim(),
    bankAccount: form.bankAccount.trim(),
    remark: form.remark.trim(),
    qualStatus: base.qualStatus ?? '正常',
    riskStatus: base.riskStatus ?? '无风险',
    licenseStatus: base.licenseStatus ?? '正常',
    hasLinkedContract: base.hasLinkedContract ?? false,
    hasLinkedPayment: base.hasLinkedPayment ?? false,
    status: base.status ?? 'active',
    creator: base.creator ?? '系统',
    createTime: base.createTime ?? new Date().toISOString().slice(0, 16).replace('T', ' '),
    updatedAt: new Date().toISOString().slice(0, 16).replace('T', ' '),
    licenses: form.licenses.map((item) => ({ ...item })),
  };
}

const TRACKED_FIELDS: Array<keyof SupplierCreateForm> = [
  'contractingCompany',
  'supplierName',
  'type',
  'coopStatus',
  'region',
  'cityDisplay',
  'detailAddress',
  'contact',
  'contactMobile',
  'contactPhone',
  'email',
  'creditCodeOrId',
  'taxId',
  'regPhone',
  'regAddress',
  'bankName',
  'bankAccount',
  'remark',
];

export function buildChangeLogs(
  before: SupplierCreateForm,
  after: SupplierCreateForm,
  supplier: Pick<SupplierRecord, 'id' | 'supplierName'>,
  operator: string,
): ChangeLogEntry[] {
  const now = new Date().toISOString().slice(0, 16).replace('T', ' ');
  const entries: ChangeLogEntry[] = [];

  TRACKED_FIELDS.forEach((field) => {
    const oldValue = String(before[field] ?? '').trim();
    const newValue = String(after[field] ?? '').trim();
    if (oldValue === newValue) return;
    entries.push({
      id: `${supplier.id}-${field}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
      supplierId: supplier.id,
      supplierName: supplier.supplierName,
      fieldLabel: KEY_FIELD_LABELS[field] ?? field,
      oldValue: oldValue || '—',
      newValue: newValue || '—',
      operator,
      operatedAt: now,
    });
  });

  return entries;
}

export function nextSupplierCode(records: SupplierRecord[]): string {
  const year = new Date().getFullYear();
  const prefix = `GYS-${year}-`;
  const maxSeq = records.reduce((max, record) => {
    if (!record.supplierCode.startsWith(prefix)) return max;
    const seq = Number.parseInt(record.supplierCode.slice(prefix.length), 10);
    return Number.isNaN(seq) ? max : Math.max(max, seq);
  }, 0);
  return `${prefix}${String(maxSeq + 1).padStart(3, '0')}`;
}
