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


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.factoring.biddingManagement.dao.CBiddingBasicInfoMapper;
import com.inkasso.factoring.biddingManagement.entity.CBiddingBasicInfo;
import com.inkasso.factoring.biddingManagement.entity.SearchBiddingBasic;
import com.inkasso.factoring.biddingManagement.entity.vo.BiddingBasicInfoResultVo;
import com.inkasso.factoring.biddingManagement.service.ICBiddingBasicInfoService;
import com.inkasso.factoring.common.entity.GridPage;
import com.inkasso.factoring.common.enums.BiddingStageEnum;
import com.inkasso.factoring.common.enums.ProjectInitiationStatusEnum;
import com.inkasso.factoring.creditmanagement.entity.ProjectInformation;
import com.inkasso.factoring.creditmanagement.entity.vo.UserBiddingProjectsVo;
import com.inkasso.factoring.creditmanagement.service.IProjectInformationService;
import com.inkasso.factoring.dict.entity.Dictionary;
import com.inkasso.factoring.dict.service.DictionaryService;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.tradingPlatform.entity.Platform;
import com.inkasso.factoring.tradingPlatform.service.ITradingPlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

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

/**
 * <p>
 * 招投标管理基本信息表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-11-21
 */
@Service
public class CBiddingBasicInfoServiceImpl extends ServiceImpl<CBiddingBasicInfoMapper, CBiddingBasicInfo>
        implements ICBiddingBasicInfoService {

    @Autowired
    private FileService fileService;
    @Autowired
    private DictionaryService dictionaryService;
    @Value("${trade.biddingManagementStartProcessUrl}")
    private String biddingManagementStartProcessUrl;
    @Value("${trade.biddingManagementHandleProcessUrl}")
    private String biddingManagementHandleProcessUrl;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ITradingPlatformService platformService;

    @Override
    public CBiddingBasicInfo getDetail(Long id) {
        //填充基础信息
        UserBiddingProjectsVo basicInfo = baseMapper.getBasicInfo(id);
        CBiddingBasicInfo biddingBasicInfo = getById(id);
        Platform platform = platformService.getById(biddingBasicInfo.getTradingPlatformId());
        basicInfo.setPlatform(platform);
        biddingBasicInfo.setBasicInfo(basicInfo);


        List<FileStorageDO> tendersFiles = fileService.findByBusinessId(id, FileTypeEnum.TENDERS_FILE.getCode());
        biddingBasicInfo.setTendersFileStorageDOList(tendersFiles);

        List<FileStorageDO> biddingFiles = fileService.findByBusinessId(id, FileTypeEnum.BIDDING_FILE.getCode());
        biddingBasicInfo.setBiddingFileStorageDOList(biddingFiles);

        return biddingBasicInfo;
    }

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

        biddingBasicInfo.setStatusCode(ProjectInitiationStatusEnum.PROCESSING.getCode());
        biddingBasicInfo.setStage(BiddingStageEnum.TEMPLATE_REVIEW.getCode());

        save(biddingBasicInfo);

        //招标文件id
        List<Long> tendersFileIds = biddingBasicInfo.getTendersFileIds();
        if (CollectionUtil.isNotEmpty(tendersFileIds)) {
            tendersFileIds.forEach(c -> {
                FileStorageDO fileStorageDO = fileService.getById(c);
                fileStorageDO.setBusinessId(biddingBasicInfo.getId());
                fileService.updateById(fileStorageDO);
            });
        }
        //投标文件id
        List<Long> biddingFileIds = biddingBasicInfo.getBiddingFileIds();
        if (CollectionUtil.isNotEmpty(biddingFileIds)) {
            biddingFileIds.forEach(c -> {
                FileStorageDO fileStorageDO = fileService.getById(c);
                fileStorageDO.setBusinessId(biddingBasicInfo.getId());
                fileService.updateById(fileStorageDO);
            });
        }
        //在B端开启流程
        BiddingBasicInfoResultVo basicInfoResultVo = baseMapper.getCreditProjectByBiddingId(biddingBasicInfo.getId());
        biddingBasicInfo.setBiddingBasicInfoResultVo(basicInfoResultVo);
        restTemplate.postForEntity(biddingManagementStartProcessUrl, biddingBasicInfo, String.class);

    }

    @Override
    public void handleProcess(CBiddingBasicInfo biddingBasicInfo) {

        //更新数据
        biddingBasicInfo.setStage(BiddingStageEnum.TEMPLATE_REVIEW.getCode());
        updateById(biddingBasicInfo);
        //更新文件
        List<FileStorageDO> tendersFiles = fileService.findByBusinessId(biddingBasicInfo.getId(), FileTypeEnum.TENDERS_FILE.getCode());
        List<Long> tenderFileIds = tendersFiles.stream().map(FileStorageDO::getId).collect(Collectors.toList());
        fileService.updateBusinessId(tenderFileIds,null);
        //招标文件id
        List<Long> tendersFileIds = biddingBasicInfo.getTendersFileIds();
        if (CollectionUtil.isNotEmpty(tendersFileIds)) {
            tendersFileIds.forEach(c -> {
                FileStorageDO fileStorageDO = fileService.getById(c);
                fileStorageDO.setBusinessId(biddingBasicInfo.getId());
                fileService.updateById(fileStorageDO);
            });
        }

        List<FileStorageDO> oldBiddingFileIds = fileService.findByBusinessId(biddingBasicInfo.getId(), FileTypeEnum.BIDDING_FILE.getCode());
        List<Long> oldBiddingIds = oldBiddingFileIds.stream().map(FileStorageDO::getId).collect(Collectors.toList());
        fileService.updateBusinessId(oldBiddingIds,null);
        //投标文件id
        List<Long> biddingFileIds = biddingBasicInfo.getBiddingFileIds();
        if (CollectionUtil.isNotEmpty(biddingFileIds)) {
            biddingFileIds.forEach(c -> {
                FileStorageDO fileStorageDO = fileService.getById(c);
                fileStorageDO.setBusinessId(biddingBasicInfo.getId());
                fileService.updateById(fileStorageDO);
            });
        }

        //在B端处理流程
        BiddingBasicInfoResultVo basicInfoResultVo = baseMapper.getCreditProjectByBiddingId(biddingBasicInfo.getId());
        biddingBasicInfo.setBiddingBasicInfoResultVo(basicInfoResultVo);
        restTemplate.postForEntity(biddingManagementHandleProcessUrl, biddingBasicInfo, String.class);
    }

    @Override
    public GridPage<BiddingBasicInfoResultVo> findBySearch(SearchBiddingBasic search) {
        search.setUserId(LoginUserHolder.get().getId());
        Page<BiddingBasicInfoResultVo> page = PageHelper.startPage(search.getPage(), search.getRows());
        List<BiddingBasicInfoResultVo> resultVos = baseMapper.findBySearch(search);
        if (CollectionUtil.isNotEmpty(resultVos)) {
            resultVos.forEach(c -> {
                //填充状态和当前阶段
                if (c.getStage()!=null){
                    Dictionary stageDic = dictionaryService.getByCode(c.getStage());
                    c.setStage(stageDic.getName());
                }

                if (c.getStatus() != null){
                    Dictionary statusDic = dictionaryService.getByCode(c.getStatus());
                    c.setStatus(statusDic.getName());
                }
            });
        }
        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), resultVos);
    }
}
