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

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.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.acceptance.*;
import com.sunxung.factoring.entity.customerinformation.ElectronicSignaturePersonal;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.mapper.acceptancesheet.AcceptanceSignConfirmationMapper;
import com.sunxung.factoring.service.acceptancesheet.*;
import com.sunxung.factoring.service.customerinformation.IElectronicSignaturePersonalService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.steelwaiter.ISellBillItemService;
import com.sunxung.factoring.service.steelwaiter.ISellBillService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * --验收单签署确认表 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-06-07
 */
@Service("acceptance_sign_confirmService")
public class AcceptanceSignConfirmationServiceImpl extends ServiceImpl<AcceptanceSignConfirmationMapper, AcceptanceSignConfirmation>
        implements IAcceptanceSignConfirmationService {

    @Autowired
    private IAcceptanceSignConfirmationElectronicInfoService acceptanceSignConfirmationElectronicInfoService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Autowired
    private AcceptanceBasicInfoService acceptanceBasicInfoService;

    @Autowired
    private IAcceptancePersonInfoService acceptancePersonInfoService;

    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private AcceptanceGoodsInfoService acceptanceGoodsInfoService;

    @Autowired
    private BusinessAssigneeService assigneeService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private UserService userService;

    @Autowired
    private IAcceptanceSignConfirmationGoodsInfoService acceptanceSignConfirmationGoodsInfoService;

    @Autowired
    private IAcceptanceSignConfirmationHistoryService acceptanceSignConfirmationHistoryService;

    @Autowired
    private IAcceptanceSignConfirmationElectronicInfoHistoryService acceptanceSignConfirmationElectronicInfoHistoryService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private ISellBillItemService sellBillItemService;

    @Autowired
    private ISellBillService sellBillService;


    private Long addHistory(AcceptanceSignConfirmation acceptanceSignConfirmation) {
        acceptanceSignConfirmation = getById(acceptanceSignConfirmation.getId());
        AcceptanceSignConfirmationHistory acceptanceSignConfirmationHistory = new AcceptanceSignConfirmationHistory();
        BeanUtils.copyProperties(acceptanceSignConfirmation, acceptanceSignConfirmationHistory, "id");
        acceptanceSignConfirmationHistoryService.save(acceptanceSignConfirmationHistory);
        List<AcceptanceSignConfirmationElectronicInfo> acceptanceSignConfirmationElectronicInfos = acceptanceSignConfirmationElectronicInfoService.lambdaQuery().eq(AcceptanceSignConfirmationElectronicInfo::getAcceptanceSignConfirmationId, acceptanceSignConfirmation.getId()).list();
        for (AcceptanceSignConfirmationElectronicInfo acceptanceSignConfirmationElectronicInfo : acceptanceSignConfirmationElectronicInfos) {
            AcceptanceSignConfirmationElectronicInfoHistory acceptanceSignConfirmationElectronicInfoHistory = new AcceptanceSignConfirmationElectronicInfoHistory();
            BeanUtils.copyProperties(acceptanceSignConfirmationElectronicInfo, acceptanceSignConfirmationElectronicInfoHistory, "id");
            acceptanceSignConfirmationElectronicInfoHistory.setAcceptanceSignConfirmationId(acceptanceSignConfirmationHistory.getId());
            acceptanceSignConfirmationElectronicInfoHistoryService.save(acceptanceSignConfirmationElectronicInfoHistory);
        }
        return acceptanceSignConfirmationHistory.getId();
    }

    @Override
    public AcceptanceSignConfirmationHistory getView(Long id) {
        AcceptanceSignConfirmationHistory acceptanceSignConfirmationHistory = acceptanceSignConfirmationHistoryService.getById(id);
        //List<AcceptanceSignConfirmationGoodsInfo> acceptanceSignConfirmationGoodsInfos = acceptanceSignConfirmationGoodsInfoService.lambdaQuery().eq(AcceptanceSignConfirmationGoodsInfo::getAcceptanceSignConfirmationId, id).list();
        List<AcceptanceSignConfirmationElectronicInfoHistory> acceptanceSignConfirmationElectronicInfoHistories = acceptanceSignConfirmationElectronicInfoHistoryService.lambdaQuery().eq(AcceptanceSignConfirmationElectronicInfoHistory::getAcceptanceSignConfirmationId, id).list();
        //acceptanceSignConfirmationHistory.setAcceptanceSignConfirmationGoodsInfos(acceptanceSignConfirmationGoodsInfos);
        acceptanceSignConfirmationHistory.setAcceptanceSignConfirmationElectronicInfoHistories(acceptanceSignConfirmationElectronicInfoHistories);
        Long electronicSignaturePersonalId = acceptanceSignConfirmationElectronicInfoHistories.get(0).getElectronicSignaturePersonalId();
        ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getById(electronicSignaturePersonalId);
        acceptanceSignConfirmationHistory.setElectronicSignaturePersonal(electronicSignaturePersonal);
        return acceptanceSignConfirmationHistory;
    }

    /**
     *  第一个节点 处理过程
     * @param acceptanceSignConfirmation
     * @return
     */
    @Override
    public ResponseJson handleProcess(AcceptanceSignConfirmation acceptanceSignConfirmation) {

        if (acceptanceSignConfirmation != null) {
            AcceptanceBasicInfo acceptanceBasicInfo = acceptanceBasicInfoService.getById(acceptanceSignConfirmation.getBusinessKey());

            //保存历史签署确认
            Long historyId = addHistory(acceptanceSignConfirmation);
            //保存货物历史-签署确认不会修改货物信息 所以不需要保存历史货物信息
//            List<AcceptanceGoodsInfo> acceptanceGoodInfos = acceptanceSignConfirmation.getAcceptanceGoodInfos();
//            if(CollectionUtil.isNotEmpty(acceptanceGoodInfos)){
//                for (AcceptanceGoodsInfo acceptanceBusinessGood : acceptanceGoodInfos) {
//                    AcceptanceSignConfirmationGoodsInfo acceptanceSignConfirmationGoodsInfo = new AcceptanceSignConfirmationGoodsInfo();
//                    BeanUtils.copyProperties(acceptanceBusinessGood, acceptanceSignConfirmationGoodsInfo,"id");
//                    acceptanceSignConfirmationGoodsInfo.setAcceptanceSignConfirmationId(historyId);
//                    acceptanceSignConfirmationGoodsInfoService.save(acceptanceSignConfirmationGoodsInfo);
//                }
//            }

            //处理流程
            String result;
            String taskId = acceptanceSignConfirmation.getTaskId();
            Map<String, Object> procVariables = new HashMap<>();
            Map<String, Object> msgVariables = new HashMap<>();
            List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
            String legalSpecials = legalSpecialists.stream().map(c -> c.toString()).collect(Collectors.joining(","));

            Task task = flowableService.getByTaskQuery(acceptanceSignConfirmation.getTaskId());
            User u = new User();
            u.setId(Long.parseLong(task.getAssignee()));
            ThreadLocalUtil.setUser(u);

            if (acceptanceSignConfirmation.getSignConclusion() == 0) {
                acceptanceBasicInfo.setAcceptanceStatus(ProjectInitiationStatusDict.ChildEnum.TERMINATED.getCode());
                acceptanceBasicInfoService.updateById(acceptanceBasicInfo);
                result = "终止";
                msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "验收单编号：" + acceptanceBasicInfo.getAcceptanceNumber());
                msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                        "验收单编号为“" + acceptanceBasicInfo.getAcceptanceNumber() + "”的验收单已终止“"
                                + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
                flowableService.completeMyTask(taskId, acceptanceBasicInfo, procVariables, result, historyId, msgVariables, ConstantUtil.ACCEPTANCE_SHEET);
            } else if (acceptanceSignConfirmation.getSignConclusion() == 1) {
                procVariables.put(ConstantUtil.ACCEPTANCE_SHEET_APPROVAL_CANDIDATE, legalSpecials);
                result = "完成";
                msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "验收单编号：" + acceptanceBasicInfo.getAcceptanceNumber());
                msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                        "验收单编号为“" + acceptanceBasicInfo.getAcceptanceNumber() + "”的验收单已进入“"
                                + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.ACCEPTANCE_SHEET) + "—法务审核阶段，"
                                + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
                flowableService.completeMyTask(taskId, acceptanceBasicInfo, procVariables, result, historyId, msgVariables, ConstantUtil.ACCEPTANCE_SHEET,legalSpecialists);

            }else if (acceptanceSignConfirmation.getSignConclusion() == 2) {
                acceptanceSignConfirmationElectronicInfoService.lambdaUpdate().eq(AcceptanceSignConfirmationElectronicInfo::getAcceptanceSignConfirmationId, acceptanceSignConfirmation.getId()).remove();
                lambdaUpdate().eq(AcceptanceSignConfirmation::getAcceptanceBasicInfoId, acceptanceSignConfirmation.getBusinessKey()).remove();
                result = "驳回";
//                msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "验收单编号：" + acceptanceBasicInfo.getAcceptanceNumber());
//                msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
//                        "验收单编号为“" + acceptanceBasicInfo.getAcceptanceNumber() + "”的验收单已退回，进入“"
//                                + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.ACCEPTANCE_SHEET) + "—录入验收单阶段，"
//                                + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);

                flowableService.completeMyTask(taskId, acceptanceBasicInfo, procVariables, result, historyId, msgVariables, ConstantUtil.ACCEPTANCE_SHEET);
            } else {
                throw new ValidatorException(CodeUtil.FAIL, "签署结论有误！");
            }


        } else {
            return new ResponseJson("签署信息不能为空！");
        }
        return null;
    }

}
