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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.acceptance.*;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.mapper.acceptancesheet.CAcceptancePriceAdjustInfoMapper;
import com.sunxung.factoring.service.acceptancesheet.*;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 验收单单价调整表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-12-19
 */
@Service("acceptanceSheetAdjustService")
public class CAcceptancePriceAdjustInfoServiceImpl extends ServiceImpl<CAcceptancePriceAdjustInfoMapper, CAcceptancePriceAdjustInfo>
        implements ICAcceptancePriceAdjustInfoService {

    @Autowired
    private AcceptanceBasicInfoService acceptanceBasicInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ICAcceptancePriceGoodsInfoService acceptancePriceGoodsInfoService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private UserService userService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private ICAcceptancePriceAdjustHisInfoService acceptancePriceAdjustHisInfoService;
    @Autowired
    private IAcceptancePriceGoodsHisInfoService acceptancePriceGoodsHisInfoService;
    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private ICAcceptancePriceAdjustInfoService acceptancePriceAdjustInfoService;

    @Override
    public void startProcess(CAcceptancePriceAdjustInfo acceptancePriceAdjustInfo) {

        AcceptanceBasicInfo acceptanceBasicInfo = acceptanceBasicInfoService.lambdaQuery()
            .eq(AcceptanceBasicInfo::getId,acceptancePriceAdjustInfo.getcAcceptanceBasicInfoId()).one();

        AcceptancePriceAdjustHisInfo history = addHistory(acceptancePriceAdjustInfo);

        if (acceptancePriceAdjustInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "价格调整信息不能为空！");
        }

        //2.新增处理人-- 当前线程
        //项目信息
        ProjectInformation projectInformation = projectInformationService
                .getOne(new QueryWrapper<ProjectInformation>().eq("business_number", acceptanceBasicInfo.getBusinessNumber()));

        User admin = userService.getByLoginName("admin");
        //3.开启流程实例
        Map<String, Object> procVariables = new HashMap<>();
        procVariables.put(ConstantUtil.ACCEPTANCE_SHEET_ADJUST_ASSIGNEE, admin.getId());

        //查询条件：验收单编号/业务编号/核心企业名称/业务名称/供应商名称
        Enterprise supplier = enterpriseService.getById(acceptanceBasicInfo.getcSupplierInfoId());
        Enterprise customer = enterpriseService.getById(acceptanceBasicInfo.getcProjectCoreEnterpriseId());
        String queryBusiness = acceptanceBasicInfo.getAcceptanceNumber() + FlowableUtil.splitChar + acceptanceBasicInfo.getBusinessNumber()
                + FlowableUtil.splitChar + customer.getCorporateName() + FlowableUtil.splitChar + projectInformation.getProjectName()
                + FlowableUtil.splitChar + supplier.getCorporateName();
        ProcessInstance processInst = flowableService.startProcessInstance(acceptanceBasicInfo, procVariables,
                FlowableUtil.generateBusinessKey(acceptanceBasicInfo, ConstantUtil.ACCEPTANCE_SHEET_ADJUST, queryBusiness),
                null, ConstantUtil.ACCEPTANCE_SHEET_ADJUST);
        if (processInst == null) {
            throw new BusinessException(CodeUtil.FAIL, "流程启动失败");
        }
        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.OPERATION_SPECIALIST + "法务专员角色内无任何用户！");
        }
        String legalSpecias = legalSpecialists.stream().map(c -> c.toString()).collect(Collectors.joining(","));

        Task task = flowableService.findRuntimeTaskByProcessInstId(processInst.getId()).get(0);
        User user = new User();
        user.setId(Long.parseLong(task.getAssignee()));
        ThreadLocalUtil.setUser(user);

        Map<String, Object> msgVariables = new HashMap<>();
        procVariables.put(ConstantUtil.ACCEPTANCE_SHEET_ADJUST_CANDIDATE, legalSpecias);

        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "验收单编号：" + acceptanceBasicInfo.getAcceptanceNumber());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
            "验收单编号为“" + acceptanceBasicInfo.getAcceptanceNumber() + "”的验收单已进入“"
                + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.ACCEPTANCE_SHEET_ADJUST) + "—单价审核阶段，"
                + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        flowableService.completeMyTask(task.getId(), acceptanceBasicInfo, procVariables, null, history.getId(), msgVariables, ConstantUtil.ACCEPTANCE_SHEET_ADJUST, legalSpecialists);



    }

    @Override
    public void handleProcess(CAcceptancePriceAdjustInfo acceptancePriceAdjustInfo) {

        AcceptanceBasicInfo acceptanceBasicInfo = acceptanceBasicInfoService.get(acceptancePriceAdjustInfo.getcAcceptanceBasicInfoId());

        if (acceptancePriceAdjustInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "价格调整信息不能为空！");
        }

        AcceptancePriceAdjustHisInfo history = addHistory(acceptancePriceAdjustInfo);
       // acceptanceBasicInfo.setId(history.getId());
        //完成流程第一步
        // 步提交验收单，开启下一步法务验收
        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.OPERATION_SPECIALIST + "法务专员角色内无任何用户！");
        }
        String legalSpecias = legalSpecialists.stream().map(c -> c.toString()).collect(Collectors.joining(","));
        User admin = userService.getByLoginName("admin");
        BusinessProcessingLog log = businessProcessingLogService.getByBusinessTypeBusinessKey(ConstantUtil.ACCEPTANCE_SHEET_ADJUST, acceptanceBasicInfo.getId());
        Map<String, Object> procVariables = new HashMap<>();
        Map<String, Object> msgVariables = new HashMap<>();


        Task task = flowableService.getByTaskQuery(log.getHistoricTaskId());
        User user = new User();
        user.setId(Long.parseLong(task.getAssignee()));
        ThreadLocalUtil.setUser(user);


            procVariables.put(ConstantUtil.ACCEPTANCE_SHEET_ADJUST_CANDIDATE, legalSpecias);
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "验收单编号：" + acceptanceBasicInfo.getAcceptanceNumber());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "验收单编号为“" + acceptanceBasicInfo.getAcceptanceNumber() + "”的验收单已进入“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.ACCEPTANCE_SHEET_ADJUST) + "—单价审核阶段，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
//            flowableService.completeMyTask(log.getHistoricTaskId(), acceptanceBasicInfo, procVariables, null, history.getId(),
//                    msgVariables, ConstantUtil.ACCEPTANCE_SHEET_ADJUST);
            flowableService.completeMyTask(log.getHistoricTaskId(), acceptanceBasicInfo, procVariables, null, history.getId(), msgVariables, ConstantUtil.ACCEPTANCE_SHEET_ADJUST, legalSpecialists);


    }

    @Override
    public AcceptancePriceAdjustHisInfo getView(Long id) {

        AcceptancePriceAdjustHisInfo priceAdjustInfoHis = acceptancePriceAdjustHisInfoService.getById(id);
        CAcceptancePriceAdjustInfo acceptancePriceAdjustInfo = acceptancePriceAdjustInfoService.getById(
            priceAdjustInfoHis.getcAcceptancePriceAdjustInfoId());
        AcceptanceBasicInfo acceptanceBasicInfo = acceptanceBasicInfoService.get(acceptancePriceAdjustInfo.getcAcceptanceBasicInfoId());
        priceAdjustInfoHis.setExpectedSettlementDate(acceptanceBasicInfo.getExpectedSettlementDate());
        //供应商（主企业）
        Enterprise mainEnterprise = enterpriseService.getById(acceptanceBasicInfo.getcSupplierInfoId());
        priceAdjustInfoHis.setMainEnterprise(mainEnterprise);
        //核心企业
        Enterprise customerEnterprise = enterpriseService.getById(acceptanceBasicInfo.getcProjectCoreEnterpriseId());
        priceAdjustInfoHis.setCoreEnterprise(customerEnterprise);
        //贸易平台
        Platform platform = platformService.getById(acceptanceBasicInfo.getTradingPlatformId());
        priceAdjustInfoHis.setPlatform(platform);
         //项目信息
        ProjectInformation one = projectInformationService.lambdaQuery().eq(
            ProjectInformation::getBusinessNumber, acceptanceBasicInfo.getBusinessNumber()).one();
        priceAdjustInfoHis.setBusinessBasicInfo(one);

//        //业务信息
//        BusinessBasicInfo byBusinessNumber = businessBasicInfoService.getByBusinessNumber(
//            acceptanceBasicInfo.getBusinessNumber());
     //   priceAdjustInfoHis.setBusinessBasicInfo(byBusinessNumber);
        //业务编号
        priceAdjustInfoHis.setBusinessNumber(acceptanceBasicInfo.getBusinessNumber());
        //货物信息
        List<AcceptancePriceGoodsHisInfo> goodsHisInfoList = acceptancePriceGoodsHisInfoService
                .lambdaQuery().eq(AcceptancePriceGoodsHisInfo::getcAcceptancePriceAdjustHisInfoId, id).list();
        priceAdjustInfoHis.setGoodsInfoList(goodsHisInfoList);
        //补充说明文件
        List<FileStorageDO> fileList = fileService.findByBusinessId(priceAdjustInfoHis.getId(), FileModuleDict.ChildEnum.ACCEPTANCE_ADJUST_HIS_FILE.getCode());
        priceAdjustInfoHis.setFileStorageList(fileList);

        return priceAdjustInfoHis;
    }

    @Override
    public AcceptanceBasicInfo get(Long id) {
        return  acceptanceBasicInfoService.get(id);

    }

    private AcceptancePriceAdjustHisInfo addHistory(CAcceptancePriceAdjustInfo acceptancePriceAdjustInfo) {

        //保存历史
        AcceptancePriceAdjustHisInfo priceAdjustHisInfo = new AcceptancePriceAdjustHisInfo();
        BeanUtils.copyProperties(acceptancePriceAdjustInfo, priceAdjustHisInfo);
        priceAdjustHisInfo.setcAcceptancePriceAdjustInfoId(acceptancePriceAdjustInfo.getId());
        acceptancePriceAdjustHisInfoService.save(priceAdjustHisInfo);
        //保存货物信息历史
        List<CAcceptancePriceGoodsInfo> priceGoodsInfoList = acceptancePriceAdjustInfo.getPriceGoodsInfoList();
        if (CollectionUtil.isNotEmpty(priceGoodsInfoList)) {
            priceGoodsInfoList.forEach(goods -> {
                AcceptancePriceGoodsHisInfo goodsHisInfo = new AcceptancePriceGoodsHisInfo();
                BeanUtils.copyProperties(goods, goodsHisInfo);
                goodsHisInfo.setcAcceptancePriceAdjustHisInfoId(priceAdjustHisInfo.getId());
                acceptancePriceGoodsHisInfoService.save(goodsHisInfo);
            });
        }
        //保存文件历史
        List<Long> fileIds = acceptancePriceAdjustInfo.getFileIds();
        if (CollectionUtil.isNotEmpty(fileIds)) {
            fileIds.forEach(fileId -> {
                FileStorageDO file = fileService.getById(fileId);
                file.setBusinessType(FileModuleDict.ChildEnum.ACCEPTANCE_ADJUST_HIS_FILE.getCode());
                file.setBusinessId(acceptancePriceAdjustInfo.getId());
                file.setId(null);
                fileService.save(file);
            });

        }

        return priceAdjustHisInfo;

    }


}
