/** 提车应收款列表 mock 数据与工具函数 */

import { buildVehiclePickupSchedule } from '../pickup-receivable-calc.js';
import {
  enrichPickupRecord,
  isValidPickupMainRecord,
  loadStoredPickupList,
  sanitizeStoredChildren,
  saveStoredPickupList,
  formatDeliveryLocation,
  dedupePickupListByContractCode,
  pickSeedIdentityFields,
  kpiKeyFromPickupProgress,
} from '../pickup-receivable-bridge.js';
import { formatMoneyYuan as formatMoneyYuanCore } from '../../../common/format-number.js';

/**
 * 模拟「租赁合同提交 / 交付日前 2 天」自动生成的提车应收款子单
 * @param {object} parent 主表记录
 * @param {{ seq: number, pickupDate: string, vehicleSeqs?: number[], creator?: string, chargeTime?: string, reason?: string, actualTotal?: number, financeReceived?: number }} config
 */
export function buildAutoGeneratedPickupChild(parent, config) {
  var pickupDate = config.pickupDate;
  var months = parent.paymentCycleMonths || 1;
  var seqFilter = config.vehicleSeqs;
  var deliveryLocation = config.deliveryLocation || formatDeliveryLocation(parent);
  var deliveryVehicles = [];
  var schedules = [];

  (parent.leaseOrderVehicles || []).forEach(function (v) {
    if (seqFilter && seqFilter.indexOf(v.seq) < 0) return;
    var schedule = buildVehiclePickupSchedule({
      monthRent: v.monthRent,
      monthServiceFee: v.serviceFeeTotal,
      deposit: v.deposit,
      pickupDate: pickupDate,
      paymentCycleMonths: months,
    });
    if (schedule) schedules.push(schedule);
    var pre = schedule && schedule.items[0] ? schedule.items[0] : {};
    var post = schedule && schedule.items[1] ? schedule.items[1] : {};
    deliveryVehicles.push({
      seq: v.seq,
      brand: v.brand,
      model: v.model,
      plateNo: v.plateNo || '',
      deliveryTime: pickupDate,
      deliveryLocation: deliveryLocation,
      receivableRent: (pre.rent || 0) + (post.rent || 0),
      receivableDeposit: pre.deposit || 0,
      receivableService: (pre.service || 0) + (post.service || 0),
      receivableTotal: (pre.amount || 0) + (post.amount || 0),
    });
  });

  var beforePickup = { deposit: 0, rent: 0, service: 0, amount: 0 };
  var month25 = { rent: 0, service: 0, amount: 0 };
  schedules.forEach(function (schedule) {
    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;
    }
  });

  var receivableRent = beforePickup.rent + month25.rent;
  var receivableDeposit = beforePickup.deposit;
  var receivableService = beforePickup.service + month25.service;
  var receivableTotal = beforePickup.amount + month25.amount;
  var financeReceived = config.financeReceived != null ? config.financeReceived : (config.actualTotal || 0);

  return {
    seq: config.seq,
    documentType: '提车应收款',
    auditStatus: '已生成',
    creator: config.creator || '系统自动',
    chargeTime: config.chargeTime || pickupDate + ' 08:00',
    pickupDate: pickupDate,
    deliveryLocation: deliveryLocation,
    autoGeneratedFromLease: true,
    autoGeneratedReason: config.reason || 'delivery-date-minus-2-days',
    deliveryCount: deliveryVehicles.length,
    deliveryVehicles: deliveryVehicles,
    receivableSchedule: {
      rule: schedules[0] ? schedules[0].rule : null,
      vehicleCount: deliveryVehicles.length,
      beforePickup: beforePickup,
      month25: month25,
      totalReceivable: receivableTotal,
    },
    receivableRent: receivableRent,
    receivableDeposit: receivableDeposit,
    receivableService: receivableService,
    receivableTotal: receivableTotal,
    actualTotal: config.actualTotal != null ? config.actualTotal : financeReceived,
    financeReceived: financeReceived,
    discountTotal: 0,
    arrivalAmount: financeReceived,
    isInvoiced: financeReceived > 0 ? '部分开票' : '未开票',
    invoicedAmount: financeReceived > 0 ? Math.round(financeReceived * 0.6) : 0,
    ccFinance: true,
    paymentImportNote: '实收金额由财务在「收款记录」导入到账后反写',
  };
}

/** 租赁合同提交时同步创建的主表骨架（无子单、无交付日） */
function buildLeaseSubmitMainRecord(base) {
  return Object.assign({}, base, {
    children: [],
    createdFromLeaseSubmit: true,
    leaseSubmitAt: base.leaseSubmitAt || base.createdAt || '2026-03-01 10:00',
  });
}

var AUTO_SAMPLE_HT_ZL_2026_012 = buildLeaseSubmitMainRecord({
  contractCode: 'HT-ZL-2026-012',
  contractType: '正式合同',
  projectName: '苏州工业园区城配项目',
  customerName: '苏州某某城配科技有限公司',
  businessDept: '业务2部',
  businessPerson: '李专员',
  contractEffectiveDate: '2026-03-01',
  contractApprovalStatus: '审批通过',
  contractStatus: '合同进行中',
  paymentCycleMonths: 3,
  paymentMethod: '预付',
  deliveryDate: '2026-03-20',
  deliveryDateTbd: false,
  deliveryRegion: ['江苏省', '苏州市'],
  lastPickupDate: '2026-03-20',
  leaseSubmitAt: '2026-03-02 14:30',
  leaseOrderVehicles: [
    { seq: 1, brand: '东风', model: 'DFH1180', plateNo: '苏E66001', monthRent: 5200, deposit: 10400, serviceFeeTotal: 520, plannedDeliveryDate: '2026-03-20' },
    { seq: 2, brand: '福田', model: '欧马可S3', plateNo: '苏E66002', monthRent: 4500, deposit: 9000, serviceFeeTotal: 450, plannedDeliveryDate: '2026-03-20' },
    { seq: 3, brand: '江淮', model: '格尔发K5', plateNo: '苏E66003', monthRent: 4300, deposit: 8600, serviceFeeTotal: 430, plannedDeliveryDate: '2026-04-05' },
  ],
});

var AUTO_SAMPLE_HT_ZL_2026_013 = buildLeaseSubmitMainRecord({
  contractCode: 'HT-ZL-2026-013',
  contractType: '正式合同',
  projectName: '无锡氢能干线运输项目',
  customerName: '无锡某某能源物流有限公司',
  businessDept: '业务1部',
  businessPerson: '张经理',
  contractEffectiveDate: '2026-02-20',
  contractApprovalStatus: '审批通过',
  contractStatus: '合同进行中',
  paymentCycleMonths: 1,
  paymentMethod: '预付',
  deliveryDate: '2026-03-08',
  deliveryDateTbd: false,
  lastPickupDate: '2026-03-08',
  leaseSubmitAt: '2026-02-25 09:15',
  leaseOrderVehicles: [
    { seq: 1, brand: '重汽', model: 'ZZ1187', plateNo: '苏B77001', monthRent: 5500, deposit: 11000, serviceFeeTotal: 550, plannedDeliveryDate: '2026-03-08' },
    { seq: 2, brand: '陕汽', model: 'X3000', plateNo: '苏B77002', monthRent: 5300, deposit: 10600, serviceFeeTotal: 530, plannedDeliveryDate: '2026-03-08' },
  ],
});

var AUTO_SAMPLE_HT_ZL_2026_014 = buildLeaseSubmitMainRecord({
  contractCode: 'HT-ZL-2026-014',
  contractType: '正式合同',
  projectName: '南京冷链租赁二期',
  customerName: '南京某某冷链物流有限公司',
  businessDept: '业务3部',
  businessPerson: '王专员',
  contractEffectiveDate: '2026-01-10',
  contractApprovalStatus: '审批通过',
  contractStatus: '合同进行中',
  paymentCycleMonths: 3,
  paymentMethod: '预付',
  deliveryDate: '2026-03-05',
  deliveryDateTbd: false,
  lastPickupDate: '2026-03-18',
  leaseSubmitAt: '2026-01-12 16:40',
  leaseOrderVehicles: [
    { seq: 1, brand: '现代', model: '帕力安牌4.5吨冷链车', plateNo: '苏A88001', monthRent: 4800, deposit: 9600, serviceFeeTotal: 480, plannedDeliveryDate: '2026-03-05' },
    { seq: 2, brand: '现代', model: '帕力安牌4.5吨冷链车', plateNo: '苏A88002', monthRent: 4800, deposit: 9600, serviceFeeTotal: 480, plannedDeliveryDate: '2026-03-05' },
    { seq: 3, brand: '福田', model: '欧马可S3', plateNo: '苏A88003', monthRent: 4600, deposit: 9200, serviceFeeTotal: 460, plannedDeliveryDate: '2026-03-18' },
    { seq: 4, brand: '福田', model: '欧马可S3', plateNo: '苏A88004', monthRent: 4600, deposit: 9200, serviceFeeTotal: 460, plannedDeliveryDate: '2026-03-25' },
  ],
});

export const PICKUP_RECEIVABLE_LIST_SEED = [
  {
    contractCode: 'HT-ZL-2025-001',
    contractType: '正式合同',
    projectName: '嘉兴氢能示范项目',
    customerName: '嘉兴某某物流有限公司',
    signingCompany: '嘉兴羚牛氢能科技有限公司',
    businessDept: '业务1部',
    businessPerson: '张经理',
    contractEffectiveDate: '2025-01-15',
    contractApprovalStatus: '审批通过',
    contractStatus: '合同进行中',
    paymentCycleMonths: 6,
    paymentMethod: 'advance',
    hydrogenBearer: '客户',
    hydrogenPaymentMethod: 'prepay',
    hydrogenPrepay: 5000,
    createdFromLeaseSubmit: true,
    leaseSubmitAt: '2025-01-08 11:20',
    deliveryDate: '2025-03-01',
    allVehiclesReceivableCompleted: false,
    leaseOrderVehicles: [
      { seq: 1, brand: '东风', model: 'DFH1180', plateNo: '浙A12345', monthRent: 5000, deposit: 10000, serviceFeeTotal: 700 },
      { seq: 2, brand: '福田', model: 'BJ1180', plateNo: '浙A23456', monthRent: 4500, deposit: 8000, serviceFeeTotal: 300 },
      { seq: 3, brand: '重汽', model: 'ZZ1187', plateNo: '浙A34567', monthRent: 5200, deposit: 10000, serviceFeeTotal: 580 },
      { seq: 4, brand: '陕汽', model: 'SX1313', plateNo: '浙A45678', monthRent: 4800, deposit: 9000, serviceFeeTotal: 350 },
      { seq: 5, brand: '解放', model: 'J6P', plateNo: '浙A56789', monthRent: 5500, deposit: 11000, serviceFeeTotal: 500 },
      { seq: 6, brand: '江淮', model: '格尔发K5', plateNo: '浙A67890', monthRent: 4300, deposit: 8500, serviceFeeTotal: 260 },
      { seq: 7, brand: '东风', model: 'DFH1250', plateNo: '浙A11111', monthRent: 6000, deposit: 12000, serviceFeeTotal: 850 },
      { seq: 8, brand: '福田', model: '欧曼EST', plateNo: '浙A22222', monthRent: 4700, deposit: 9000, serviceFeeTotal: 380 },
    ],
    children: [],
  },
  {
    contractCode: 'HT-ZL-2025-002',
    contractType: '正式合同',
    projectName: '上海物流租赁项目',
    customerName: '上海某某运输有限公司',
    businessDept: '业务2部',
    businessPerson: '李专员',
    contractEffectiveDate: '2025-02-01',
    contractApprovalStatus: '审批通过',
    contractStatus: '合同进行中',
    paymentCycleMonths: 3,
    paymentMethod: '预付',
    createdFromLeaseSubmit: true,
    leaseSubmitAt: '2025-02-05 15:00',
    deliveryDate: '2025-02-20',
    allVehiclesReceivableCompleted: false,
    leaseOrderVehicles: [
      { seq: 1, brand: '江淮', model: '格尔发K5', plateNo: '沪B11111', monthRent: 4300, deposit: 8500, serviceFeeTotal: 260 },
      { seq: 2, brand: '东风', model: 'DFH1250', plateNo: '沪B22222', monthRent: 6000, deposit: 12000, serviceFeeTotal: 500 },
      { seq: 3, brand: '解放', model: 'JH6', plateNo: '沪B33333', monthRent: 5400, deposit: 10800, serviceFeeTotal: 630 },
    ],
    children: [],
  },
  {
    contractCode: 'HT-ZL-2025-003',
    contractType: '正式合同',
    projectName: '杭州城配租赁项目',
    customerName: '杭州某某租赁有限公司',
    signingCompany: '上海羚牛氢能科技有限公司',
    businessDept: '业务3部',
    businessPerson: '王专员',
    contractEffectiveDate: '2025-02-10',
    contractApprovalStatus: '审批驳回',
    contractStatus: '已结束',
    pickupRefundCompleted: true,
    refundPaymentLinked: true,
    paymentCycleMonths: 1,
    paymentMethod: 'postpay',
    hydrogenBearer: '客户',
    hydrogenPaymentMethod: 'month',
    createdFromLeaseSubmit: true,
    leaseSubmitAt: '2025-02-11 09:30',
    allVehiclesReceivableCompleted: false,
    leaseOrderVehicles: [
      { seq: 1, brand: '福田', model: '欧曼EST', plateNo: '浙C33333', monthRent: 4700, deposit: 9000, serviceFeeTotal: 380 },
      { seq: 2, brand: '东风', model: 'DFH1180', plateNo: '浙C44444', monthRent: 5000, deposit: 10000, serviceFeeTotal: 200 },
    ],
    children: [],
  },
  {
    contractCode: 'HT-ZL-2026-010',
    contractType: '正式合同',
    projectName: '宁波城配新车投放项目',
    customerName: '宁波某某供应链有限公司',
    businessDept: '业务1部',
    businessPerson: '张经理',
    contractEffectiveDate: '2026-03-01',
    contractApprovalStatus: '审批通过',
    contractStatus: '合同进行中',
    paymentCycleMonths: 3,
    paymentMethod: '预付',
    allVehiclesReceivableCompleted: false,
    createdFromLeaseSubmit: true,
    leaseSubmitAt: '2026-03-01 10:30',
    deliveryDate: null,
    deliveryDateTbd: true,
    handleDemo: true,
    leaseOrderVehicles: [
      { seq: 1, brand: '现代', model: '帕力安牌4.5吨冷链车', plateNo: '浙B88001', monthRent: 4800, deposit: 9600, serviceFeeTotal: 420 },
      { seq: 2, brand: '福田', model: '欧马可S3', plateNo: '浙B88002', monthRent: 4500, deposit: 9000, serviceFeeTotal: 380 },
      { seq: 3, brand: '东风', model: 'DFH1180', plateNo: '浙B88003', monthRent: 5200, deposit: 10400, serviceFeeTotal: 500 },
      { seq: 4, brand: '江淮', model: '格尔发K5', plateNo: '浙B88004', monthRent: 4300, deposit: 8600, serviceFeeTotal: 320 },
    ],
    children: [],
  },
  buildLeaseSubmitMainRecord({
    contractCode: 'HT-ZL-2026-011',
    contractType: '正式合同',
    projectName: '温州城配新车租赁项目',
    customerName: '温州某某供应链管理有限公司',
    businessDept: '业务2部',
    businessPerson: '李专员',
    contractEffectiveDate: '2026-03-05',
    contractApprovalStatus: '待审批',
    contractStatus: '已提交审批',
    paymentCycleMonths: 3,
    paymentMethod: '预付',
    deliveryDate: null,
    deliveryDateTbd: true,
    deliveryRegion: ['浙江省', '温州市'],
    leaseSubmitAt: '2026-03-10 11:05',
    leaseOrderVehicles: [
      { seq: 1, brand: '福田', model: '欧马可S3', plateNo: '', monthRent: 4400, deposit: 8800, serviceFeeTotal: 400 },
      { seq: 2, brand: '东风', model: 'DFH1180', plateNo: '', monthRent: 5100, deposit: 10200, serviceFeeTotal: 510 },
    ],
  }),
  Object.assign({}, AUTO_SAMPLE_HT_ZL_2026_012, {
    preserveSeedChildren: true,
    children: [
      buildAutoGeneratedPickupChild(AUTO_SAMPLE_HT_ZL_2026_012, {
        seq: 1,
        pickupDate: '2026-03-20',
        vehicleSeqs: [1, 2],
        chargeTime: '2026-03-18 08:00',
        reason: 'delivery-date-minus-2-days',
        creator: '系统自动（交付日前2天）',
      }),
    ],
  }),
  Object.assign({}, AUTO_SAMPLE_HT_ZL_2026_013, {
    preserveSeedChildren: true,
    children: (function () {
      var child = buildAutoGeneratedPickupChild(AUTO_SAMPLE_HT_ZL_2026_013, {
        seq: 1,
        pickupDate: '2026-03-08',
        vehicleSeqs: [1, 2],
        chargeTime: '2026-03-06 08:00',
        reason: 'delivery-date-minus-2-days',
        creator: '系统自动（交付日前2天）',
      });
      var received = Math.round(child.receivableTotal * 0.85);
      child.financeReceived = received;
      child.actualTotal = received;
      child.arrivalAmount = received;
      child.receivedRent = Math.round(child.receivableRent * 0.85);
      child.receivedDeposit = child.receivableDeposit;
      child.receivedService = Math.round(child.receivableService * 0.85);
      return [child];
    })(),
  }),
  Object.assign({}, AUTO_SAMPLE_HT_ZL_2026_014, {
    preserveSeedChildren: true,
    children: (function () {
      var child1 = buildAutoGeneratedPickupChild(AUTO_SAMPLE_HT_ZL_2026_014, {
        seq: 1,
        pickupDate: '2026-03-05',
        vehicleSeqs: [1, 2],
        chargeTime: '2026-03-03 08:00',
        reason: 'delivery-date-minus-2-days',
        creator: '系统自动（交付日前2天）',
      });
      child1.financeReceived = child1.receivableTotal;
      child1.actualTotal = child1.receivableTotal;
      child1.arrivalAmount = child1.receivableTotal;
      child1.receivedRent = child1.receivableRent;
      child1.receivedDeposit = child1.receivableDeposit;
      child1.receivedService = child1.receivableService;
      child1.isInvoiced = '已开票';
      child1.invoicedAmount = child1.receivableTotal;

      var child2 = buildAutoGeneratedPickupChild(AUTO_SAMPLE_HT_ZL_2026_014, {
        seq: 2,
        pickupDate: '2026-03-18',
        vehicleSeqs: [3],
        chargeTime: '2026-03-16 08:00',
        reason: 'delivery-date-minus-2-days',
        creator: '系统自动（交付日前2天）',
      });
      return [child1, child2];
    })(),
  }),
];

export const PICKUP_KPI_CARDS = [
  {
    key: 'all',
    title: '全部',
    desc: '显示全部租赁合同对应的提车应收款信息',
  },
  {
    key: 'notPickedUp',
    title: '未提车',
    desc: '显示租赁合同中没有完成任何车辆提车应收款并关联收款记录闭环的数据',
  },
  {
    key: 'partialPickedUp',
    title: '部分提车',
    desc: '显示租赁合同中只完成部分车辆提车应收款并关联收款记录闭环的数据',
  },
  {
    key: 'completed',
    title: '已完成',
    desc: '显示租赁合同中全部车辆都已完成提车应收款并关联收款记录闭环的数据',
  },
  {
    key: 'refunded',
    title: '已退款',
    desc: '显示租赁合同已被审批终止，且点击退款并完成付款记录关联的数据',
  },
];

export function buildCollectCode(contractCode, seq) {
  const suffix = `TC${String(seq != null ? seq : '').padStart(4, '0')}`;
  return `${String(contractCode || '')}${suffix}`;
}

export function fmtMoneyYuan(v) {
  return formatMoneyYuanCore(v);
}

export function normalizeAuditStatus(status) {
  const s = String(status || '').trim();
  if (s === '已驳回' || s === '审批驳回') return '已驳回';
  if (s === '已生成') return '已生成';
  return s;
}

export function auditStatusTone(status) {
  const s = normalizeAuditStatus(status);
  switch (s) {
    case '审批通过':
      return 'green';
    case '已生成':
      return 'blue';
    case '待审批':
      return 'blue';
    case '审批中':
      return 'amber';
    case '已驳回':
      return 'red';
    default:
      return 'gray';
  }
}

export function invoiceStatusTone(status) {
  switch (status) {
    case '已开票':
      return 'green';
    case '部分开票':
      return 'amber';
    case '未开票':
      return 'gray';
    default:
      return 'gray';
  }
}

export function kpiKeyFromAuditStatus(status) {
  const s = normalizeAuditStatus(status);
  if (s === '待审批') return 'pending';
  if (s === '审批中') return 'inReview';
  if (s === '审批通过') return 'approved';
  if (s === '已驳回') return 'rejected';
  if (s === '已生成') return 'generated';
  return null;
}

export function cloneMainList(list) {
  return (list || []).map((row) => {
    const next = { ...row };
    next.children = (row.children || []).map((child) => ({ ...child }));
    return next;
  });
}

export function buildFilterOptions(list) {
  const codes = [];
  const projects = [];
  const customers = [];
  const plateNos = [];
  const depts = [];
  const persons = [];
  (list || []).forEach((r) => {
    if (r.contractCode && !codes.includes(r.contractCode)) codes.push(r.contractCode);
    if (r.projectName && !projects.includes(r.projectName)) projects.push(r.projectName);
    if (r.customerName && !customers.includes(r.customerName)) customers.push(r.customerName);
    if (r.businessDept && !depts.includes(r.businessDept)) depts.push(r.businessDept);
    if (r.businessPerson && !persons.includes(r.businessPerson)) persons.push(r.businessPerson);
    (r.leaseOrderVehicles || []).forEach((v) => {
      var plate = String(v.plateNo || '').trim();
      if (plate && !plateNos.includes(plate)) plateNos.push(plate);
    });
    (r.children || []).forEach((child) => {
      (child.deliveryVehicles || []).forEach((v) => {
        var childPlate = String(v.plateNo || '').trim();
        if (childPlate && !plateNos.includes(childPlate)) plateNos.push(childPlate);
      });
    });
  });
  plateNos.sort();
  return {
    contractCode: codes.map((v) => ({ value: v, label: v })),
    projectName: projects.map((v) => ({ value: v, label: v })),
    customerName: customers.map((v) => ({ value: v, label: v })),
    plateNo: plateNos.map((v) => ({ value: v, label: v })),
    businessDept: depts.map((v) => ({ value: v, label: v })),
    businessPerson: persons.map((v) => ({ value: v, label: v })),
  };
}

function recordMatchesPlateNo(record, plateNo) {
  var target = String(plateNo || '').trim();
  if (!target) return true;
  var matched = (record.leaseOrderVehicles || []).some(function (v) {
    return String(v.plateNo || '').trim() === target;
  });
  if (matched) return true;
  return (record.children || []).some(function (child) {
    return (child.deliveryVehicles || []).some(function (v) {
      return String(v.plateNo || '').trim() === target;
    });
  });
}

export function filterMainList(list, filters) {
  let rows = (list || []).filter(isValidPickupMainRecord);
  if (filters.contractCode) rows = rows.filter((r) => r.contractCode === filters.contractCode);
  if (filters.projectName) rows = rows.filter((r) => r.projectName === filters.projectName);
  if (filters.customerName) rows = rows.filter((r) => r.customerName === filters.customerName);
  if (filters.plateNo) rows = rows.filter((r) => recordMatchesPlateNo(r, filters.plateNo));
  if (filters.businessDept) rows = rows.filter((r) => r.businessDept === filters.businessDept);
  if (filters.businessPerson) rows = rows.filter((r) => r.businessPerson === filters.businessPerson);
  return rows;
}

export function countKpiFromList(list) {
  const counts = {
    all: 0,
    notPickedUp: 0,
    partialPickedUp: 0,
    completed: 0,
    refunded: 0,
  };
  (list || []).forEach(function (parent) {
    counts.all += 1;
    const key = kpiKeyFromPickupProgress(parent);
    if (key && counts[key] != null) counts[key] += 1;
  });
  return counts;
}

export function filterByKpiTab(list, kpiTab) {
  if (!kpiTab || kpiTab === 'all') return list;
  return (list || []).filter(function (parent) {
    return kpiKeyFromPickupProgress(parent) === kpiTab;
  });
}

function mergeSeedWithStored(seed, stored) {
  var seedCodeMap = {};
  seed.forEach(function (row) {
    seedCodeMap[row.contractCode] = row;
  });

  var storedByCode = {};
  (stored || []).filter(isValidPickupMainRecord).forEach(function (row) {
    storedByCode[row.contractCode] = row;
  });

  var merged = seed.map(function (seedRow) {
    var storedRow = storedByCode[seedRow.contractCode];
    if (!storedRow) return enrichPickupRecord(seedRow);
    var userChildren = sanitizeStoredChildren(storedRow.children);
    var seedChildren = seedRow.children || [];
    var children = userChildren.length
      ? userChildren
      : (seedRow.preserveSeedChildren && seedChildren.length ? seedChildren : userChildren);
    return enrichPickupRecord(Object.assign({}, seedRow, pickSeedIdentityFields(seedRow), {
      children: children,
      lastPickupDate: children.length ? (storedRow.lastPickupDate || seedRow.lastPickupDate) : seedRow.lastPickupDate,
      financeReceived: storedRow.financeReceived,
      totalReceivedAmount: storedRow.totalReceivedAmount,
    }));
  });

  (stored || []).filter(isValidPickupMainRecord).forEach(function (row) {
    if (seedCodeMap[row.contractCode]) return;
    merged.push(enrichPickupRecord(Object.assign({}, row, {
      children: sanitizeStoredChildren(row.children),
    })));
  });

  return dedupePickupListByContractCode(merged.filter(isValidPickupMainRecord));
}

/** 合并 seed 与 localStorage，供列表初始化 */
export function initPickupReceivableList() {
  var seed = cloneMainList(PICKUP_RECEIVABLE_LIST_SEED).map(enrichPickupRecord);
  var stored = loadStoredPickupList();
  var merged = mergeSeedWithStored(seed, stored);
  saveStoredPickupList(merged);
  return merged;
}
