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.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.sys.User;
import com.sunxung.factoring.mapper.salescontractmanagement.SalesContractSupplementTemplateApprovalMapper;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
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.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-08
 */
@Service("supplement_template_again_approvalService")
public class SalesContractSupplementTemplateApprovalServiceImpl extends ServiceImpl<SalesContractSupplementTemplateApprovalMapper,
        SalesContractSupplementTemplateApproval> implements ISalesContractSupplementTemplateApprovalService {

    @Autowired
    private ICSalesContractSupplementInfoService salesContractSupplementInfoService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private SalesContractService salesContractService;
    @Autowired
    private UserService userService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private ISalesContractSupplementTemplateApprovalCommentInfoService salesContractSupplementTemplateApprovalCommentInfoService;


    @Override
    public void doApproval(SalesContractSupplementTemplateApproval supplementTemplateApproval) {

        CSalesContract contractManagement = salesContractService.getById(supplementTemplateApproval.getcSalesContractManagementId());
        //销售合同变更信息表

        CSalesContractSupplementInfo contractSupplementInfo = salesContractSupplementInfoService
                .lambdaQuery().eq(CSalesContractSupplementInfo::getcSalesContractManagementId, contractManagement.getId())
                .orderByDesc(CSalesContractSupplementInfo::getGmtCreate).last("limit 1").one();

        if (CollectionUtil.isNotEmpty(supplementTemplateApproval.getComments())){
            supplementTemplateApproval.getComments().forEach(c->{
                SalesContractSupplementTemplateApprovalCommentInfo approvalCommentInfo = new SalesContractSupplementTemplateApprovalCommentInfo();
                approvalCommentInfo.setApprovalComment(c);
                approvalCommentInfo.setSalesContractSupplementTemplateApprovalId(supplementTemplateApproval.getId());
                salesContractSupplementTemplateApprovalCommentInfoService.save(approvalCommentInfo);
            });
        }

        supplementTemplateApproval.setAuditorId(ThreadLocalUtil.getUserId());
        supplementTemplateApproval.setcSalesContractSupplementInfoId(contractSupplementInfo.getId());
        save(supplementTemplateApproval);


        //流程处理
        String processKey = ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS;
        Map<String, Object> procVariables = new HashMap<>(1);
        User admin = userService.getByLoginName("admin");
        procVariables.put(ConstantUtil.SALES_SUPPLEMENT_BASIC + ConstantUtil.ASSIGNEE, admin.getId());
        Map<String, Object> msgVariables = new HashMap<>(2);
        //项目信息
        ProjectInformation projectInformation = projectInformationService
                .getOne(new QueryWrapper<ProjectInformation>()
                        .eq("business_number", contractManagement.getBusinessNumber()));
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, projectInformation.getProjectName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为" + contractManagement.getBusinessNumber() + "”的项目已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(processKey) + "—formBusiness”阶段，");

        Boolean success = flowableService.completeMyTask(supplementTemplateApproval.getTaskId(), contractManagement, procVariables,
                ConstantConversionUtil.processApprovalResult.get(supplementTemplateApproval.getApprovalConclusion()),
                supplementTemplateApproval.getId(), msgVariables, processKey);
        if (success == null || !success) {
            throw new ValidatorException(CodeUtil.FAIL, "销售合同变更-创建时出错啦！");
        }

    }

    @Override
    public SalesContractSupplementTemplateApproval getView(Long id) {

        SalesContractSupplementTemplateApproval supplementTemplateApproval = getById(id);
        List<SalesContractSupplementTemplateApprovalCommentInfo> list = salesContractSupplementTemplateApprovalCommentInfoService
                .lambdaQuery().eq(SalesContractSupplementTemplateApprovalCommentInfo::getSalesContractSupplementTemplateApprovalId, id).list();
        if (CollectionUtil.isNotEmpty(list)){
            List<String> comments = list.stream().map(c -> c.getApprovalComment()).collect(Collectors.toList());
            supplementTemplateApproval.setComments(comments);
        }

        return supplementTemplateApproval;
    }
}
