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

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.dict.impl.BusinessStageDict;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.biddingManagement.BiddingAwardConfirm;
import com.sunxung.factoring.entity.biddingManagement.CBiddingBasicInfo;
import com.sunxung.factoring.entity.biddingManagement.vo.BiddingBasicInfoResultVo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.biddingManagement.BiddingAwardConfirmMapper;
import com.sunxung.factoring.service.biddingManagement.IBiddingAwardConfirmService;
import com.sunxung.factoring.service.biddingManagement.ICBiddingBasicInfoService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.supplier.ISupplierInfoService;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
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-11-21
 */
@Service("award_confirmService")
public class BiddingAwardConfirmServiceImpl extends ServiceImpl<BiddingAwardConfirmMapper, BiddingAwardConfirm> implements
        IBiddingAwardConfirmService {

    @Autowired
    private ICBiddingBasicInfoService biddingBasicInfoService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private FileService fileService;
    @Resource(name = "supplierInfoService")
    private ISupplierInfoService supplierInfoService;
    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;
    @Autowired
    private UserService userService;
    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(BiddingAwardConfirm biddingAwardConfirm) {
        //基础信息
        biddingAwardConfirm.setBusinessKey(biddingAwardConfirm.getBiddingBasicInfoId());
        save(biddingAwardConfirm);

        CBiddingBasicInfo biddingBasicInfo = biddingBasicInfoService.getById(biddingAwardConfirm.getBusinessKey());
        Map<String, Object> procVariables = new HashMap<>();
        switch (biddingAwardConfirm.getWinTheBidding()) {
            case 1:
                procVariables.put("result", ConstantUtil.AWARD);
                biddingBasicInfo.setStage(BusinessStageDict.ChildEnum.EMPTY.getCode());
                biddingBasicInfo.setStatusCode(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
                biddingBasicInfoService.updateById(biddingBasicInfo);
                //中标通知书
                if (CollectionUtil.isNotEmpty(biddingAwardConfirm.getAwardNotificationFileIds())) {
                    AttachmentDto guaranteeLetter = AttachmentDto.builder().setEntityId(biddingAwardConfirm.getId())
                            .setChildEnum(FileModuleDict.ChildEnum.BIDDING_AWARD_NOTIFICATION_FILE).build();
                    sysAttachmentRefService.saveRef(biddingAwardConfirm.getAwardNotificationFileIds(), guaranteeLetter);
                }

                break;
            case 0:
                procVariables.put("result", ConstantUtil.NOT_AWARD);
                biddingBasicInfo.setStage(BusinessStageDict.ChildEnum.REFUND_DEPOSIT.getCode());
                biddingBasicInfoService.updateById(biddingBasicInfo);
                break;
            default:
                throw new ValidatorException(CodeUtil.FAIL, "是否中标不明确！");

        }
        //保证金退款确认操作岗
        //获取财务 todo
        List<Long> finanIdLists = userService.findUserIdByRole(ConstantUtil.ACCOUNTANT);
        String finanLists = finanIdLists.stream().map(c -> c.toString()).collect(Collectors.joining(","));

        procVariables.put(ConstantUtil.REFUND_DEPOSIT_CONFIRM_ASSIGNEE, new Long(44));
        //完成审核流程流转到下一流程或者完成流程
        //查找项目
        BiddingBasicInfoResultVo basicInfoResultVo = biddingBasicInfoService.getCreditProjectByBiddingId(biddingBasicInfo.getId());
        Map<String, Object> msgVariables = new HashMap<>();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "业务编号为：" + basicInfoResultVo.getBusinessNumber());
        if (biddingAwardConfirm.getWinTheBidding().equals(1)) {
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "业务编号为：" + basicInfoResultVo.getBusinessNumber() + "”的业务中标确认已完成，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
            flowableService.completeMyTask(biddingAwardConfirm.getTaskId(), biddingBasicInfo, procVariables, null,
                    biddingAwardConfirm.getId(), msgVariables, ConstantUtil.BIDDING_MANAGEMENT);
        } else if (biddingAwardConfirm.getWinTheBidding().equals(0)) {
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "业务编号为：" + basicInfoResultVo.getBusinessNumber() + "”的业务中标确认已完成，进入“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.BIDDING_MANAGEMENT) + "—保证金退款确认”阶段，"
                            + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
            flowableService.completeMyTask(biddingAwardConfirm.getTaskId(), biddingBasicInfo, procVariables, null,
                    biddingAwardConfirm.getId(), msgVariables, ConstantUtil.BIDDING_MANAGEMENT, finanIdLists);
        }

    }

    @Override
    public BiddingAwardConfirm getView(Long formBusinessId) {
        BiddingAwardConfirm awardConfirm = getById(formBusinessId);
        if (awardConfirm.getWinTheBidding().equals(1)) {
            //中标通知书
            AttachmentDto upstreamPurchDto = AttachmentDto.builder().setEntityId(formBusinessId)
                    .setChildEnum(FileModuleDict.ChildEnum.BIDDING_AWARD_NOTIFICATION_FILE).build();
            List<FileStorage> files = sysAttachmentRefService.getFiles(upstreamPurchDto);
            awardConfirm.setAwardNotificationFiles(files);
        }
        return awardConfirm;
    }
}
