package com.huigou.topsun.sap.processQuotedPrice.application.impl;

import com.huigou.cache.DictUtil;
import com.huigou.data.domain.model.AbstractEntity;
import com.huigou.data.domain.query.QueryPageRequest;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.sap.processQuotedPrice.application.ProcessQuotedPriceItemApplication;
import com.huigou.topsun.sap.processQuotedPrice.application.ProcessQuotedPriceItemNumberApplication;
import com.huigou.topsun.sap.processQuotedPrice.domain.ProcessQuotedPrice;
import com.huigou.topsun.sap.processQuotedPrice.domain.ProcessQuotedPriceItem;
import com.huigou.topsun.sap.processQuotedPrice.domain.ProcessQuotedPriceItemNumber;
import com.huigou.topsun.sap.processQuotedPrice.domain.query.ProcessQuotedPriceQueryRequest;
import com.huigou.topsun.sap.processQuotedPrice.domain.vo.ProcessQuotedPriceAndMwskzVo;
import com.huigou.topsun.sap.processQuotedPrice.domain.vo.ProcessQuotedPricePrintVo;
import com.huigou.topsun.sap.processQuotedPrice.repository.ProcessQuotedPriceItemRepository;
import com.huigou.topsun.sap.processQuotedPrice.repository.ProcessQuotedPriceRepository;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import com.huigou.util.ClassHelper;
import com.huigou.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xin.lu
 * @Date: 2024/10/30/14:17
 * @Description:
 */
@Service("processQuotedPriceItemApplication")
public class ProcessQuotedPriceItemApplicationImpl extends BaseApplication implements ProcessQuotedPriceItemApplication {
    @Autowired
    private ProcessQuotedPriceItemRepository processQuotedPriceItemRepository;
    @Autowired
    private ProcessQuotedPriceItemNumberApplication processQuotedPriceItemNumberApplication;
    @Autowired
    private ProcessQuotedPriceRepository processQuotedPriceRepository;
    @Override
    public void saveProcessQuotedPriceItems(String processQuotedPriceId, List<ProcessQuotedPriceItem> processQuotedPriceItems) {
        for (ProcessQuotedPriceItem processQuotedPriceItem : processQuotedPriceItems) {
            processQuotedPriceItem.setProcessQuotedPriceId(processQuotedPriceId);
            processQuotedPriceItemRepository.save(processQuotedPriceItem);

            //保存明细价格区间
            List<Map<String, Object>> numberList = processQuotedPriceItem.getNumberList();
            if (!CollectionUtils.isEmpty(numberList)){
                List<ProcessQuotedPriceItemNumber> itemNumberList = numberList
                        .stream()
                                .map(itemNumberMap -> {
                                    ProcessQuotedPriceItemNumber priceItemNumber = ClassHelper.fromMap(ProcessQuotedPriceItemNumber.class, itemNumberMap);
                                    priceItemNumber.setId((String) itemNumberMap.get("id"));
                                    return priceItemNumber;
                                }).collect(Collectors.toList());
                processQuotedPriceItemNumberApplication.saveProcessQuotedPriceItemNumbers(processQuotedPriceItem.getId(),itemNumberList);
            }
        }
    }

    @Override
    public Map<String, Object> queryProcessQuotedPriceItems(ProcessQuotedPriceQueryRequest queryRequest) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtil.isNotBlank(queryRequest.getProcessQuotedPriceId())){
            QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "processQuotedPriceItems");
            QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
            map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        }
        return map;
    }

    @Override
    public void deleteByIds(List<String> ids) {
        ids.forEach(id->{
            //先删除明细下的报价规则
            List<ProcessQuotedPriceItemNumber> itemNumberList = processQuotedPriceItemNumberApplication.findByProcessQuotedPriceItemId(id);
            if (!CollectionUtils.isEmpty(itemNumberList)){
                List<String> itemNumberIds = itemNumberList
                        .stream()
                                .map(AbstractEntity::getId).collect(Collectors.toList());
                processQuotedPriceItemNumberApplication.deleteByIds(itemNumberIds);
            }
            //再删除报价明细
            processQuotedPriceItemRepository.delete(id);
        });
    }

    @Override
    public List<ProcessQuotedPriceItem> findByProcessQuotedPriceId(String processQuotedPriceId) {
        return processQuotedPriceItemRepository.findByProcessQuotedPriceId(processQuotedPriceId);
    }

    @Override
    public void updateProcessQuotedPriceItemStatus(List<String> ids,String status) {
        List<ProcessQuotedPriceItem> priceItemList = processQuotedPriceItemRepository.findAll(ids);
        for (ProcessQuotedPriceItem processQuotedPriceItem : priceItemList) {
            processQuotedPriceItem.setStatus(status);
        }
        processQuotedPriceItemRepository.save(priceItemList);
    }

    @Override
    public Map<String, Object> print(String id) {
        ProcessQuotedPriceItem quotedPriceItem = processQuotedPriceItemRepository.findOne(id);
        ProcessQuotedPrice quotedPrice = processQuotedPriceRepository.findOne(quotedPriceItem.getProcessQuotedPriceId());
        Map<String, Object> map = ClassHelper.beanToMap(quotedPrice);
        List<ProcessQuotedPriceItemNumber> itemNumberList = processQuotedPriceItemNumberApplication.findByProcessQuotedPriceItemId(quotedPriceItem.getId());
        itemNumberList = itemNumberList
                .stream()
                .sorted(Comparator.comparing(ProcessQuotedPriceItemNumber::getNumberFrom)).collect(Collectors.toList());
        List<ProcessQuotedPricePrintVo> printVoList = new ArrayList<>();
        for (int i = 0; i < itemNumberList.size(); i++) {
            ProcessQuotedPriceItemNumber itemNumber = itemNumberList.get(i);
            ProcessQuotedPricePrintVo pricePrintVo = new ProcessQuotedPricePrintVo();
            ClassHelper.copyProperties(itemNumber, pricePrintVo);
            pricePrintVo.setProductCode(quotedPriceItem.getProductCode());
            pricePrintVo.setProductName(quotedPriceItem.getProductName());
            pricePrintVo.setUnitName(quotedPriceItem.getUnitName());
            pricePrintVo.setItemNo(String.valueOf(i+1));
            printVoList.add(pricePrintVo);
        }
        map.put("printVoList",printVoList);
        return map;
    }

    @Override
    public ProcessQuotedPriceAndMwskzVo findPriceByProductAndProcess(ProcessQuotedPriceAndMwskzVo data,String productCode, String outProcess, BigDecimal number,String lifnr) {
        List<ProcessQuotedPriceItem> quotedPriceItemList = processQuotedPriceItemRepository.findByProductCodeAndOutProcess(productCode, outProcess);
        if (!CollectionUtils.isEmpty(quotedPriceItemList)){
            for (ProcessQuotedPriceItem quotedPriceItem : quotedPriceItemList) {
                ProcessQuotedPrice quotedPrice = processQuotedPriceRepository.findOne(quotedPriceItem.getProcessQuotedPriceId());
                //审批完成的；已启用的；对应供应商
                if (quotedPrice.getStatusId() == BizBillStatus.COMPLETED.getId() && lifnr.equals(quotedPrice.getSupplier()) && "1".equals(quotedPriceItem.getStatus())){
                    List<ProcessQuotedPriceItemNumber> numberList = processQuotedPriceItemNumberApplication.findByProcessQuotedPriceItemId(quotedPriceItem.getId());
                    List<ProcessQuotedPriceAndMwskzVo> processQuotedPriceAndMwskzVoList = numberList
                            .stream()
                            .filter(processQuotedPriceItemNumber ->
                                    (processQuotedPriceItemNumber.getNumberFrom().compareTo(number) < 0
                                            && processQuotedPriceItemNumber.getNumberTo().compareTo(number) >= 0))
                            .map(
                                    processQuotedPriceItemNumber -> {
                                        ProcessQuotedPriceAndMwskzVo processQuotedPriceAndMwskzVo = new ProcessQuotedPriceAndMwskzVo();
                                        //返回含税单价+运输费
                                        BigDecimal unitPrice = processQuotedPriceItemNumber.getUnitPrice();
                                        BigDecimal freight = processQuotedPriceItemNumber.getFreight();
                                        BigDecimal packMoney = processQuotedPriceItemNumber.getPackMoney();
                                        if (freight != null){
                                            unitPrice = unitPrice.add(freight);
                                        }
                                        if (packMoney != null){
                                            unitPrice = unitPrice.add(packMoney);
                                        }
                                        processQuotedPriceAndMwskzVo.setUnitPrice(unitPrice);
                                        processQuotedPriceAndMwskzVo.setPurchaseMwskz(processQuotedPriceItemNumber.getPurchaseMwskz());
                                        String detailText = DictUtil.getDictionaryDetailText("purchaseMwskz", processQuotedPriceAndMwskzVo.getPurchaseMwskz());
                                        processQuotedPriceAndMwskzVo.setPurchaseMwskzTextView(detailText);
                                        return processQuotedPriceAndMwskzVo;
                                    }
                            ).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(processQuotedPriceAndMwskzVoList)){
                        data = processQuotedPriceAndMwskzVoList.get(0);
                    }
                }
            }
        }
        return data;
    }

    @Override
    public ProcessQuotedPriceItemNumber findQuotedPriceByProductAndProcess(String productCode, String outProcess, BigDecimal number,String lifnr) {
        List<ProcessQuotedPriceItem> quotedPriceItemList = processQuotedPriceItemRepository.findByProductCodeAndOutProcess(productCode, outProcess);
        ProcessQuotedPriceItemNumber quotedPriceItemNumber = new ProcessQuotedPriceItemNumber();
        if (!CollectionUtils.isEmpty(quotedPriceItemList)){
            for (ProcessQuotedPriceItem quotedPriceItem : quotedPriceItemList) {
                ProcessQuotedPrice quotedPrice = processQuotedPriceRepository.findOne(quotedPriceItem.getProcessQuotedPriceId());
                //审批完成的；已启用的；对应供应商
                if (quotedPrice.getStatusId() == BizBillStatus.COMPLETED.getId() && lifnr.equals(quotedPrice.getSupplier()) && "1".equals(quotedPriceItem.getStatus())){
                    List<ProcessQuotedPriceItemNumber> numberList = processQuotedPriceItemNumberApplication.findByProcessQuotedPriceItemId(quotedPriceItem.getId());
                    numberList = numberList
                            .stream()
                            .filter(processQuotedPriceItemNumber ->
                                    (processQuotedPriceItemNumber.getNumberFrom().compareTo(number) < 0
                                            && processQuotedPriceItemNumber.getNumberTo().compareTo(number) >= 0))
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(numberList)){
                        quotedPriceItemNumber = numberList.get(0);
                    };

                }
            }
        }
        return quotedPriceItemNumber;
    }
}
