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.*;
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.BiddingBasicInfoHis;
import com.sunxung.factoring.entity.biddingManagement.CBiddingBasicInfo;
import com.sunxung.factoring.entity.biddingManagement.vo.BiddingBasicInfoResultVo;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.vo.BusinessProcessingTaskVo;
import com.sunxung.factoring.entity.project.vo.SearchBusinessProcessingTask;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorageDO;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.mapper.biddingManagement.CBiddingBasicInfoMapper;
import com.sunxung.factoring.service.biddingManagement.IBiddingBasicInfoHisService;
import com.sunxung.factoring.service.biddingManagement.ICBiddingBasicInfoService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
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 author
 * @since 2023-11-20
 */
@Service("biddingBasicInfoService")
public class CBiddingBasicInfoServiceImpl extends ServiceImpl<CBiddingBasicInfoMapper, CBiddingBasicInfo>
        implements ICBiddingBasicInfoService {

    @Autowired
    private IBiddingBasicInfoHisService biddingBasicInfoHisService;
    @Autowired
    private BusinessAssigneeService assigneeService;
    @Autowired
    private UserService userService;
    @Autowired
    private FlowableService flowableService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private FileService fileService;
    @Autowired
    private DictionaryService dictService;
    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startProcess(CBiddingBasicInfo biddingBasicInfo) {

        //开启流程
        startBusinessManagementProcess(biddingBasicInfo);
        //处理流程
        handleProcess(biddingBasicInfo);
    }

    @Override
    public void handleProcess(CBiddingBasicInfo biddingBasicInfo) {

        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.LEGAL_SPECIALIST + "角色内无任何用户！");
        }

        String legallist = legalSpecialists.stream().map(id -> id.toString()).collect(Collectors.joining(","));

        //新增历史
        BiddingBasicInfoResultVo basicInfoResultVo = biddingBasicInfo.getBiddingBasicInfoResultVo();

        BiddingBasicInfoHis biddingBasicInfoHis = new BiddingBasicInfoHis(biddingBasicInfo);
        biddingBasicInfoHisService.save(biddingBasicInfoHis);
        //新增文件历史

        //投标文件
        List<Long> biddingFileIds = biddingBasicInfo.getBiddingFileIds();
        List<FileStorageDO> biddingFiles = fileService.listByIds(biddingFileIds);
        if (CollectionUtil.isNotEmpty(biddingFiles)) {
            biddingFiles.forEach(file -> {
                file.setBusinessId(biddingBasicInfoHis.getId());
                file.setBusinessType(FileModuleDict.ChildEnum.BIDDING_HIS_FILE.getCode());
                file.setId(null);
                fileService.save(file);
            });
        }

        //招标文件
        List<Long> tendersFileIds = biddingBasicInfo.getTendersFileIds();
        List<FileStorageDO> tendersFiles = fileService.listByIds(tendersFileIds);
        if (CollectionUtil.isNotEmpty(tendersFiles)) {
            tendersFiles.forEach(file -> {
                file.setBusinessId(biddingBasicInfoHis.getId());
                file.setBusinessType(FileModuleDict.ChildEnum.TENDERS_HIS_FILE.getCode());
                file.setId(null);
                fileService.save(file);
            });
        }

        //获取授信通过的招投标项目
        BusinessProcessingLog processingLog = businessProcessingLogService.getByBusinessTypeBusinessKey(ConstantUtil.BIDDING_MANAGEMENT, biddingBasicInfo.getId());
        //完成流程第一步提交验收单，开启下一步法务验收
        String processInstId = processingLog.getHistoricTaskId();
        Map<String, Object> msgVariables = new HashMap<>();
        Task task = flowableService.getByTaskQuery(processInstId);
//        Task task = flowableService.findRuntimeTaskByProcessInstId(processInstId).get(0);
        Map<String, Object> procVariables = new HashMap<>();
        procVariables.put(ConstantUtil.TEMPLATE_REVIEW_CANDIDATE, legallist);
        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);
        ThreadLocalUtil.setUser(userService.getByLoginName("admin"));
        flowableService.completeMyTask(task.getId(), biddingBasicInfo, procVariables, null, biddingBasicInfoHis.getId(),
                msgVariables, ConstantUtil.BIDDING_MANAGEMENT, legalSpecialists);
    }

//    @Override
//    public List<BusinessProcessingTaskVo> findMyCompletedList(SearchBusinessProcessingTask search) {
//        List<BusinessProcessingTaskVo> rows = baseMapper.findMyCompletedList(search);
//        rows.forEach(r->{
//            List<BusinessSupplierInfo> supplierInfos = businessSupplierInfoService.lambdaQuery().eq(BusinessSupplierInfo::getBusinessBasicInfoId, r.getId()).list();
//            String suppliersName = supplierInfos.stream().map(supplierInfo -> supplierInfo.getSupplierName()).collect(Collectors.joining(","));
//            r.setSupplierName(suppliersName);
//            if(StringUtil.isNotEmpty(r.getMode())){
//                if(r.getMode().equals("1")){
//                    r.setMode("保函");
//                }else if (r.getMode().equals("0")) {
//                    r.setMode("保证金");
//                }
//            }
//            CBiddingBasicInfo biddingBasicInfo = get(r.getId());
//            Dictionary status = dictService.getByCode(biddingBasicInfo.getStatusCode());
//            Dictionary stage = dictService.getByCode(biddingBasicInfo.getStage());
//            r.setStage(stage);
//            r.setStatus(status);
//            if(stage.getCode().equals(BusinessStageDict.ChildEnum.CREATE.getCode()) || stage.getCode().equals(BusinessStageDict.ChildEnum.GUARANTEE_MODE.getCode())
//                    || stage.getCode().equals(BusinessStageDict.ChildEnum.AWARD.getCode()) || stage.getCode().equals(BusinessStageDict.ChildEnum.REFUND_DEPOSIT.getCode())){
//                r.setExecutor(userService.get(biddingBasicInfo.getManagerId()).getName());
//            } else if(stage.getCode().equals(BusinessStageDict.ChildEnum.TEMPLATE_REVIEW.getCode())){
//                r.setExecutor("法务专员");
//            } else if(stage.getCode().equals(BusinessStageDict.ChildEnum.BOND_COLLECTION.getCode())){
//                r.setExecutor("会计");
//            }
//            r.setDelete(false);
//        });
//        return rows;
//    }

    @Override
    public List<BusinessProcessingTaskVo> findAllList(SearchBusinessProcessingTask search) {
        List<BusinessProcessingTaskVo> rows = baseMapper.findAllList(search);
        rows.forEach(r -> {
            if (StringUtil.isNotEmpty(r.getMode())) {
                if (r.getMode().equals("1")) {
                    r.setMode("保函");
                } else if (r.getMode().equals("0")) {
                    r.setMode("保证金");
                }
            }
            Dictionary status = dictService.getByCode(r.getStatus().getCode());
            r.setStatus(status);
            //填充当前阶段
            Dictionary stage = dictService.getByCode(r.getStage().getCode());
            r.setStage(stage);

            if (stage.getCode().equals(BusinessStageDict.ChildEnum.CREATE.getCode())) {
                r.setExecutor("供应商");
            }
            if (stage.getCode().equals(BusinessStageDict.ChildEnum.GUARANTEE_MODE.getCode())
                    || stage.equals(BusinessStageDict.ChildEnum.AWARD.getCode())) {
                r.setExecutor("业务经理");
            }
            if (stage.getCode().equals(BusinessStageDict.ChildEnum.TEMPLATE_REVIEW.getCode())) {
                r.setExecutor("法务专员");
            }
            if (stage.getCode().equals(BusinessStageDict.ChildEnum.BOND_COLLECTION.getCode()) ||
                    stage.equals(BusinessStageDict.ChildEnum.REFUND_DEPOSIT.getCode())) {
                r.setExecutor("财务");
            }
            if (stage.getCode().equals(BusinessStageDict.ChildEnum.AWARD.getCode())){
                r.setExecutor("业务经理");
            }
            if (stage.getCode().equals(BusinessStageDict.ChildEnum.CREATE.getCode())) {
                r.setDelete(true);
            } else {
                r.setDelete(false);
            }
            //是否展示下载文件按钮
            r.setDownloadFileFlag(false);
            if (ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode().equals(status.getCode()) ||
                    ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode().equals(status.getCode())) {
                r.setDownloadFileFlag(true);
            }
        });
        return rows;
    }

    @Override
    public BiddingBasicInfoResultVo getCreditProjectByBiddingId(Long id) {
        return baseMapper.getCreditProjectByBiddingId(id);
    }

    @Override
    public BiddingBasicInfoResultVo getByHisId(Long hisId) {
        return baseMapper.getByHisId(hisId);
    }

    @Override
    public CBiddingBasicInfo get(Long id) {
        CBiddingBasicInfo biddingBasicInfo = baseMapper.get(id);
        Dictionary status = dictService.getByCode(biddingBasicInfo.getStatusCode());
        biddingBasicInfo.setStatusDictionary(status);
        return biddingBasicInfo;
    }


    private void startBusinessManagementProcess(CBiddingBasicInfo biddingBasicInfo) {

        User admin = userService.getByLoginName("admin");

        //3.开启流程实例
        Map<String, Object> procVariables = new HashMap<>();
        procVariables.put(ConstantUtil.BUSINESS_ADD_ASSIGNEE, admin.getId());
        //获取授信通过的招投标项目
        BiddingBasicInfoResultVo basicInfoResultVo = biddingBasicInfo.getBiddingBasicInfoResultVo();
        String queryBusiness = basicInfoResultVo.getBusinessNumber() + FlowableUtil.splitChar + basicInfoResultVo.getProjectName() +
                FlowableUtil.splitChar + basicInfoResultVo.getEnterprise() + FlowableUtil.splitChar + basicInfoResultVo.getPlatform() +
                FlowableUtil.splitChar + basicInfoResultVo.getMainEnterprise();
        ProcessInstance processInst = flowableService.startProcessInstance(biddingBasicInfo, procVariables,
                FlowableUtil.generateBusinessKey(biddingBasicInfo, ConstantUtil.BIDDING_MANAGEMENT, queryBusiness), null, ConstantUtil.BIDDING_MANAGEMENT);
        if (processInst == null) {
            throw new BusinessException(CodeUtil.FAIL, "流程启动失败");
        }

    }



}
