import { getDefaultCurrency } from "@/utils/request.js";

// 获取默认币种
const currency = {
  id: getDefaultCurrency().id || "",
  currencySign: getDefaultCurrency().currencySign || "￥",
  currencyPriceScale: getDefaultCurrency().currencyPriceScale || 2,
  currencyAmountScale: getDefaultCurrency().currencyAmountScale || 2
};
// 对购物车下单、货补下单、手动添加商品等等补充默认数据todo...
export const setItemsDefaultData = (orderItems, ifTransProdInfo) => {
  const newOrderItems = [];
  orderItems.forEach(item => {
    const newItem = Object.assign({}, item);
    if (ifTransProdInfo) {
      newItem.goodsId = item.id;
      newItem.goodsDisplayName = item.displayName;
      newItem.goodsName = item.name;
      newItem.goodsCode = item.code;
      newItem.goodsImg = item.mainPictureFileUrl;
      newItem.orderNumUnitId = item.assistUnitId;
      newItem.orderNumUnitCode = item.assistUnitCode;
      newItem.orderNumUnitName = item.assistUnitName;
      newItem.orderNumUnitScale = item.assistUnitPrecision || 0;
      newItem.mainNumUnitId = item.basicUnitId;
      newItem.mainNumUnitCode = item.basicUnitCode;
      newItem.mainNumUnitName = item.basicUnitName;
      newItem.mainNumUnitScale = item.basicUnitPrecision || 0;
      newItem.weight = item.grossWeight; // 默认取毛重
      newItem.salePrice = item.baseDiscountPrice || 0;
    }
    newItem.id = null;
    newItem.isOptional = item.isOptional;
    newItem.basePrice = item.basePrice || 0;
    newItem.salePrice = newItem.salePrice || item.salePrice;
    newItem.promPrice = newItem.salePrice || item.salePrice;
    newItem.dealPrice = newItem.salePrice || item.salePrice;
    newItem.stock = item.stock || 0; // 库存
    newItem.currency = currency.id;
    newItem.currencyId = currency.id;
    newItem.currencySign = currency.currencySign;
    newItem.currencyPriceScale = currency.currencyPriceScale || 2; // 币种单价精度
    newItem.currencyAmountScale = currency.currencyAmountScale || 2; // 币种金额精度
    newItem.amount = 0;
    newItem.promAmount = 0;
    newItem.offsetAmount = 0;
    newItem.dealAmount = 0;
    newItem.isGift = 0;
    newOrderItems.push(newItem);
  });
  return newOrderItems;
};
// 获取本次最高可冲抵金额
export const getMaxOccupyMny = (occupyMnyTopLimit, totalAmount, totalDealAmount) => {
  // 是否基于销售价（净价）冲抵, 默认true
  const ifOccupyForSalePrice = true;
  if (!occupyMnyTopLimit || !occupyMnyTopLimit.supplyMaxOccupyMny) return 0;
  // 订单最高可用冲抵金额
  let orderMaxOccMny =
    parseFloat(ifOccupyForSalePrice ? totalAmount : totalDealAmount) *
    parseFloat(occupyMnyTopLimit.costOffsetRatio || "0");
  // 本供应商最高可用余额
  const supplyMaxOccupyMny = parseFloat(
    occupyMnyTopLimit.supplyMaxOccupyMny || "0"
  );
  if (orderMaxOccMny > supplyMaxOccupyMny) {
    orderMaxOccMny = supplyMaxOccupyMny;
  }
  if (ifOccupyForSalePrice) {
    if (orderMaxOccMny > totalDealAmount) {
      orderMaxOccMny = totalDealAmount;
    }
  }
  if (orderMaxOccMny < 0) {
    orderMaxOccMny = 0;
  }
  return +(orderMaxOccMny.toFixed(currency.currencyAmountScale));
};
// 匹配客户可用费用余额
export const matchCustomerCast = (orderCartData, occupyMnyTopLimits) => {
  if (!orderCartData || orderCartData.length < 1) return {};
  if (!occupyMnyTopLimits || !Array.isArray(occupyMnyTopLimits) || occupyMnyTopLimits.length < 1) return {};
  // 获取商品行产品线主键
  const productLineIds = [];
  orderCartData.forEach(item => {
    if (!productLineIds.includes(item.productLineId)) {
      productLineIds.push(item.productLineId);
    }
  });
  const financeOrgIds = [];
  // 产品线为空
  const defalutoccupyMnyTopLimit = occupyMnyTopLimits.find(limit => {
    return limit.productLineIds && (limit.productLineIds.includes(null) || limit.productLineIds.includes(""));
  });
  // 判断每条产品线对应的财务组织
  productLineIds.forEach(lineId => {
    const occupyMnyTopLimit = occupyMnyTopLimits.find(limit => {
      return limit.productLineIds && limit.productLineIds.includes(lineId);
    });
    if (occupyMnyTopLimit) {
      if (!financeOrgIds.includes(occupyMnyTopLimit.financeOrgId)) {
        financeOrgIds.push(occupyMnyTopLimit.financeOrgId);
      }
    } else if (defalutoccupyMnyTopLimit) {
      if (!financeOrgIds.includes(defalutoccupyMnyTopLimit.financeOrgId)) {
        financeOrgIds.push(defalutoccupyMnyTopLimit.financeOrgId);
      }
    }
  });
  // 如果订单商品分属不同的财务组织，则不能使用费用
  if (financeOrgIds && financeOrgIds.length > 1) return {};

  const occupyMnyTopLimit = occupyMnyTopLimits.find(limit => {
    return limit.financeOrgId == financeOrgIds[0];
  });
  return occupyMnyTopLimit || {};
};
/**
 * 判断供应商是否组织
 * @param {*} supplierId
 * @param {*} supplierData
 */
export const ifSupplierIsOrg = (supplierId, supplierData) => {
  if (!supplierId || !supplierData || !Array.isArray(supplierData)) return false;
  const supplier = supplierData.find(item => supplierId == item.id);
  if (supplier) {
    if (supplier.isPrimaryChannel == "1") {
      return true;
    }
  }
  return false;
};
/**
 * 使用AntDesign Upload组件，编辑展示附件时补充信息
 * @param {*} fileList
 */
export const fillDefalutInfoForUpload = (fileList) => {
  if (fileList && fileList.length > 0) {
    fileList.forEach(item => {
      item.uid = `${Math.random()}`;
      item.key = `${Math.random()}`;
      item.name = item.attachmentName;
      item.url = item.attachmentUrl;
      item.status = "done";
    });
    return fileList;
  }
  return [];
};
/**
 * 根据商品行，转换BOM行信息
 * @param {*} orderItems
 */
export const translateItemBomFromItem = (orderItems) => {
  if (!orderItems || orderItems.length < 1) return [];
  const orderItemBomData = [];
  let bomIndex = 0;
  orderItems.forEach((item, index) => {
    item.persistStatus = "new";
    item.rowNum = (index + 1) * 10;
    if (item.reqOrderItemBoms && item.reqOrderItemBoms.length > 0) {
      item.reqOrderItemBoms.forEach(itemBom => {
        bomIndex++;
        const newItemBom = Object.assign({}, item, itemBom);
        newItemBom.rowNum = bomIndex * 10;
        newItemBom.parentRowNum = item.rowNum;
        newItemBom.parentGoodsId = item.goodsId;
        newItemBom.persistStatus = "new";
        newItemBom.parentGoodsCode = item.goodsCode;
        newItemBom.parentGoodsName = item.goodsDisplayName;
        const childGoodsQty = parseFloat(itemBom.childGoodsQty || 1);
        newItemBom.mainNum = item.mainNum * childGoodsQty;
        newItemBom.orderNum = item.orderNum * childGoodsQty;
        newItemBom.goodsId = itemBom.childGoodsId;
        newItemBom.goodsDisplayName = itemBom.childGoodsName;
        newItemBom.goodsName = itemBom.childGoodsName;
        newItemBom.goodsCode = itemBom.childGoodsCode;
        newItemBom.goodsImg = itemBom.mainPictureFileUrl;
        newItemBom.version = itemBom.childGoodsVersion;
        newItemBom.childGoodsQty = itemBom.childGoodsQty || 1;
        newItemBom.originalGoodsId = itemBom.childOriginalGoodsId;
        newItemBom.orderNumUnitId = itemBom.childGoodsUnitId;
        newItemBom.orderNumUnitCode = itemBom.childGoodsUnitCode;
        newItemBom.orderNumUnitName = itemBom.childGoodsUnitName;
        newItemBom.orderNumUnitScale = itemBom.assistUnitPrecision || 0;
        newItemBom.mainNumUnitId = itemBom.childGoodsUnitId;
        newItemBom.mainNumUnitCode = itemBom.childGoodsUnitCode;
        newItemBom.mainNumUnitName = itemBom.childGoodsUnitName;
        newItemBom.mainNumUnitScale = itemBom.basicUnitPrecision || 0;
        // 选配
        if(itemBom.baseGoodsOptValue) {
          newItemBom.baseGoodsOptId = itemBom.baseGoodsOptId;
          newItemBom.baseGoodsOptValue = itemBom.baseGoodsOptValue;
        }
        // 补充额外字段
        newItemBom.productLineId = itemBom.productLineId;
        newItemBom.weight = itemBom.grossWeight || ""; // 默认取毛重
        newItemBom.volume = itemBom.volume;
        newItemBom.orderNumUnit = itemBom.childGoodsUnitName;
        newItemBom.mainNumUnit = itemBom.childGoodsUnitName;
        newItemBom.goodsImg = itemBom.childGoodsMainPictureFileUrl || "";
        newItemBom.conversionRate = itemBom.childGoodsConversionRate;
        newItemBom.basePrice = itemBom.childGoodsBasePrice || 0;
        newItemBom.salePrice = itemBom.childGoodsBaseDiscountPrice || 0;
        newItemBom.isOptional = itemBom.isOptional;
        newItemBom.salePrice = itemBom.salePrice || 0;
        newItemBom.promPrice = itemBom.salePrice || 0;
        newItemBom.currency = item.currencyId;
        newItemBom.isGift = item.isGift;
        newItemBom.rowWeight = 0;
        newItemBom.rowVolume = 0;
        newItemBom.stock = 0; // 库存
        newItemBom.amount = 0;
        newItemBom.promAmount = 0;
        newItemBom.offsetAmount = 0;
        newItemBom.dealAmount = 0;
        orderItemBomData.push(newItemBom);
      });
    } else {
      bomIndex++;
      const translate = {
        rowNum: bomIndex * 10,
        parentRowNum: item.rowNum,
        parentGoodsId: item.goodsId,
        persistStatus: "new",
        parentGoodsCode: item.goodsCode,
        parentGoodsName: item.goodsDisplayName,
        childGoodsQty: 1,
        orderNumUnit: item.orderNumUnitName,
        mainNumUnit: item.mainNumUnitName
      };
      const newItemBom = Object.assign({}, item, translate);
      orderItemBomData.push(newItemBom);
    }
  });
  return orderItemBomData;
};
