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.CodeUtil;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ConstantConversionUtil;
import com.sunxung.factoring.component.util.ConstantUtil;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContract;
import com.sunxung.factoring.entity.salescontractmanagement.SalesContractTemplateAgainApprovalCommentInfo;
import com.sunxung.factoring.entity.salescontractmanagement.SalesContractTemplateAgainApprovalInfo;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.mapper.salescontractmanagement.SalesContractTemplateAgainApprovalInfoMapper;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.salescontractmanagement.ISalesContractTemplateAgainApprovalCommentInfoService;
import com.sunxung.factoring.service.salescontractmanagement.ISalesContractTemplateAgainApprovalInfoService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
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 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-08
 */
@Service("template_again_approvalService")
public class SalesContractTemplateAgainApprovalInfoServiceImpl extends ServiceImpl<SalesContractTemplateAgainApprovalInfoMapper, SalesContractTemplateAgainApprovalInfo> implements ISalesContractTemplateAgainApprovalInfoService {

    @Autowired
    private ISalesContractTemplateAgainApprovalCommentInfoService salesContractTemplateAgainApprovalCommentInfoService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private UserService userService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private SalesContractService salesContractService;

    @Override
    public SalesContractTemplateAgainApprovalInfo getView(Long id) {

        SalesContractTemplateAgainApprovalInfo againApprovalInfo = getById(id);
        //审批意见
        List<SalesContractTemplateAgainApprovalCommentInfo> againApprovalCommentInfos = salesContractTemplateAgainApprovalCommentInfoService
                .list(new QueryWrapper<SalesContractTemplateAgainApprovalCommentInfo>().eq("sales_contract_template_again_approval_info_id", id));
        List<String> comments = againApprovalCommentInfos.stream().map(c -> c.getApprovalComment()).collect(Collectors.toList());
        againApprovalInfo.setComments(comments);
        return againApprovalInfo;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(SalesContractTemplateAgainApprovalInfo againApprovalInfo) {

        if (againApprovalInfo.getApprovalConclusion().equals("back") && CollectionUtil.isEmpty(againApprovalInfo.getComments())) {
            //退回时
            throw new ValidatorException(CodeUtil.FAIL, "审批意见不能为空！");
        }
        //保存审批信息
        save(againApprovalInfo);

        CSalesContract salesContract = salesContractService.getById(againApprovalInfo.getcSalesContractManagementId());

        againApprovalInfo.getComments().forEach(c -> {

            SalesContractTemplateAgainApprovalCommentInfo commentInfo = new SalesContractTemplateAgainApprovalCommentInfo();
            commentInfo.setApprovalComment(c);
            commentInfo.setSalesContractTemplateAgainApprovalInfoId(againApprovalInfo.getId());
            salesContractTemplateAgainApprovalCommentInfoService.save(commentInfo);

        });

        handleProcess(againApprovalInfo);

        //驳回时释放占用的项目
        if (againApprovalInfo.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
            projectInformationService.lambdaUpdate().eq(ProjectInformation::getBusinessNumber, salesContract.getBusinessNumber())
                    .set(ProjectInformation::getSales, 0).update();

        }


    }

    //流程处理
    private void handleProcess(SalesContractTemplateAgainApprovalInfo againApprovalInfo) {

        // c端供应商
        User admin = userService.getByLoginName("admin");

        //查询基础信息
        CSalesContract salesContractManagement = salesContractService.getById(againApprovalInfo.getcSalesContractManagementId());

        //流程处理
        String processKey = ConstantUtil.SALES_CONTRACT;

        Map<String, Object> procVariables = new HashMap<>(2);
        procVariables.put(ConstantUtil.SALES_CONTRACT_BASIC + ConstantUtil.ASSIGNEE, admin.getId());
        procVariables.put("result", ConstantConversionUtil.processApprovalResult.get(againApprovalInfo.getApprovalConclusion()));

        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(againApprovalInfo.getTaskId(), salesContractManagement,
                procVariables, null, againApprovalInfo.getId(),
                msgVariables, processKey);
        if (success == null || !success) {
            throw new ValidatorException(CodeUtil.FAIL, "销售合同-模板复审时出错啦！");
        }
    }
}
