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

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.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.BiddingGuaranteeMethod;
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.entity.sys.FileStorageDO;
import com.sunxung.factoring.entity.sys.FileStorageDTO;
import com.sunxung.factoring.entity.sys.SysAttachmentRef;
import com.sunxung.factoring.mapper.biddingManagement.BiddingGuaranteeMethodMapper;
import com.sunxung.factoring.service.biddingManagement.IBiddingGuaranteeMethodService;
import com.sunxung.factoring.service.biddingManagement.ICBiddingBasicInfoService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.sys.FileService;
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.dto.AttachmentDto;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import org.apache.bcel.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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("guarantee_method_confirmService")
public class BiddingGuaranteeMethodServiceImpl extends ServiceImpl<BiddingGuaranteeMethodMapper, BiddingGuaranteeMethod> implements IBiddingGuaranteeMethodService {

    @Autowired
    private ICBiddingBasicInfoService cBiddingBasicInfoService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserService userService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(BiddingGuaranteeMethod biddingGuaranteeMethod) {
        //保存保证方式确认
        List<Long> accountantIds = userService.findUserIdByRole(ConstantUtil.ACCOUNTANT);
//                List<Long> accountantIds = userService.findUserIdByRole(ConstantUtil.FINANCE_STAFF);

        biddingGuaranteeMethod.setBusinessKey(biddingGuaranteeMethod.getBiddingBasicInfoId());
        save(biddingGuaranteeMethod);

        CBiddingBasicInfo biddingBasicInfo = cBiddingBasicInfoService.getById(biddingGuaranteeMethod.getBusinessKey());
        Map<String, Object> procVariables = new HashMap<>();
        switch (biddingGuaranteeMethod.getBidGuaranteeMethod()) {
            case 1:
                procVariables.put("result", ConstantUtil.GUARANTEE);
                biddingBasicInfo.setStage(BusinessStageDict.ChildEnum.EMPTY.getCode());
                biddingBasicInfo.setStatusCode(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
                cBiddingBasicInfoService.updateById(biddingBasicInfo);
                //处理保函文件
                if (CollectionUtil.isNotEmpty(biddingGuaranteeMethod.getGuaranteeLetterFileIds())) {
                    AttachmentDto guaranteeLetter = AttachmentDto.builder().setEntityId(biddingGuaranteeMethod.getId())
                            .setChildEnum(FileModuleDict.ChildEnum.BIDDING_GUARANTEE_LETTER_FILE).build();
                    sysAttachmentRefService.saveRef(biddingGuaranteeMethod.getGuaranteeLetterFileIds(),guaranteeLetter);
                }
                break;
            case 2:
                procVariables.put("result", ConstantUtil.OTHER);
                biddingBasicInfo.setStage(BusinessStageDict.ChildEnum.EMPTY.getCode());
                biddingBasicInfo.setStatusCode(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());
                cBiddingBasicInfoService.updateById(biddingBasicInfo);
                break;
            case 0:
                procVariables.put("result", ConstantUtil.BOND);
                biddingBasicInfo.setStage(BusinessStageDict.ChildEnum.BOND_COLLECTION.getCode());
                cBiddingBasicInfoService.updateById(biddingBasicInfo);
                //处理保函文件
                if (CollectionUtil.isNotEmpty(biddingGuaranteeMethod.getPaymentVoucherFileIds())){
                    AttachmentDto paymentVoucher = AttachmentDto.builder().setEntityId(biddingGuaranteeMethod.getId())
                            .setChildEnum(FileModuleDict.ChildEnum.BIDDING_PAYMENT_VOUCHER_FILE).build();
                    sysAttachmentRefService.saveRef(biddingGuaranteeMethod.getPaymentVoucherFileIds(),paymentVoucher);
                }
                // 保证金收款确认 执行人为财务
                String accountants = accountantIds.stream().map(c -> c.toString()).collect(Collectors.joining(","));
                procVariables.put(ConstantUtil.MARGIN_COLLECTION_CONFIRM_CANDIDATE, accountants);
                break;
            default:
                throw new ValidatorException(CodeUtil.FAIL, "保证方式不正确！");
        }

        //需求变更
        //投标说明字段取消
//        List<Long> bidDescriptionFileIds = biddingGuaranteeMethod.getBidDescriptionFileIds();
//
//        if (CollectionUtil.isEmpty(bidDescriptionFileIds)) {
//            throw new BusinessException(CodeUtil.FAIL,"投标说明文件不能为空！");
//        }
//        AttachmentDto upstreamPurchDto = AttachmentDto.builder().setEntityId(biddingGuaranteeMethod.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.BIDING_DESCRIPTION_FILE).build();
//        sysAttachmentRefService.saveRef(bidDescriptionFileIds,upstreamPurchDto);

        //完成审核流程流转到下一流程或者完成流程
        //查询项目
        BiddingBasicInfoResultVo basicInfoResultVo = cBiddingBasicInfoService.getCreditProjectByBiddingId(biddingBasicInfo.getId());
        Map<String, Object> msgVariables = new HashMap<>();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "业务编号为：" + basicInfoResultVo.getBusinessNumber());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为：" + basicInfoResultVo.getBusinessNumber() + "”的保证方式确认完成，进入“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.BIDDING_MANAGEMENT) + "—保证金收款确认”阶段，"
                        + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        flowableService.completeMyTask(biddingGuaranteeMethod.getTaskId(), biddingBasicInfo, procVariables, null,
                biddingGuaranteeMethod.getId(), msgVariables, ConstantUtil.BIDDING_MANAGEMENT,accountantIds);

    }

    @Override
    public BiddingGuaranteeMethod getView(Long formBusinessId) {
        //基础信息
        BiddingGuaranteeMethod biddingGuaranteeMethod = getById(formBusinessId);

        if (biddingGuaranteeMethod.getBidGuaranteeMethod().equals(1)){
            //保函文件
            AttachmentDto upstreamPurchDto = AttachmentDto.builder().setEntityId(biddingGuaranteeMethod.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.BIDDING_GUARANTEE_LETTER_FILE).build();
            List<FileStorage> files = sysAttachmentRefService.getFiles(upstreamPurchDto);
            biddingGuaranteeMethod.setGuaranteeLetterFiles(files);
        }else if (biddingGuaranteeMethod.getBidGuaranteeMethod().equals(0)){
            //支付凭证
            AttachmentDto upstreamPurchDto = AttachmentDto.builder().setEntityId(biddingGuaranteeMethod.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.BIDDING_PAYMENT_VOUCHER_FILE).build();
            List<FileStorage> files = sysAttachmentRefService.getFiles(upstreamPurchDto);
            biddingGuaranteeMethod.setPaymentVoucherFiles(files);
        }

        //投标说明
//        AttachmentDto upstreamPurchDto = AttachmentDto.builder().setEntityId(biddingGuaranteeMethod.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.BIDING_DESCRIPTION_FILE).build();
//        List<FileStorage> files = sysAttachmentRefService.getFiles(upstreamPurchDto);
//        biddingGuaranteeMethod.setBidDescriptionFiles(files);

        return biddingGuaranteeMethod;
    }
}
