import type { LicenseRecord, SupplierCreateForm, SupplierRecord } from '../types';
import { validateContactPhones, validateEmail, validateMobile } from './phone';

const TAX_ID_PATTERN = /^[0-9A-HJ-NPQRTUWXY]{15}$|^[0-9A-HJ-NPQRTUWXY]{18}$/i;
const USCC_PATTERN = /^[0-9A-HJ-NPQRTUWXY]{18}$/i;

export function validateTaxId(value: string): string | null {
  const trimmed = value.trim();
  if (!trimmed) return null;
  if (!TAX_ID_PATTERN.test(trimmed)) return '纳税人识别号格式不正确';
  return null;
}

export function validateCreditCode(value: string): string | null {
  const trimmed = value.trim();
  if (!trimmed) return null;
  if (!USCC_PATTERN.test(trimmed)) return '统一社会信用代码格式不正确（18位）';
  return null;
}

export function validateBankAccount(value: string): string | null {
  const trimmed = value.trim();
  if (!trimmed) return null;
  if (!/^\d+$/.test(trimmed)) return '银行账号仅允许数字';
  return null;
}

export function validateLicenses(licenses: LicenseRecord[]): string | null {
  const businessLicense = licenses.find((item) => item.docType === '营业执照');
  if (!businessLicense?.fileName.trim()) return '请上传营业执照';

  for (const license of licenses) {
    if (!license.validFrom || !license.validTo) continue;
    if (license.validTo < license.validFrom) {
      return `${license.docType}有效期结束时间不得早于开始时间`;
    }
  }
  return null;
}

export function validateSupplierForm(
  form: SupplierCreateForm,
  records: SupplierRecord[],
  editingId?: string,
): string | null {
  if (!form.contractingCompany) return '请选择签约公司';
  if (!form.supplierName.trim()) return '请输入供应商名称';
  if (!form.type) return '请选择供应商类型';
  if (!form.coopStatus) return '请选择合作状态';

  const duplicateName = records.some(
    (r) => r.supplierName.trim() === form.supplierName.trim() && r.id !== editingId,
  );
  if (duplicateName) return '供应商名称不可重复';

  if (!form.contact.trim()) return '请输入联系人姓名';

  const phoneError = validateContactPhones(form.contactMobile, form.contactPhone);
  if (phoneError) return phoneError;

  if (form.contactMobile.trim()) {
    const mobileError = validateMobile(form.contactMobile);
    if (mobileError) return mobileError;
  }

  if (form.email.trim()) {
    const emailError = validateEmail(form.email);
    if (emailError) return emailError;
  }

  const creditError = validateCreditCode(form.creditCodeOrId);
  if (creditError) return creditError;

  const taxError = validateTaxId(form.taxId);
  if (taxError) return taxError;

  const bankError = validateBankAccount(form.bankAccount);
  if (bankError) return bankError;

  const licenseError = validateLicenses(form.licenses);
  if (licenseError) return licenseError;

  return null;
}

export function validateCreditCodeUnique(
  creditCode: string,
  records: SupplierRecord[],
  editingId?: string,
): string | null {
  const trimmed = creditCode.trim();
  if (!trimmed) return null;
  const formatError = validateCreditCode(trimmed);
  if (formatError) return formatError;
  const duplicate = records.some(
    (r) => r.creditCodeOrId.trim().toUpperCase() === trimmed.toUpperCase() && r.id !== editingId,
  );
  if (duplicate) return '统一社会信用代码不可重复';
  return null;
}
