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

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.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.salescontractmanagement.*;
import com.sunxung.factoring.entity.salescontractmanagement.vo.SalesContractFirstTemplateConditionVo;
import com.sunxung.factoring.mapper.salescontractmanagement.SalesContractTemplateFirstApprovalInfoMapper;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.salescontractmanagement.*;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.flowable.engine.RuntimeService;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售合同-模板初审表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-12-08
 */
@Service("template_first_approvalService")
public class SalesContractTemplateFirstApprovalInfoServiceImpl extends ServiceImpl<SalesContractTemplateFirstApprovalInfoMapper,
        SalesContractTemplateFirstApprovalInfo> implements ISalesContractTemplateFirstApprovalInfoService {

    @Autowired
    private ISalesContractApprovalConditionDicService salesContractApprovalConditionDicService;
    @Autowired
    private ISalesContractTemplateFirstApprovalCommentInfoService salesContractTemplateFirstApprovalCommentInfoService;
    @Autowired
    private ISalesContractTemplateFirstApprovalConditionRelService templateFirstApprovalConditionRelService;
    @Autowired
    private UserService userService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public List<SalesContractFirstTemplateConditionVo> approval() {

//        runtimeService.deleteProcessInstance("197501","212");

        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
    @Transactional(rollbackFor = Exception.class)
    public void doApproval(SalesContractTemplateFirstApprovalInfo firstApprovalInfo) {

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

        //保存审核信息
        firstApprovalInfo.setUserCreate(ThreadLocalUtil.getUser().getLoginName());
        save(firstApprovalInfo);
        //保存审核意见
        firstApprovalInfo.getComments().forEach(comment -> {
            SalesContractTemplateFirstApprovalCommentInfo commentInfo = new SalesContractTemplateFirstApprovalCommentInfo();
            commentInfo.setApprovalComment(comment);
            commentInfo.setSalesContractTemplateFirstApprovalInfoId(firstApprovalInfo.getId());
            salesContractTemplateFirstApprovalCommentInfoService.save(commentInfo);
        });
        //保存审核条件
        approvalConditions.forEach(condition -> {
            SalesContractTemplateFirstApprovalConditionRel conditionRel = new SalesContractTemplateFirstApprovalConditionRel();
            conditionRel.setSalesContractApprovalConditionDicId(condition.getId());
            conditionRel.setSalesContractTemplateFirstApprovalInfoId(firstApprovalInfo.getId());
            conditionRel.setAgree(condition.getAgree());
            templateFirstApprovalConditionRelService.save(conditionRel);
        });

        //流程处理
        handleProcess(firstApprovalInfo);

        //驳回时释放项目
        if (ConstantConversionUtil.APPROVAL_RESULT_BACK.equals(firstApprovalInfo.getApprovalConclusion())){
            CSalesContract salesContract = salesContractService.getById(firstApprovalInfo.getcSalesContractManagementId());
            projectInformationService.lambdaUpdate().eq(ProjectInformation::getBusinessNumber,salesContract.getBusinessNumber())
                    .set(ProjectInformation::getSales,0).update();
        }
    }

    @Override
    public SalesContractTemplateFirstApprovalInfo getView(Long id) {

        SalesContractTemplateFirstApprovalInfo firstApprovalInfo = getById(id);
        List<SalesContractTemplateFirstApprovalCommentInfo> list = salesContractTemplateFirstApprovalCommentInfoService
                .list(new QueryWrapper<SalesContractTemplateFirstApprovalCommentInfo>().eq("sales_contract_template_first_approval_info_id", id));
        List<String> comments = list.stream().map(c -> c.getApprovalComment()).collect(Collectors.toList());
        //审批意见
        firstApprovalInfo.setComments(comments);
        //审核条件
        List<SalesContractFirstTemplateConditionVo> conditions = new ArrayList<>();
        List<SalesContractTemplateFirstApprovalConditionRel> conditionRels = templateFirstApprovalConditionRelService
                .list(new QueryWrapper<SalesContractTemplateFirstApprovalConditionRel>()
                        .eq("sales_contract_template_first_approval_info_id", id));
        conditionRels.forEach(rel -> {
            SalesContractApprovalConditionDic conditionDic = salesContractApprovalConditionDicService.getById(rel.getSalesContractApprovalConditionDicId());
            SalesContractFirstTemplateConditionVo conditionVo = new SalesContractFirstTemplateConditionVo();
            BeanUtil.copyProperties(conditionDic, conditionVo);
            conditionVo.setAgree(rel.getAgree());
            conditions.add(conditionVo);
        });
        firstApprovalInfo.setApprovalConditions(conditions);

        return firstApprovalInfo;
    }

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

        //最后一条审核条件选中触发模板审核，未选中无需复审
        List<SalesContractFirstTemplateConditionVo> approvalConditions = templateFirstApprovalInfo.getApprovalConditions();
        SalesContractFirstTemplateConditionVo lastCondition = approvalConditions.get(approvalConditions.size() - 1);

        //流程处理
        String processKey = ConstantUtil.SALES_CONTRACT;
        String conclusion = null;
        Map<String, Object> procVariables = new HashMap<>(2);
        Map<String, Object> msgVariables = new HashMap<>(2);
        //项目信息
        //查询基础信息
        CSalesContract salesContractManagement = salesContractService.getById(templateFirstApprovalInfo.getcSalesContractManagementId());
        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”阶段，");
        if (templateFirstApprovalInfo.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)){
            if (lastCondition.getAgree() == 0) {
                //模板复审
                conclusion = ConstantUtil.AGAIN_APPROVAL;

                // 法务专员 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());
                procVariables.put(ConstantUtil.TEMPLATE_AGAIN_APPROVAL + ConstantUtil._CANDIDATE, legalIds);
                procVariables.put("result", conclusion);

                Boolean success = flowableService.completeMyTask(templateFirstApprovalInfo.getTaskId(), salesContractManagement,
                        procVariables, null, templateFirstApprovalInfo.getId(),
                        msgVariables, processKey, legalSpecialists);
                if (success == null || !success) {
                    throw new ValidatorException(CodeUtil.FAIL, "销售合同-模板初审时出错啦！");
                }
            }else {
                //销售合同录入
                conclusion = ConstantUtil.DATA_ENTER;
                procVariables.put(ConstantUtil.SALES_CONTRACT_BASIC + ConstantUtil.ASSIGNEE, userService.getByLoginName("admin").getId());
                procVariables.put("result", conclusion);

                Boolean success = flowableService.completeMyTask(templateFirstApprovalInfo.getTaskId(), salesContractManagement,
                        procVariables, null, templateFirstApprovalInfo.getId(),
                        msgVariables, processKey, null);
                if (success == null || !success) {
                    throw new ValidatorException(CodeUtil.FAIL, "销售合同-模板初审时出错啦！");
                }
            }
        }else {
            conclusion = ConstantConversionUtil.processApprovalResult.get(templateFirstApprovalInfo.getApprovalConclusion());
            procVariables.put("result", conclusion);
            Boolean success = flowableService.completeMyTask(templateFirstApprovalInfo.getTaskId(), salesContractManagement,
                    procVariables, null, templateFirstApprovalInfo.getId(),
                    msgVariables, processKey, null);
            if (success == null || !success) {
                throw new ValidatorException(CodeUtil.FAIL, "销售合同-模板初审时出错啦！");
            }
        }






    }
}
