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

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.factoring.creditmanagement.entity.ProjectInformation;
import com.inkasso.factoring.creditmanagement.service.IProjectInformationService;
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.file.util.FileStorageUtil;
import com.inkasso.factoring.purchManagement.dao.CPurchContractSupplementInfoMapper;
import com.inkasso.factoring.purchManagement.entity.CPurchContractBasicInfo;
import com.inkasso.factoring.purchManagement.entity.CPurchContractManagement;
import com.inkasso.factoring.purchManagement.entity.CPurchContractSupplementGoodsInfo;
import com.inkasso.factoring.purchManagement.entity.CPurchContractSupplementInfo;
import com.inkasso.factoring.purchManagement.entity.vo.PurchContractChangeVo;
import com.inkasso.factoring.purchManagement.service.*;
import com.inkasso.factoring.salesManagement.entity.CSalesContractManagement;
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.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 采购合同-补充信息表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-12-15
 */
@Service
public class CPurchContractSupplementInfoServiceImpl extends ServiceImpl<CPurchContractSupplementInfoMapper, CPurchContractSupplementInfo>
        implements ICPurchContractSupplementInfoService {

    @Autowired
    private ICPurchContractManagementService purchContractService;
    @Autowired
    private ICPurchContractBasicInfoService purchContractBasicInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ICPurchContractSupplementElectronicInfoService purchContractSupplementElectronicInfoService;
    @Autowired
    private IProjectInformationService projectInformationService;
    @Autowired
    private ITradingPlatformService platformService;
    @Autowired
    private ICSalesContractManagementService salesContractService;
    @Autowired
    private ICPurchContractSupplementGoodsInfoService purchContractSupplementGoodsInfoService;
    @Value("${trade.purchContractChangeEnterUrl}")
    private String purchContractChangeEnterUrl;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean change(PurchContractChangeVo vo) {


        try {
            restTemplate.postForObject(purchContractChangeEnterUrl, vo, String.class);
        } catch (Exception e) {
            String result = e.getMessage().substring(7, e.getMessage().length() - 1);
            cn.hutool.json.JSONObject jsonObject = new JSONObject(result);
            throw new BusinessException(CodeUtil.FAIL, jsonObject.get("msg").toString());
        }
        return true;
    }

    @Override
    public PurchContractChangeVo getDetail(Long id) {


        PurchContractChangeVo contractChangeVo = new PurchContractChangeVo();
        CPurchContractSupplementInfo supplementInfo = lambdaQuery().eq(CPurchContractSupplementInfo::getcPurchContractManagementId, id)
                .orderByDesc(CPurchContractSupplementInfo::getGmtCreate).last("limit 1").one();
        if (supplementInfo != null) {
            contractChangeVo.setContractSupplementInfo(supplementInfo);

            List<CPurchContractSupplementGoodsInfo> goodsInfoList = purchContractSupplementGoodsInfoService.lambdaQuery()
                    .eq(CPurchContractSupplementGoodsInfo::getcPurchContractSupplementInfoId, supplementInfo.getId()).list();
            contractChangeVo.setContractGoodsInfo(goodsInfoList);
        }

        return contractChangeVo;
    }

    private void checkVo(PurchContractChangeVo vo) {
        if (vo == null || vo.getBusinessKey() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "采购合同信息不能为空");
        }

        if (vo.getContractSupplementInfo() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "采购合同变更补充信息不能为空");
        }

        if (vo.getContractSupplementInfo().getAddGoods().equals(1)) {
            if (vo.getContractGoodsInfo() == null || vo.getContractGoodsInfo().size() == 0) {
                throw new ValidatorException(CodeUtil.FAIL, "采购合同变更货物信息不能为空");
            }
        }
    }

    private CPurchContractManagement getContractManageByBusinessKey(PurchContractChangeVo vo) {
        CPurchContractManagement contractManagement = purchContractService.getById(vo.getBusinessKey());
        if (contractManagement == null) {
            throw new BusinessException(CodeUtil.FAIL, "BusinessKey无效");
        }
        return contractManagement;
    }


    @Override
    public String getContractNumber(Long businessKey) {
        //合同编号，系统自动生成，生成规则为：
        List<CPurchContractSupplementInfo> oldPurchContractSupplementInfos = lambdaQuery()
                .eq(CPurchContractSupplementInfo::getcPurchContractManagementId, businessKey)
                .orderByDesc(CPurchContractSupplementInfo::getGmtCreate).list();
        CPurchContractBasicInfo latestBasicInfo = purchContractBasicInfoService
                .getOne(new QueryWrapper<CPurchContractBasicInfo>()
                        .eq("c_purch_contract_management_id", businessKey));
        if (latestBasicInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "无法获取主合同信息！");
        }
        String contractNumber = latestBasicInfo.getContractNumber() + "-BO";
        if (CollectionUtil.isNotEmpty(oldPurchContractSupplementInfos)) {
            int number = (int) oldPurchContractSupplementInfos.stream().count() + 1;
            contractNumber = contractNumber + String.valueOf(number);
        } else {
            contractNumber = contractNumber + "1";
        }
        return contractNumber;
    }

    @Override
    public FileStorageDO makeContract(Long businessKey, String otherConvention) {
        CPurchContractManagement purchContractManagement = purchContractService.getById(businessKey);
        List<CPurchContractSupplementInfo> purchContractSupplementInfos = lambdaQuery()
                .eq(CPurchContractSupplementInfo::getcPurchContractManagementId, purchContractManagement.getId())
                .orderByDesc(CPurchContractSupplementInfo::getGmtCreate)
                .list();

        if (purchContractSupplementInfos == null || purchContractSupplementInfos.size() == 0) {
            throw new BusinessException(CodeUtil.FAIL, "未查到该变更信息");
        }
        //项目信息
        ProjectInformation projectInformation = projectInformationService.getOne(new QueryWrapper<ProjectInformation>()
                .eq("business_number", purchContractManagement.getBusinessNumber()));
        CSalesContractManagement salesContractInfo = salesContractService.getOne(new QueryWrapper<CSalesContractManagement>()
                .eq("c_project_information_id", projectInformation.getId()));
        Platform platform = platformService.getById(salesContractInfo.getTradingPlatformId());

        CPurchContractSupplementInfo supplementInfo = purchContractSupplementInfos.get(0);
        CPurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getOne(new QueryWrapper<CPurchContractBasicInfo>()
                .eq("c_purch_contract_management_id", purchContractManagement.getId()));
        //制作合同
        File outFile = null;
        try {
            outFile = purchContractSupplementElectronicInfoService.makePurchContractDocx(purchContractManagement, purchContractBasicInfo,
                    projectInformation, platform, supplementInfo, otherConvention);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将docx转为pdf
        String suffix = FileUtil.getSuffix(outFile.getName());
        String newPath = outFile.getAbsolutePath().replace(suffix, ".pdf");
//        File purchContractPdfFile = OfficeConverterUtil.office2Pdf(outFile.getAbsolutePath(), newPath);
        FileStorageDO fileStorage = FileStorageUtil.createFileStorage2(outFile.getName(), suffix, FileTypeEnum.PURCHASE_CONTRACT_SUPPLEMENT_FILE);
        fileStorage.setBusinessId(supplementInfo.getId());
        fileService.save(fileStorage);
        return fileStorage;
    }

    @Override
    public PurchContractChangeVo getView(Long id) {
        PurchContractChangeVo contractChangeVo = new PurchContractChangeVo();
        CPurchContractSupplementInfo supplementInfo = lambdaQuery().eq(CPurchContractSupplementInfo::getId, id).one();
        if (supplementInfo != null) {
            contractChangeVo.setContractSupplementInfo(supplementInfo);

            List<CPurchContractSupplementGoodsInfo> goodsInfoList = purchContractSupplementGoodsInfoService.lambdaQuery()
                    .eq(CPurchContractSupplementGoodsInfo::getcPurchContractSupplementInfoId, supplementInfo.getId()).list();
            contractChangeVo.setContractGoodsInfo(goodsInfoList);
        }

        return contractChangeVo;
    }


}
