/** 统一社会信用代码：18 位，不含 I/O/S/V/Z */
export const CREDIT_CODE_PATTERN = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;

/** 18 位身份证号 */
export const ID_CARD_PATTERN = /^\d{17}[\dX]$/i;

/** 手机号 */
export const MOBILE_PHONE_PATTERN = /^1[3-9]\d{9}$/;

/** 固话或手机 */
export const PHONE_PATTERN = /^(\d{3,4}-?\d{7,8}|1[3-9]\d{9})$/;

/** 经度 */
export const LONGITUDE_PATTERN = /^-?((1[0-7]\d)|(\d{1,2}))(\.\d+)?$|^180(\.0+)?$/;

/** 纬度 */
export const LATITUDE_PATTERN = /^-?([1-8]?\d(\.\d+)?|90(\.0+)?)$/;

/** URL */
export const URL_PATTERN = /^(https?:\/\/)[\w.-]+(?:\.[\w.-]+)+[\w\-._~:/?#[\]@!$&'()*+,;=.]*$/;

export function creditCodeRule(required = true) {
  return {
    required,
    message: required ? "请输入统一社会信用代码" : undefined,
    pattern: CREDIT_CODE_PATTERN,
    ...(required ? {} : { validateTrigger: "onBlur" }),
    validator: (_, value) => {
      if (!value) {
        return required ? Promise.reject(new Error("请输入统一社会信用代码")) : Promise.resolve();
      }
      if (!CREDIT_CODE_PATTERN.test(value.trim())) {
        return Promise.reject(new Error("统一社会信用代码格式不正确"));
      }
      return Promise.resolve();
    },
  };
}

export function idCardRule(required = true) {
  return {
    required,
    validator: (_, value) => {
      if (!value) {
        return required ? Promise.reject(new Error("请输入身份证号")) : Promise.resolve();
      }
      const id = String(value).trim();
      if (!ID_CARD_PATTERN.test(id)) {
        return Promise.reject(new Error("身份证号格式不正确"));
      }
      return Promise.resolve();
    },
  };
}

export function phoneRule(label = "联系电话", required = true) {
  return {
    required,
    validator: (_, value) => {
      if (!value) {
        return required ? Promise.reject(new Error(`请输入${label}`)) : Promise.resolve();
      }
      const str = String(value).replace(/\s+/g, "");
      if (!PHONE_PATTERN.test(str)) {
        return Promise.reject(new Error(`${label}格式不正确`));
      }
      return Promise.resolve();
    },
  };
}

export function mobileRule(label = "账号", required = true) {
  return {
    required,
    validator: (_, value) => {
      if (!value) {
        return required ? Promise.reject(new Error(`请输入${label}`)) : Promise.resolve();
      }
      const str = String(value).replace(/\s+/g, "");
      if (!MOBILE_PHONE_PATTERN.test(str)) {
        return Promise.reject(new Error(`${label}应为11位手机号`));
      }
      return Promise.resolve();
    },
  };
}

export function longitudeRule(required = false) {
  return {
    required,
    validator: (_, value) => {
      if (value === undefined || value === null || value === "") {
        return required ? Promise.reject(new Error("请输入经度")) : Promise.resolve();
      }
      const num = Number(value);
      if (Number.isNaN(num) || num < -180 || num > 180) {
        return Promise.reject(new Error("经度格式不正确（-180 ~ 180）"));
      }
      return Promise.resolve();
    },
  };
}

export function latitudeRule(required = false) {
  return {
    required,
    validator: (_, value) => {
      if (value === undefined || value === null || value === "") {
        return required ? Promise.reject(new Error("请输入纬度")) : Promise.resolve();
      }
      const num = Number(value);
      if (Number.isNaN(num) || num < -90 || num > 90) {
        return Promise.reject(new Error("纬度格式不正确（-90 ~ 90）"));
      }
      return Promise.resolve();
    },
  };
}

export function urlRule(label = "网址", required = false) {
  return {
    required,
    validator: (_, value) => {
      if (!value) {
        return required ? Promise.reject(new Error(`请输入${label}`)) : Promise.resolve();
      }
      if (!URL_PATTERN.test(String(value).trim())) {
        return Promise.reject(new Error(`${label}格式不正确`));
      }
      return Promise.resolve();
    },
  };
}

export function positiveNumberRule(label, required = false) {
  return {
    required,
    validator: (_, value) => {
      if (value === undefined || value === null || value === "") {
        return required ? Promise.reject(new Error(`请输入${label}`)) : Promise.resolve();
      }
      const num = Number(value);
      if (Number.isNaN(num) || num < 0) {
        return Promise.reject(new Error(`${label}应为非负数字`));
      }
      return Promise.resolve();
    },
  };
}

/** 非负整数（人员数量等） */
export function nonNegativeIntegerRule(label, required = false) {
  return {
    required,
    validator: (_, value) => {
      if (value === undefined || value === null || value === "") {
        return required ? Promise.reject(new Error(`请输入${label}`)) : Promise.resolve();
      }
      const num = Number(value);
      if (!Number.isInteger(num) || num < 0) {
        return Promise.reject(new Error(`${label}应为非负整数`));
      }
      return Promise.resolve();
    },
  };
}

export function dateRangeRule(label = "证书有效期") {
  return {
    validator: (_, value) => {
      const allEmpty = Array.isArray(value) && value.every(item => item === "" || item == null);
      if (allEmpty || !value || !value[0] || !value[1]) {
        return Promise.reject(new Error(`请选择${label}`));
      }
      return Promise.resolve();
    },
  };
}
