package com.sunxung.factoring.service.salescontractmanagement.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.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.salescontractmanagement.*;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.mapper.salescontractmanagement.CSalesContractSupplementBasicInfoMapper;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.salescontractmanagement.*;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
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 org.springframework.transaction.annotation.Transactional;

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-12
 */
@Service("sales_supplement_basicService")
public class CSalesContractSupplementBasicInfoServiceImpl extends ServiceImpl<CSalesContractSupplementBasicInfoMapper, CSalesContractSupplementBasicInfo> implements ICSalesContractSupplementBasicInfoService {

    @Autowired
    private FileService fileService;
    @Autowired
    private ISalesContractSupplementGoodsInfoService supplementGoodsInfoService;
    @Autowired
    private ISalesContractSupplementInfoService salesContractSupplementInfoService;
    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private ICSalesContractSupplementBasicHisInfoService salesContractSupplementBasicHisInfoService;
    @Autowired
    private ISalesContractSupplementGoodsInfoHistoryService salesContractSupplementGoodsInfoHistoryService;
    @Autowired
    private UserService userService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAdd(CSalesContractSupplementBasicInfo supplementBasicInfo) {

        ThreadLocalUtil.setUser(userService.getByLoginName("admin"));
        if (CollectionUtil.isEmpty(supplementBasicInfo.getFileIds())) {
            throw new BusinessException(CodeUtil.FAIL, "合同文件不能为空！");
        }

        CSalesContract salesContract = salesContractService.lambdaQuery()
                .eq(CSalesContract::getId, supplementBasicInfo.getcSalesContractManagementId())
                .one();
        if (supplementBasicInfo.getId() == null) {

            CSalesContractSupplementInfo supplementInfo = salesContractSupplementInfoService.lambdaQuery().eq(CSalesContractSupplementInfo::getcSalesContractManagementId, salesContract.getId())
                    .orderByDesc(CSalesContractSupplementInfo::getGmtCreate).last("limit 1").one();
            supplementBasicInfo.setcSalesContractSupplementInfoId(supplementInfo.getId());
            save(supplementBasicInfo);
        } else {
            updateById(supplementBasicInfo);
            //删除不需要的文件
            fileService.lambdaUpdate().eq(FileStorageDO::getBusinessId, supplementBasicInfo.getId())
                    .eq(FileStorageDO::getBusinessType, FileModuleDict.ChildEnum.SALES_CONTRACT_SUPPLEMENT_CONTRACT_FILE.getCode())
                    .set(FileStorageDO::getBusinessId, null);
            //删除货物信息
            supplementGoodsInfoService.remove(new QueryWrapper<SalesContractSupplementGoodsInfo>()
                    .eq("c_sales_contract_supplement_basic_info_id", supplementBasicInfo.getId()));
        }


        //合同文件id
        List<Long> fileIds = supplementBasicInfo.getFileIds();
        fileIds.forEach(c -> {
            FileStorageDO fileStorageDO = fileService.getById(c);
            fileStorageDO.setBusinessId(supplementBasicInfo.getId());
            fileService.updateById(fileStorageDO);
        });


        if (supplementBasicInfo.getAddGoods() == 1) {

            if (CollectionUtil.isEmpty(supplementBasicInfo.getSupplementGoodsInfos())) {
                throw new BusinessException(CodeUtil.FAIL, "货物信息不能为空！");
            }

            supplementBasicInfo.getSupplementGoodsInfos().forEach(goods -> {
                goods.setcSalesContractSupplementBasicInfoId(supplementBasicInfo.getId());
                goods.setOccupy(0);
                String salesPrice = StringUtil.formatStrT(goods.getSalesPrice());
                goods.setSalesPrice(salesPrice);
                supplementGoodsInfoService.save(goods);
            });
        }

        //流程处理
        Long hisId = addHistory(supplementBasicInfo);

        BusinessProcessingLog lastLog = businessProcessingLogService
                .getByBusinessTypeBusinessKey(ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS, supplementBasicInfo.getcSalesContractManagementId());


        //走变更流程
        String processKey = ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS;
        String assigneeKey = ConstantUtil.SALES_SUPPLEMENT_APPROVAL + ConstantUtil._CANDIDATE;

        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.OPERATION_SPECIALIST + "角色内无任何用户！");
        }
        String legalIds = legalSpecialists.stream().map(c -> c.toString()).collect(Collectors.joining(","));


        Map<String, Object> procVariables = new HashMap<>(1);
        procVariables.put(assigneeKey, legalIds);
        ProjectInformation projectInformation = projectInformationService
                .getOne(new QueryWrapper<ProjectInformation>()
                        .eq("business_number", salesContract.getBusinessNumber()));
        Map<String, Object> msgVariables = new HashMap<>(2);
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, projectInformation.getProjectName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为" + salesContract.getBusinessNumber() + "”的项目已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(processKey) + "—formBusiness”阶段，");

        Boolean success = flowableService.completeMyTask(lastLog.getHistoricTaskId(), salesContract, procVariables, null, hisId,
                msgVariables, processKey, legalSpecialists);
        if (success == null || !success) {
            throw new ValidatorException(CodeUtil.FAIL, "销售合同变更-录入时出错啦！");
        }

    }

    @Override
    public CSalesContractSupplementBasicHisInfo getView(Long id) {

        CSalesContractSupplementBasicHisInfo his = salesContractSupplementBasicHisInfoService.getById(id);

        List<FileStorageDO> files = fileService.findByBusinessId(id, FileModuleDict.ChildEnum.SALES_CONTRACT_SUPPLEMENT_HIS_FILE.getCode());
        his.setFiles(files);

        List<SalesContractSupplementGoodsInfoHistory> goodsInfoHistories = salesContractSupplementGoodsInfoHistoryService
                .lambdaQuery().eq(SalesContractSupplementGoodsInfoHistory::getSalesContractSupplementBasicHisInfoId, id).list();
        his.setGoodsInfoHistoryList(goodsInfoHistories);

        return his;
    }


    private Long addHistory(CSalesContractSupplementBasicInfo supplementBasicInfo) {

        CSalesContractSupplementBasicHisInfo his = new CSalesContractSupplementBasicHisInfo();
        BeanUtils.copyProperties(supplementBasicInfo, his, "id");
        salesContractSupplementBasicHisInfoService.save(his);
        List<Long> fileIds = supplementBasicInfo.getFileIds();
        List<FileStorageDO> fileStorageDOS = fileService.listByIds(fileIds);
        if (CollectionUtil.isNotEmpty(fileStorageDOS)) {
            fileStorageDOS.forEach(fileStorageDO -> {
                FileStorageDO hisFile = new FileStorageDO();
                BeanUtils.copyProperties(fileStorageDO, hisFile, "id");
                hisFile.setBusinessId(his.getId());
                hisFile.setBusinessType(FileModuleDict.ChildEnum.SALES_CONTRACT_SUPPLEMENT_HIS_FILE.getCode());
                fileService.save(hisFile);
            });
        }

        if (supplementBasicInfo.getAddGoods() == 1) {
            supplementBasicInfo.getSupplementGoodsInfos().forEach(goods -> {
                SalesContractSupplementGoodsInfoHistory goodsInfoHistory = new SalesContractSupplementGoodsInfoHistory();
                BeanUtils.copyProperties(goods, goodsInfoHistory, "id");
                goodsInfoHistory.setSalesContractSupplementBasicHisInfoId(his.getId());
                salesContractSupplementGoodsInfoHistoryService.save(goodsInfoHistory);
            });
        }

        return his.getId();

    }
}
