package com.sunxung.factoring.service.acceptancesheet.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.acceptance.*;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.mapper.acceptancesheet.AcceptancePriceAdjustApprovalInfoMapper;
import com.sunxung.factoring.service.acceptancesheet.*;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 验收单-单价调整审核表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-12-25
 */
@Service("acceptanceSheetAdjustApprovalService")
public class AcceptancePriceAdjustApprovalInfoServiceImpl extends ServiceImpl<AcceptancePriceAdjustApprovalInfoMapper, AcceptancePriceAdjustApprovalInfo>
        implements IAcceptancePriceAdjustApprovalInfoService {

    @Autowired
    private ICAcceptancePriceAdjustInfoService acceptancePriceAdjustInfoService;
    @Autowired
    private ICAcceptancePriceGoodsInfoService acceptancePriceGoodsInfoService;
    @Autowired
    private AcceptanceBasicInfoService acceptanceBasicInfoService;
    @Autowired
    private AcceptanceGoodsInfoService acceptanceGoodsInfoService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private UserService userService;
    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Override
    public AcceptancePriceAdjustApprovalInfo getView(Long id) {
        return getById(id);
    }

    @Override
    public void apprval(AcceptancePriceAdjustApprovalInfo adjustApprovalInfo) {

        if (adjustApprovalInfo.getBusinessKey() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "businessKey不能为空！");
        }

        AcceptanceBasicInfo basicInfo = acceptanceBasicInfoService.getById(adjustApprovalInfo.getBusinessKey());
        //最新一条单价调整数据
        CAcceptancePriceAdjustInfo priceAdjustInfo = acceptancePriceAdjustInfoService
                .getOne(Wrappers.<CAcceptancePriceAdjustInfo>lambdaQuery().eq(CAcceptancePriceAdjustInfo::getcAcceptanceBasicInfoId, adjustApprovalInfo.getBusinessKey())
                        .orderByDesc(CAcceptancePriceAdjustInfo::getGmtCreate).last("limit 1"));
        adjustApprovalInfo.setcAcceptancePriceAdjustInfoId(priceAdjustInfo.getId());
        save(adjustApprovalInfo);

        //通过时同步更新验收单基础信息表字段和货物信息
        if (adjustApprovalInfo.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
            basicInfo.setCheckOperatorSupplier(priceAdjustInfo.getCheckOperatorSupplier());
            basicInfo.setAcceptanceStatus(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
            acceptanceBasicInfoService.updateById(basicInfo);
           // acceptanceGoodsInfoService.remove(new QueryWrapper<AcceptanceGoodsInfo>().eq("c_acceptance_basic_info_id", adjustApprovalInfo.getBusinessKey()));
            List<CAcceptancePriceGoodsInfo> priceGoodsInfoList = acceptancePriceGoodsInfoService.lambdaQuery()
                    .eq(CAcceptancePriceGoodsInfo::getcAcceptancePriceAdjustInfoId, priceAdjustInfo.getId()).list();
            if (CollectionUtil.isNotEmpty(priceGoodsInfoList)) {
                priceGoodsInfoList.forEach(priceGoodsInfo -> {
//                    AcceptanceGoodsInfo goodsInfo = new AcceptanceGoodsInfo();
//                    BeanUtils.copyProperties(priceGoodsInfo,goodsInfo);
//                    goodsInfo.setAcceptanceBasicInfoId(priceAdjustInfo.getcAcceptanceBasicInfoId());
//                    acceptanceGoodsInfoService.save(goodsInfo);
                    LambdaUpdateWrapper<AcceptanceGoodsInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(AcceptanceGoodsInfo::getId, priceGoodsInfo.getGoodsId())
                        .set(AcceptanceGoodsInfo::getReferencePrice, priceGoodsInfo.getReferencePrice())
                    .set(AcceptanceGoodsInfo::getFloatingPrice,priceGoodsInfo.getFloatingPrice())
                    .set(AcceptanceGoodsInfo::getGoodsQuantity,priceGoodsInfo.getGoodsQuantity())
                    .set(AcceptanceGoodsInfo::getSalesPrice,priceGoodsInfo.getReferencePrice().add(priceGoodsInfo.getFloatingPrice()))
                    .set(AcceptanceGoodsInfo::getAcceptanceDate,priceGoodsInfo.getAcceptanceDate());
                    acceptanceGoodsInfoService.update(lambdaUpdateWrapper);

                });
            }

        }

//        //流程处理
//        BusinessProcessingLog log = businessProcessingLogService.getByBusinessTypeBusinessKey(ConstantUtil.ACCEPTANCE_SHEET_ADJUST, priceAdjustInfo.getId());
        //流程处理
        BusinessProcessingLog log = businessProcessingLogService.getByBusinessTypeBusinessKey(ConstantUtil.ACCEPTANCE_SHEET_ADJUST, adjustApprovalInfo.getBusinessKey());


        //拾取task
        flowableService.claimTask(log.getHistoricTaskId(), ThreadLocalUtil.getUserId(), ConstantUtil.LEGAL_SPECIALIST);

        Map<String, Object> msgVariables = new HashMap<>();

            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "验收单编号：" + basicInfo.getAcceptanceNumber());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "验收单编号为“" + basicInfo.getAcceptanceNumber() + "”的验收单已进入“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.ACCEPTANCE_SHEET_ADJUST) + "—单价审核阶段，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
            Map<String, Object> procVariables = new HashMap<>();

            flowableService.completeMyTask(log.getHistoricTaskId(), basicInfo, null,
                    ConstantConversionUtil.processApprovalResult.get(adjustApprovalInfo.getApprovalConclusion()), adjustApprovalInfo.getId(),
                    msgVariables, ConstantUtil.ACCEPTANCE_SHEET_ADJUST);

    }


}
