package com.gree.mall.manager.logic.material.manage;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.gree.mall.manager.bean.material.stock.WorkerStockDTO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.enums.material.*;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.material.stock.MaterialGoodsStockLogic;
import com.gree.mall.manager.plus.entity.WebsitPartsChangeSales;
import com.gree.mall.manager.plus.entity.WebsitPartsChangeSalesItem;
import com.gree.mall.manager.plus.entity.WebsitPartsSales;
import com.gree.mall.manager.plus.entity.WebsitPartsSalesItem;
import com.gree.mall.manager.plus.service.WebsitPartsChangeSalesItemService;
import com.gree.mall.manager.plus.service.WebsitPartsSalesItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class WebsitPartsSalesLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitPartsSalesItemService websitPartsSalesItemService;
    private final WebsitPartsChangeSalesItemService websitPartsChangeSalesItemService;
    private final MaterialGoodsStockLogic materialGoodsStockLogic;

    @Transactional
    public void updatePartsSalesOrder(WebsitPartsSales salesOrder) throws Exception {
        String sheetId = commonLogic.generateMaterialNo(salesOrder.getCompanyWechatId(), "ZX", PartsRefTypeEnum.CHANGE_SALES.getKey(), 13);

        List<WebsitPartsSalesItem> partsSalesOrderItemList = websitPartsSalesItemService.lambdaQuery()
                .eq(WebsitPartsSalesItem::getSalesId, salesOrder.getId())
                .list();

        List<WebsitPartsChangeSalesItem> partsChangeSalesItemList = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (WebsitPartsSalesItem partsSalesOrderItem : partsSalesOrderItemList) {
            // 大于0才转明细
            if (partsSalesOrderItem.getQty().compareTo(BigDecimal.ZERO) > 0) {
                WebsitPartsChangeSalesItem partsChangeSalesItem = new WebsitPartsChangeSalesItem();
                partsChangeSalesItem.setChangeSalesNo(sheetId)
                        .setIdentity(salesOrder.getIdentity())
                        .setWebsitId(salesOrder.getWebsitId())
                        .setPartsWebsitId(salesOrder.getPartsWebsitId())
                        .setPartsNumber(partsSalesOrderItem.getPartsNumber())
                        .setPartsName(partsSalesOrderItem.getPartsName())
                        .setMaterialGroupName(partsSalesOrderItem.getMaterialGroupName())
                        .setGoodsStockUnit(partsSalesOrderItem.getGoodsStockUnit())
                        .setSalesId(salesOrder.getId())
                        .setSalesPrice(partsSalesOrderItem.getSalesPrice())
                        .setMarketPrice(partsSalesOrderItem.getMarketPrice())
                        .setSecondPrice(partsSalesOrderItem.getSecondPrice())
                        .setQty(partsSalesOrderItem.getQty())
                        .setTotalAmount(partsSalesOrderItem.getSalesPrice().multiply(partsSalesOrderItem.getQty()));
                totalAmount = totalAmount.add(partsChangeSalesItem.getTotalAmount());
                partsChangeSalesItemList.add(partsChangeSalesItem);
            }
        }

        if (CollectionUtil.isEmpty(partsChangeSalesItemList)) {
            // 如果明细为空 变更为END=完结
            salesOrder.setPushFlag(PartsPushFlagEnum.END.getKey());
            salesOrder.updateById();
            materialMapper.updateItemPushFlag(salesOrder.getId(), PartsPushFlagEnum.END.toString());
            return;
        }

        // 变更为TRANS=转销售
        salesOrder.setPushFlag(PartsPushFlagEnum.TRANS.toString());
        salesOrder.updateById();
        materialMapper.updateItemPushFlag(salesOrder.getId(), PartsPushFlagEnum.TRANS.toString());

        WebsitPartsChangeSales partsChangeSales = new WebsitPartsChangeSales();

        partsChangeSales.setChangeSalesNo(sheetId)
                .setCompanyWechatId(salesOrder.getCompanyWechatId())
                .setCompanyWechatName(salesOrder.getCompanyWechatName())
                .setSalesId(salesOrder.getId())
                .setChangeType(PartsRefTypeEnum.CHANGE_SALES.getKey())
                .setTotalAmount(totalAmount)
                .setWebsitId(salesOrder.getWebsitId())
                .setWebsitName(salesOrder.getWebsitName())
                .setPartsWebsitId(salesOrder.getPartsWebsitId())
                .setIdentity(salesOrder.getIdentity())
                .setWorkerId(salesOrder.getWorkerId())
                .setWorkerName(salesOrder.getWorkerName())
                .setSalesEndTime(salesOrder.getEndTime())
                .setFlag(PartsOrderFlagEnum.SUBMIT.getKey())
                .setCreateBy("自动处理")
                .setCreateTime(DateUtil.date())
                .setUpdateBy("自动处理")
                .setUpdateTime(DateUtil.date())
                .setSubmitBy("自动处理")
                .setSubmitTime(DateUtil.date())
                .insert();

        websitPartsChangeSalesItemService.saveBatch(partsChangeSalesItemList);

        // 师傅新件库存减 临占新件库存加
        List<WorkerStockDTO> workerStockDTOList = this.createWorkerStockDTO(partsChangeSales, partsChangeSalesItemList,
                PartsRefTypeEnum.CHANGE_SALES.getRemark(), PartsAttrEnum.NEW.getKey(), PartsAttrEnum.TEMP_NEW.getKey());
        materialGoodsStockLogic.handleWorkerStock(workerStockDTOList);
    }

    private List<WorkerStockDTO> createWorkerStockDTO(WebsitPartsChangeSales partsChangeSales,
                                                      List<WebsitPartsChangeSalesItem> partsChangeSalesItemList,
                                                      String refType, String partsAttr1,
                                                      String partsAttr2) {
        List<WorkerStockDTO> workerStockDTOList = new ArrayList<>();
        if (StringUtils.isNotBlank(partsAttr1)) {
            for (WebsitPartsChangeSalesItem partsChangeSalesItem : partsChangeSalesItemList) {
                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(partsChangeSales.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(partsChangeSales.getCompanyWechatName());
                workerStockDTO.setIdentity(partsChangeSales.getIdentity());
                workerStockDTO.setWorkerId(partsChangeSales.getWorkerId());
                workerStockDTO.setWorkerName(partsChangeSales.getWorkerName());
                workerStockDTO.setWebsitId(partsChangeSales.getWebsitId());
                workerStockDTO.setWebsitName(partsChangeSales.getWebsitName());
                workerStockDTO.setPartsWebsitId(partsChangeSales.getPartsWebsitId());
                workerStockDTO.setSdate(DateUtil.date());
                workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
                workerStockDTO.setGoodsId(partsChangeSalesItem.getPartsNumber());
                workerStockDTO.setGoodsName(partsChangeSalesItem.getPartsName());
                workerStockDTO.setMaterialGroupName(partsChangeSalesItem.getMaterialGroupName());
                workerStockDTO.setGoodsStockUnit(partsChangeSalesItem.getGoodsStockUnit());
                workerStockDTO.setPrice(partsChangeSalesItem.getSalesPrice());
                workerStockDTO.setRef(partsChangeSales.getChangeSalesNo());
                workerStockDTO.setRefType(refType);
                workerStockDTO.setPartsAttr(partsAttr1);
                workerStockDTO.setChangeQty(partsChangeSalesItem.getQty());
                workerStockDTO.setDirectFlag(DirectFlagEnum.SUB.getKey());
                workerStockDTO.setRemark("");
                workerStockDTO.setOperateBy("自动处理");
                workerStockDTO.setOperateTime(DateUtil.date());

                workerStockDTOList.add(workerStockDTO);
            }
        }
        if (StringUtils.isNotBlank(partsAttr2)) {
            for (WebsitPartsChangeSalesItem partsChangeSalesItem : partsChangeSalesItemList) {
                WorkerStockDTO workerStockDTO = new WorkerStockDTO();
                workerStockDTO.setCompanyWechatId(partsChangeSales.getCompanyWechatId());
                workerStockDTO.setCompanyWechatName(partsChangeSales.getCompanyWechatName());
                workerStockDTO.setIdentity(partsChangeSales.getIdentity());
                workerStockDTO.setWorkerId(partsChangeSales.getWorkerId());
                workerStockDTO.setWorkerName(partsChangeSales.getWorkerName());
                workerStockDTO.setWebsitId(partsChangeSales.getWebsitId());
                workerStockDTO.setWebsitName(partsChangeSales.getWebsitName());
                workerStockDTO.setPartsWebsitId(partsChangeSales.getPartsWebsitId());
                workerStockDTO.setSdate(DateUtil.date());
                workerStockDTO.setGoodsType(WebsitGoodsTypeEnum.P.getKey());
                workerStockDTO.setGoodsId(partsChangeSalesItem.getPartsNumber());
                workerStockDTO.setGoodsName(partsChangeSalesItem.getPartsName());
                workerStockDTO.setMaterialGroupName(partsChangeSalesItem.getMaterialGroupName());
                workerStockDTO.setGoodsStockUnit(partsChangeSalesItem.getGoodsStockUnit());
                workerStockDTO.setPrice(partsChangeSalesItem.getSalesPrice());
                workerStockDTO.setRef(partsChangeSalesItem.getChangeSalesNo());
                workerStockDTO.setRefType(refType);
                workerStockDTO.setPartsAttr(partsAttr2);
                workerStockDTO.setChangeQty(partsChangeSalesItem.getQty());
                workerStockDTO.setDirectFlag(DirectFlagEnum.ADD.getKey());
                workerStockDTO.setRemark("");
                workerStockDTO.setOperateBy("自动处理");
                workerStockDTO.setOperateTime(DateUtil.date());

                workerStockDTOList.add(workerStockDTO);
            }
        }
        return workerStockDTOList;
    }
}
