import dayjs from 'dayjs';
import validate from "@/utils/validate";


// 从身份证号码中提取出生日期
function extractBirthdateFromId(idNo) {
  const year = idNo.substring(6, 10);
  const month = idNo.substring(10, 12);
  const day = idNo.substring(12, 14);
  return `${year}-${month}-${day}`;
}

function calculateAge(birthdate) {
  const now = dayjs();
  const birthDate = dayjs(birthdate);
  if (birthDate.isValid() && birthDate.isSameOrBefore(dayjs(), 'day')) {
    const years = now.diff(birthDate, 'year');
    const months = now.diff(birthDate.add(years, 'year'), 'month');
    if (years < 1 && months >= 1) return `${months}个月`;
    else if (years < 1 && months === 0) return `未满月`;
    return `${years}岁`;
  }
  return '';
}

export function getCustomerAge(customer) {
  if (customer) {
    if (customer.birthday) {
      return calculateAge(customer.birthday);
    } else if (customer.birthdayStamp) {
      return calculateAge(customer.birthdayStamp);
    } else if (customer.idNo && validate.isChinaId(customer.idNo)) {
      const birthdate = extractBirthdateFromId(customer.idNo);
      return calculateAge(birthdate);
    } else if (typeof customer.age === 'number') {
      return customer.age + '岁';
    } else if (typeof customer.age === 'string' && /^\d+$/.test(customer.age)) {
      return customer.age + '岁';
    }
  }
  return '';
}
