package com.sunxung.factoring.service.salescontractmanagement;

import cn.hutool.core.bean.BeanUtil;
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.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.salescontractmanagement.*;
import com.sunxung.factoring.entity.salescontractmanagement.vo.SalesContractFirstTemplateConditionVo;
import com.sunxung.factoring.mapper.salescontractmanagement.SalesContractSupplementTemplateFirstApprovalInfoMapper;
import com.sunxung.factoring.service.project.IProjectInformationService;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售合同变更-模板初审表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2024-01-09
 */
@Service("supplement_template_first_approvalService")
public class SalesContractSupplementTemplateFirstApprovalInfoServiceImpl extends ServiceImpl<SalesContractSupplementTemplateFirstApprovalInfoMapper, SalesContractSupplementTemplateFirstApprovalInfo> implements ISalesContractSupplementTemplateFirstApprovalInfoService {

    @Autowired
    private ISalesContractApprovalConditionDicService salesContractApprovalConditionDicService;
    @Autowired
    private UserService userService;
    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private ISalesContractSupplementInfoService salesContractSupplementInfoService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private ISalesContractSupplementTemplateFirstApprovalCommentInfoService salesContractSupplementTemplateFirstApprovalCommentInfoService;
    @Autowired
    private ISalesContractSupplementTemplateFirstApprovalConditionRelService salesContractSupplementTemplateFirstApprovalConditionRelService;

    @Override
    public void doAdd(SalesContractSupplementTemplateFirstApprovalInfo firstApprovalInfo) {
        List<SalesContractFirstTemplateConditionVo> approvalConditions = firstApprovalInfo.getApprovalConditions();
        if (CollectionUtil.isEmpty(approvalConditions)) {
            throw new BusinessException(CodeUtil.FAIL, "审核条件不能为空！");
        }

        CSalesContractSupplementInfo supplementInfo = salesContractSupplementInfoService.lambdaQuery().eq(CSalesContractSupplementInfo::getcSalesContractManagementId, firstApprovalInfo.getBusinessKey())
                .orderByDesc(CSalesContractSupplementInfo::getGmtCreate).last("limit 1").one();


        //保存审核信息
        firstApprovalInfo.setUserCreate(ThreadLocalUtil.getUser().getLoginName());
        firstApprovalInfo.setcSalesContractSupplementInfoId(supplementInfo.getId());
        save(firstApprovalInfo);
        //保存审核意见
        firstApprovalInfo.getComments().forEach(comment -> {
            SalesContractSupplementTemplateFirstApprovalCommentInfo commentInfo = new SalesContractSupplementTemplateFirstApprovalCommentInfo();
            commentInfo.setApprovalComment(comment);
            commentInfo.setSalesContractSupplementTemplateFirstApprovalInfoId(firstApprovalInfo.getId());
            salesContractSupplementTemplateFirstApprovalCommentInfoService.save(commentInfo);
        });
        //保存审核条件
        approvalConditions.forEach(condition -> {
            SalesContractSupplementTemplateFirstApprovalConditionRel conditionRel = new SalesContractSupplementTemplateFirstApprovalConditionRel();
            conditionRel.setSalesContractApprovalConditionDicId(condition.getId());
            conditionRel.setSalesContractSupplementTemplateFirstApprovalInfoId(firstApprovalInfo.getId());
            conditionRel.setAgree(condition.getAgree());
            salesContractSupplementTemplateFirstApprovalConditionRelService.save(conditionRel);
        });

        //流程处理
        handleProcess(firstApprovalInfo);


    }

    @Override
    public List<SalesContractFirstTemplateConditionVo> add() {
        List<SalesContractFirstTemplateConditionVo> list = new ArrayList<>();
        //初始化审核条件
        List<SalesContractApprovalConditionDic> conditionDicList = salesContractApprovalConditionDicService.list();
        if (CollectionUtil.isNotEmpty(conditionDicList)) {
            conditionDicList.forEach(conditionDic -> {
                SalesContractFirstTemplateConditionVo conditionVo = new SalesContractFirstTemplateConditionVo();
                BeanUtil.copyProperties(conditionDic, conditionVo);
                conditionVo.setAgree(1);
                list.add(conditionVo);
            });
        }

        return list;
    }

    @Override
    public SalesContractSupplementTemplateFirstApprovalInfo getView(Long id) {

        SalesContractSupplementTemplateFirstApprovalInfo templateFirstApprovalInfo = getById(id);

        List<SalesContractSupplementTemplateFirstApprovalCommentInfo> list = salesContractSupplementTemplateFirstApprovalCommentInfoService.lambdaQuery()
                .eq(SalesContractSupplementTemplateFirstApprovalCommentInfo::getSalesContractSupplementTemplateFirstApprovalInfoId, id).list();
        if (CollectionUtil.isNotEmpty(list)){
            List<String> comments = list.stream().map(c -> c.getApprovalComment()).collect(Collectors.toList());
            templateFirstApprovalInfo.setComments(comments);
        }

        List<SalesContractSupplementTemplateFirstApprovalConditionRel> conditionRelList = salesContractSupplementTemplateFirstApprovalConditionRelService
                .lambdaQuery()
                .eq(SalesContractSupplementTemplateFirstApprovalConditionRel::getSalesContractSupplementTemplateFirstApprovalInfoId, id).list();
        List<SalesContractFirstTemplateConditionVo> conditionVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(conditionRelList)){
            conditionRelList.forEach(c->{
                SalesContractApprovalConditionDic contractApprovalConditionDic = salesContractApprovalConditionDicService.getById(c.getSalesContractApprovalConditionDicId());
                SalesContractFirstTemplateConditionVo templateConditionVo = new SalesContractFirstTemplateConditionVo();
                BeanUtils.copyProperties(contractApprovalConditionDic,templateConditionVo);
                templateConditionVo.setAgree(c.getAgree());
                conditionVoList.add(templateConditionVo);
            });
        }
        templateFirstApprovalInfo.setApprovalConditions(conditionVoList);


        return templateFirstApprovalInfo;
    }

    //处理流程
    private void handleProcess(SalesContractSupplementTemplateFirstApprovalInfo templateFirstApprovalInfo) {

        //查询基础信息
        CSalesContract salesContractManagement = salesContractService.getById(templateFirstApprovalInfo.getBusinessKey());
        CSalesContractSupplementInfo supplementInfo = salesContractSupplementInfoService.getById(templateFirstApprovalInfo.getcSalesContractSupplementInfoId());
        //最后一条审核条件选中触发模板审核，未选中无需复审
        List<SalesContractFirstTemplateConditionVo> approvalConditions = templateFirstApprovalInfo.getApprovalConditions();
        SalesContractFirstTemplateConditionVo lastCondition = approvalConditions.get(approvalConditions.size() - 1);

        Map<String, Object> procVariables = new HashMap<>(2);
        // 法务专员 todo 法务经理
        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.LEGAL_SPECIALIST + "角色内无任何用户！");
        }
        List<String> legalIds = legalSpecialists.stream().map(c -> c.toString()).collect(Collectors.toList());

        //经办人变更时直接通过，合同内容变更时走后续流程
        String conclusion;
        if (templateFirstApprovalInfo.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
            if (supplementInfo.getChangeType() == 1) {
                conclusion = "经办人变更";
                salesContractManagement.setContractStatus(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
                salesContractService.updateById(salesContractManagement);
            } else {
                if (lastCondition.getAgree() == 0) {
                    //变更复审
                    conclusion = ConstantUtil.SUPPLEMENT_AGAIN_APPROVAL;
                    procVariables.put(ConstantUtil.SUPPLEMENT_TEMPLATE_AGAIN_APPROVAL + ConstantUtil._CANDIDATE, legalIds);
                } else {
                    //销售合同录入
                    conclusion = ConstantUtil.DATA_ENTER;
                    procVariables.put(ConstantUtil.SALES_SUPPLEMENT_BASIC + ConstantUtil.ASSIGNEE, userService.getByLoginName("admin").getId());
                }
            }

        } else {
            conclusion = ConstantConversionUtil.processApprovalResult.get(templateFirstApprovalInfo.getApprovalConclusion());
        }
        procVariables.put("result", conclusion);

        //流程处理
        String processKey = ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS;
        Map<String, Object> msgVariables = new HashMap<>(2);
        //项目信息
        ProjectInformation projectInformation = projectInformationService
                .getOne(new QueryWrapper<ProjectInformation>()
                        .eq("business_number", salesContractManagement.getBusinessNumber()));
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, projectInformation.getProjectName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为" + salesContractManagement.getBusinessNumber() + "”的项目已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(processKey) + "—formBusiness”阶段，");
        Boolean success = flowableService.completeMyTask(templateFirstApprovalInfo.getTaskId(), salesContractManagement,
                procVariables, null, templateFirstApprovalInfo.getId(),
                msgVariables, processKey, legalSpecialists);
        if (success == null || !success) {
            throw new ValidatorException(CodeUtil.FAIL, "销售合同变更-模板初审时出错啦！");
        }
    }

}
