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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.auth.response.ResponseJson;
import com.inkasso.factoring.acceptanceManagement.dao.CAcceptancePriceAdjustInfoMapper;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceBasicInfo;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceGoodsInfo;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptancePriceAdjustInfo;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptancePriceGoodsInfo;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceBasicInfoService;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptancePriceAdjustInfoService;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptancePriceGoodsInfoService;
import com.inkasso.factoring.common.enums.ProjectInitiationStatusEnum;
import com.inkasso.factoring.creditmanagement.entity.Enterprise;
import com.inkasso.factoring.creditmanagement.service.IEnterpriseService;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 验收单单价调整表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-12-19
 */
@Service
public class CAcceptancePriceAdjustInfoServiceImpl extends ServiceImpl<CAcceptancePriceAdjustInfoMapper, CAcceptancePriceAdjustInfo> implements ICAcceptancePriceAdjustInfoService {

    @Autowired
    private ICAcceptanceBasicInfoService acceptanceBasicInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ICAcceptancePriceGoodsInfoService acceptancePriceGoodsInfoService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.acceptanceAdjustStartProcessUrl}")
    private String acceptanceAdjustStartProcessUrl;
    @Value("${trade.acceptanceAdjustHandleProcessUrl}")
    private String acceptanceAdjustHandleProcessUrl;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private ITradingPlatformService platformService;

    @Override
    public CAcceptancePriceAdjustInfo getDetail(Long acceptanceBasicId) {

        CAcceptanceBasicInfo acceptanceBasicInfo = acceptanceBasicInfoService.findDetail(acceptanceBasicId);
        if (acceptanceBasicInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "验收单基础信息不能为空！");
        }
        CAcceptancePriceAdjustInfo adjustInfo;
        if (acceptanceBasicInfo.getAcceptanceStatus().equals(ProjectInitiationStatusEnum.PROCESSING.getCode())) {
            //退回的信息
            //获取最新一条单价调整的信息
            QueryWrapper<CAcceptancePriceAdjustInfo> last = new QueryWrapper<CAcceptancePriceAdjustInfo>().eq("c_acceptance_basic_info_id",
                    acceptanceBasicId)
                .orderByDesc("gmt_create").last("limit 1");
            adjustInfo = getOne(last);
            //供应商（主企业）
            Enterprise mainEnterprise = enterpriseService.getById(acceptanceBasicInfo.getcSupplierInfoId());
            adjustInfo.setMainEnterprise(mainEnterprise);
            //核心企业
            Enterprise customerEnterprise = enterpriseService.getById(acceptanceBasicInfo.getcProjectCoreEnterpriseId());
            adjustInfo.setCoreEnterprise(customerEnterprise);
            //贸易平台
            Platform platform = platformService.getById(acceptanceBasicInfo.getTradingPlatformId());
            adjustInfo.setPlatform(platform);
            //业务编号
            adjustInfo.setBusinessNumber(acceptanceBasicInfo.getBusinessNumber());
            //预计结算日期
            adjustInfo.setExpectedSettlementDate(acceptanceBasicInfo.getExpectedSettlementDate());
            //货物信息
            List<CAcceptancePriceGoodsInfo> adjustGoodsList = acceptancePriceGoodsInfoService
                    .list(new QueryWrapper<CAcceptancePriceGoodsInfo>()
                            .eq("c_acceptance_price_adjust_info_id", adjustInfo.getId()));
            adjustInfo.setPriceGoodsInfoList(adjustGoodsList);
            //补充说明文件（调整）
            List<FileStorageDO> fileList = fileService.findByBusinessId(adjustInfo.getId(), FileTypeEnum.ACCEPTANCE_ADJUST_FILE.getCode());
            adjustInfo.setFileList(fileList);

        } else {
            //初始化验收单价调整信息
            adjustInfo = new CAcceptancePriceAdjustInfo(acceptanceBasicInfo);
            //供应商（主企业）
            Enterprise mainEnterprise = enterpriseService.getById(acceptanceBasicInfo.getcSupplierInfoId());
            adjustInfo.setMainEnterprise(mainEnterprise);
            //核心企业
            Enterprise customerEnterprise = enterpriseService.getById(acceptanceBasicInfo.getcProjectCoreEnterpriseId());
            adjustInfo.setCoreEnterprise(customerEnterprise);
            //贸易平台
            Platform platform = platformService.getById(acceptanceBasicInfo.getTradingPlatformId());
            adjustInfo.setPlatform(platform);
            //业务编号
            adjustInfo.setBusinessNumber(acceptanceBasicInfo.getBusinessNumber());
            //预计结算日期
            adjustInfo.setExpectedSettlementDate(acceptanceBasicInfo.getExpectedSettlementDate());
            //验收单货物信息
            List<CAcceptanceGoodsInfo> acceptanceGoodInfos = acceptanceBasicInfo.getAcceptanceGoodInfos();
            if (CollectionUtil.isNotEmpty(acceptanceGoodInfos)) {
                List<CAcceptancePriceGoodsInfo> priceGoodsInfoList = new ArrayList<>();
                acceptanceGoodInfos.forEach(cAcceptanceGoodsInfo -> {
                    CAcceptancePriceGoodsInfo priceGoodsInfo = new CAcceptancePriceGoodsInfo();
                    BeanUtils.copyProperties(cAcceptanceGoodsInfo, priceGoodsInfo);
                    priceGoodsInfoList.add(priceGoodsInfo);
                });
                adjustInfo.setPriceGoodsInfoList(priceGoodsInfoList);
            }

        }

        return adjustInfo;
    }

    @Override
    public ResponseJson doAdjust(CAcceptancePriceAdjustInfo adjustInfo) {

        if (CollectionUtil.isEmpty(adjustInfo.getFileIds())) {
            throw new ValidatorException(CodeUtil.FAIL, "补充文件不能为空！");
        }

        if (CollectionUtil.isEmpty(adjustInfo.getPriceGoodsInfoList())) {
            throw new ValidatorException(CodeUtil.FAIL, "货物信息不能为空！");
        }
        ResponseEntity<ResponseJson> response = null;
        if (adjustInfo.getId() != null) {
            //退回
            updateById(adjustInfo);
            //删除货物
            acceptancePriceGoodsInfoService.removeBatchByIds(adjustInfo.getPriceGoodsInfoList());
            //新增货物
            acceptancePriceGoodsInfoService.saveBatch(adjustInfo.getPriceGoodsInfoList());
            //删除文件
            if (CollectionUtil.isNotEmpty(adjustInfo.getDeleteFileIds())) {
                fileService.removeBatchByIds(adjustInfo.getDeleteFileIds());
            }
            List<Long> fileIds = adjustInfo.getFileIds();
            if (CollectionUtil.isNotEmpty(fileIds)) {
                fileService.updateBusinessId(fileIds, adjustInfo.getId());
            }
            //流程处理
            response = restTemplate.postForEntity(acceptanceAdjustHandleProcessUrl, adjustInfo, ResponseJson.class);
        } else {
            //修改主业务状态
            CAcceptanceBasicInfo cAcceptanceBasicInfo = acceptanceBasicInfoService.getById(
                adjustInfo.getcAcceptanceBasicInfoId());
            cAcceptanceBasicInfo.setAcceptanceStatus(ProjectInitiationStatusEnum.PROCESSING.getCode());
            acceptanceBasicInfoService.updateById(cAcceptanceBasicInfo);

            save(adjustInfo);
            //保存货物信息
            List<CAcceptancePriceGoodsInfo> priceGoodsInfoList = adjustInfo.getPriceGoodsInfoList();
            priceGoodsInfoList.forEach(goods -> {
                goods.setcAcceptancePriceAdjustInfoId(adjustInfo.getId());
            });
            acceptancePriceGoodsInfoService.saveBatch(priceGoodsInfoList);
            List<Long> fileIds = adjustInfo.getFileIds();
            if (CollectionUtil.isNotEmpty(fileIds)) {
                fileService.updateBusinessId(fileIds, adjustInfo.getId());
            }
            //  开启流程
            response = restTemplate.postForEntity(acceptanceAdjustStartProcessUrl, adjustInfo, ResponseJson.class);
        }
        return response.getBody();

    }
}
