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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.factoring.biddingManagement.entity.CBiddingBasicInfo;
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.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.salesManagement.dao.CSalesContractManagementMapper;
import com.inkasso.factoring.salesManagement.entity.CSalesContractBasicInfo;
import com.inkasso.factoring.salesManagement.entity.CSalesContractManagement;
import com.inkasso.factoring.salesManagement.entity.SearchSalesBasic;
import com.inkasso.factoring.salesManagement.entity.vo.SalesContractBasicVo;
import com.inkasso.factoring.salesManagement.entity.vo.SalesContractListVo;
import com.inkasso.factoring.salesManagement.service.ICSalesContractBasicInfoService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractManagementService;
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.ArrayList;
import java.util.List;

/**
 * <p>
 * 销售合同管理表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-11-28
 */
@Service
public class CSalesContractManagementServiceImpl extends ServiceImpl<CSalesContractManagementMapper, CSalesContractManagement> implements ICSalesContractManagementService {

    @Autowired
    private FileService fileService;
    @Autowired
    private ICBiddingBasicInfoService biddingBasicInfoService;
    @Autowired
    private ITradingPlatformService platformService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private ICSalesContractBasicInfoService contractBasicInfoService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.salesContractCreateUrl}")
    private String salesContractCreateUrl;

    @Override
    public GridPage<SalesContractListVo> list(SearchSalesBasic search) {

        search.setUserId(LoginUserHolder.get().getId());
        Page<BiddingBasicInfoResultVo> page = PageHelper.startPage(search.getPage(), search.getRows());
        List<SalesContractListVo> contractListVos = baseMapper.findBySearch(search);
        if (CollectionUtil.isNotEmpty(contractListVos)) {
            contractListVos.forEach(c -> {
                Dictionary statusDic = dictionaryService.getByCode(c.getStatus());
                c.setStatus(statusDic.getName());
            });
        }

        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), contractListVos);
    }

    @Override
    public SalesContractBasicVo getView(Long id) {
        SalesContractBasicVo contractBasicVo = baseMapper.getBasicInfoById(id);
        List<FileStorageDO> fileStorageDOList = fileService.findByBusinessId(id, FileTypeEnum.SALES_CONTRACT_MANAGEMENT_FILE.getCode());
        contractBasicVo.setFiles(fileStorageDOList);
        return contractBasicVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAdd(CSalesContractManagement salesContractManagement) {
        try {
            restTemplate.postForObject(salesContractCreateUrl, salesContractManagement, String.class);
        } catch (Exception e) {
            throw new BusinessException(CodeUtil.FAIL, e.getMessage());
        }
    }

    @Override
    public List<SalesContractBasicVo> getCreditProject() {

        List<SalesContractBasicVo> contractBasicVos = baseMapper.getCreditProject(LoginUserHolder.get().getId());
        if (CollectionUtil.isNotEmpty(contractBasicVos)) {
            List<Platform> allPlatforms = platformService.list();
            contractBasicVos.forEach(salesContractBasicVo -> {
                if (salesContractBasicVo.getcBiddingBasicInfoId() != null) {
                    //招投标信息
                    //当为中标项目时，拉取展示 项目关联的贸易平台公司名称
                    CBiddingBasicInfo biddingBasicInfo = biddingBasicInfoService.getById(salesContractBasicVo.getcBiddingBasicInfoId());
                    Platform platform = platformService.getById(biddingBasicInfo.getTradingPlatformId());
                    List<Platform> platforms = new ArrayList<>();
                    platforms.add(platform);
                    salesContractBasicVo.setPlatforms(platforms);
                } else {
                    salesContractBasicVo.setPlatforms(allPlatforms);
                }
            });
        }

        return contractBasicVos;
    }

    @Override
    public List<SalesContractBasicVo> getCompletedSales() {

        return baseMapper.getCompletedSales(LoginUserHolder.get().getId());
    }

    @Override
    public SalesContractBasicVo getCompletedSalesByBusinessNumber(String businessNumber) {
        return baseMapper.getCompletedSalesByBusinessNumber(businessNumber);
    }

    @Override
    public CSalesContractBasicInfo findByBusinessNumber(String businessNumber) {
        CSalesContractManagement contractManagement = getOne(new QueryWrapper<CSalesContractManagement>().eq("business_number", businessNumber).orderByDesc("gmt_modified")
                .last("limit 1"));
        CSalesContractBasicInfo contractBasicInfo = contractBasicInfoService.getOne(new QueryWrapper<CSalesContractBasicInfo>()
                .eq("c_sales_contract_management_id", contractManagement.getId())
                .orderByDesc("gmt_modified").last("limit 1"));
        return contractBasicInfo;
    }

    @Override
    public CSalesContractManagement getByBusinessNumber(String businessNumber) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("business_number", businessNumber);
        return baseMapper.selectOne(queryWrapper);
    }
}
