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

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.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.salesManagement.dao.CSalesContractSupplementBasicInfoMapper;
import com.inkasso.factoring.salesManagement.entity.*;
import com.inkasso.factoring.salesManagement.entity.vo.SalesContractBasicVo;
import com.inkasso.factoring.salesManagement.service.*;
import org.springframework.beans.BeanUtils;
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 CSalesContractSupplementBasicInfoServiceImpl extends ServiceImpl<CSalesContractSupplementBasicInfoMapper,
        CSalesContractSupplementBasicInfo> implements ICSalesContractSupplementBasicInfoService {

    @Autowired
    private ICSalesContractBasicInfoService salesContractBasicInfoService;
    @Autowired
    private ICSalesContractSupplementInfoService supplementInfoService;
    @Autowired
    private ICSalesContractSupplementGoodsInfoService supplementGoodsInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ICSalesContractManagementService salesContractManagementService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.salesContractChangeEnterUrl}")
    private String salesContractChangeEnterUrl;
    @Autowired
    private ICSalesContractGoodsInfoService salesContractGoodsInfoService;

    @Override
    public CSalesContractSupplementBasicInfo add(Long salesContractManagementId) {

        SalesContractBasicVo contractBasicVo = salesContractManagementService.getView(salesContractManagementId);
        CSalesContractSupplementInfo contractSupplementInfo = supplementInfoService.getOne(new QueryWrapper<CSalesContractSupplementInfo>()
                .eq("c_sales_contract_management_id", salesContractManagementId).orderByDesc("gmt_create"));
        CSalesContractSupplementBasicInfo supplementBasicInfo = null;
        if (contractSupplementInfo != null) {
            supplementBasicInfo = getOne(new QueryWrapper<CSalesContractSupplementBasicInfo>()
                    .eq("c_sales_contract_supplement_info_id", contractSupplementInfo.getId()));
            if (supplementBasicInfo != null) {
                //货物信息
                List<CSalesContractSupplementGoodsInfo> supplementGoodsInfoList = supplementGoodsInfoService
                        .list(new QueryWrapper<CSalesContractSupplementGoodsInfo>().eq("c_sales_contract_supplement_basic_info_id", supplementBasicInfo.getId()));
                if (CollectionUtil.isNotEmpty(supplementGoodsInfoList)) {
                    supplementBasicInfo.setSupplementGoodsInfos(supplementGoodsInfoList);
                }
                //合同文件
                List<FileStorageDO> fileStorageDOList = fileService.findByBusinessId(supplementBasicInfo.getId(), FileTypeEnum.SALES_SUPPLEMENT_CONTRACT_FILE.getCode());
                supplementBasicInfo.setFileStorageDOs(fileStorageDOList);
            } else {
                supplementBasicInfo = new CSalesContractSupplementBasicInfo();
                CSalesContractBasicInfo contractBasicInfo = salesContractBasicInfoService.lambdaQuery()
                        .eq(CSalesContractBasicInfo::getcSalesContractManagementId, salesContractManagementId).one();
                List<CSalesContractGoodsInfo> goodsInfos = salesContractGoodsInfoService.lambdaQuery()
                        .eq(CSalesContractGoodsInfo::getcSalesContractBasicInfoId, contractBasicInfo.getId()).list();
                List<CSalesContractSupplementGoodsInfo> goodsInfoList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(goodsInfos)) {
                    goodsInfos.forEach(goodsInfo -> {
                        CSalesContractSupplementGoodsInfo supplementGoodsInfo = new CSalesContractSupplementGoodsInfo();
                        BeanUtils.copyProperties(goodsInfo, supplementGoodsInfo, "id");
                        goodsInfoList.add(supplementGoodsInfo);
                    });
                }
                supplementBasicInfo.setSupplementGoodsInfos(goodsInfoList);
            }
            supplementBasicInfo.setContractBasicVo(contractBasicVo);

        }


        return supplementBasicInfo;
    }

    @Override
    public CSalesContractSupplementBasicInfo getView(Long id) {
        CSalesContractSupplementInfo contractSupplementInfo = supplementInfoService.getOne(new QueryWrapper<CSalesContractSupplementInfo>()
                .eq("id", id));
        CSalesContractSupplementBasicInfo supplementBasicInfo = getOne(new QueryWrapper<CSalesContractSupplementBasicInfo>()
                .eq("c_sales_contract_supplement_info_id", contractSupplementInfo.getId()));
        if (supplementBasicInfo != null) {
            //货物信息
            List<CSalesContractSupplementGoodsInfo> supplementGoodsInfoList = supplementGoodsInfoService
                    .list(new QueryWrapper<CSalesContractSupplementGoodsInfo>().eq("c_sales_contract_supplement_basic_info_id", supplementBasicInfo.getId()));
            if (CollectionUtil.isNotEmpty(supplementGoodsInfoList)) {
                supplementBasicInfo.setSupplementGoodsInfos(supplementGoodsInfoList);
            }
            //合同文件
            List<FileStorageDO> fileStorageDOList = fileService.findByBusinessId(supplementBasicInfo.getId(), FileTypeEnum.SALES_SUPPLEMENT_CONTRACT_FILE.getCode());
            supplementBasicInfo.setFileStorageDOs(fileStorageDOList);
        }
        return supplementBasicInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAdd(CSalesContractSupplementBasicInfo supplementBasicInfo) {

        try {
            restTemplate.postForObject(salesContractChangeEnterUrl, supplementBasicInfo, String.class);
        } catch (Exception e) {
            String result = e.getMessage().substring(7, e.getMessage().length() - 1);
            JSONObject jsonObject = new JSONObject(result);
            throw new BusinessException(CodeUtil.FAIL, jsonObject.get("msg").toString());
        }

    }
}
