/**
 * 提车应收款费用计算（对齐合同 2.1.2 / 2.1.3）
 * - 当月实际租赁天数按比例：（月租金 + 月服务费）/ 30 × 天数，四舍五入取整到元
 * - 提车日 ≤15 日：提车前2日内付保证金+当月剩余；当月25日付下周期
 * - 提车日 >15 日：提车前2日内付保证金+当月剩余+下周期
 */

export function roundYuan(amount) {
  var n = typeof amount === 'number' ? amount : parseFloat(amount);
  if (Number.isNaN(n)) return 0;
  return Math.round(n);
}

export function parsePickupDateInput(value) {
  if (!value) return null;
  if (value instanceof Date && !Number.isNaN(value.getTime())) {
    return new Date(value.getFullYear(), value.getMonth(), value.getDate());
  }
  var s = String(value).trim().slice(0, 10);
  if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
  var parts = s.split('-');
  var d = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
  if (Number.isNaN(d.getTime())) return null;
  return d;
}

export function formatDateYmd(date) {
  if (!date) return '';
  var y = date.getFullYear();
  var m = String(date.getMonth() + 1).padStart(2, '0');
  var d = String(date.getDate()).padStart(2, '0');
  return y + '-' + m + '-' + d;
}

export function addDays(date, days) {
  var next = new Date(date.getTime());
  next.setDate(next.getDate() + days);
  return next;
}

/** 提车当月实际租赁天数（含提车日） */
export function calcMonthActualRentalDays(pickupDate) {
  var d = parsePickupDateInput(pickupDate);
  if (!d) return 0;
  var daysInMonth = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
  return daysInMonth - d.getDate() + 1;
}

export function calcProRatedRent(monthRent, actualDays) {
  return roundYuan(((parseFloat(monthRent) || 0) / 30) * (actualDays || 0));
}

export function calcProRatedService(monthServiceFee, actualDays) {
  return roundYuan(((parseFloat(monthServiceFee) || 0) / 30) * (actualDays || 0));
}

export function calcCycleRent(monthRent, paymentCycleMonths) {
  return roundYuan((parseFloat(monthRent) || 0) * (paymentCycleMonths || 1));
}

export function calcCycleService(monthServiceFee, paymentCycleMonths) {
  return roundYuan((parseFloat(monthServiceFee) || 0) * (paymentCycleMonths || 1));
}

export function isPickupOnOrBefore15th(pickupDate) {
  var d = parsePickupDateInput(pickupDate);
  if (!d) return true;
  return d.getDate() <= 15;
}

export function buildVehiclePickupSchedule(params) {
  var pickupDate = parsePickupDateInput(params.pickupDate);
  if (!pickupDate) return null;

  var monthRent = parseFloat(params.monthRent) || 0;
  var monthService = parseFloat(params.monthServiceFee) || 0;
  var deposit = parseFloat(params.deposit) || 0;
  var paymentCycleMonths = params.paymentCycleMonths || 1;

  var actualDays = calcMonthActualRentalDays(pickupDate);
  var proRent = calcProRatedRent(monthRent, actualDays);
  var proService = calcProRatedService(monthService, actualDays);
  var cycleRent = calcCycleRent(monthRent, paymentCycleMonths);
  var cycleService = calcCycleService(monthService, paymentCycleMonths);

  var beforeDue = formatDateYmd(addDays(pickupDate, -2));
  var month25Due = formatDateYmd(
    new Date(pickupDate.getFullYear(), pickupDate.getMonth(), 25),
  );

  var rule = isPickupOnOrBefore15th(pickupDate) ? 'on-or-before-15' : 'after-15';
  var beforePickup = {
    key: 'before-pickup',
    label: '提车前2日内',
    dueDate: beforeDue,
    deposit: deposit,
    rent: rule === 'after-15' ? proRent + cycleRent : proRent,
    service: rule === 'after-15' ? proService + cycleService : proService,
    actualDays: actualDays,
    proRatedRent: proRent,
    proRatedService: proService,
    cycleRent: rule === 'after-15' ? cycleRent : 0,
    cycleService: rule === 'after-15' ? cycleService : 0,
  };
  beforePickup.amount = beforePickup.deposit + beforePickup.rent + beforePickup.service;

  var items = [beforePickup];

  if (rule === 'on-or-before-15') {
    items.push({
      key: 'month-25',
      label: '当月25日',
      dueDate: month25Due,
      deposit: 0,
      rent: cycleRent,
      service: cycleService,
      amount: cycleRent + cycleService,
    });
  }

  var totalReceivable = items.reduce(function (sum, item) {
    return sum + (item.amount || 0);
  }, 0);

  return {
    rule: rule,
    pickupDate: formatDateYmd(pickupDate),
    paymentCycleMonths: paymentCycleMonths,
    actualDays: actualDays,
    items: items,
    beforePickupAmount: beforePickup.amount,
    month25Amount: rule === 'on-or-before-15' ? cycleRent + cycleService : 0,
    totalReceivable: totalReceivable,
  };
}

export function buildBatchPickupScheduleSummary(vehicles, pickupDate, paymentCycleMonths) {
  var list = (vehicles || []).filter(function (v) {
    return v.selected && !v.receivableCompleted;
  });
  var beforePickup = { deposit: 0, rent: 0, service: 0, amount: 0 };
  var month25 = { rent: 0, service: 0, amount: 0 };
  var rule = null;

  list.forEach(function (v) {
    var schedule = v.receivableSchedule || buildVehiclePickupSchedule({
      monthRent: v.monthRent,
      monthServiceFee: v.serviceFeeTotal != null ? v.serviceFeeTotal : v.receivableService,
      deposit: v.receivableDeposit != null ? v.receivableDeposit : v.deposit,
      pickupDate: pickupDate,
      paymentCycleMonths: paymentCycleMonths,
    });
    if (!schedule) return;
    rule = schedule.rule;
    var pre = schedule.items[0];
    if (pre) {
      beforePickup.deposit += pre.deposit || 0;
      beforePickup.rent += pre.rent || 0;
      beforePickup.service += pre.service || 0;
      beforePickup.amount += pre.amount || 0;
    }
    var post = schedule.items[1];
    if (post) {
      month25.rent += post.rent || 0;
      month25.service += post.service || 0;
      month25.amount += post.amount || 0;
    }
  });

  return {
    rule: rule,
    vehicleCount: list.length,
    beforePickup: beforePickup,
    month25: month25,
    totalReceivable: beforePickup.amount + month25.amount,
  };
}

export function describePickupRule(rule) {
  if (rule === 'after-15') {
    return '提车日为当月15日后：提车前2日内支付保证金、当月剩余天数租金及服务费，以及下个付款周期租金及服务费。';
  }
  return '提车日为当月15日前（含15日）：提车前2日内支付保证金和当月剩余天数租金及服务费；当月25日支付下个付款周期租金及服务费。';
}
