package com.trade.admin.tradingPlatform.service.impl;


import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.trade.admin.tradingPlatform.service.TradingPlatformService;
import com.trade.common.constant.HttpStatus;
import com.trade.common.core.page.GridPage;
import com.trade.common.exception.ValidatorException;
import com.trade.common.utils.ConstantUtil;
import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.bean.BeanUtils;
import com.trade.common.utils.bean.Builder;
import com.trade.common.validate.ValidatorGroup;
import com.trade.common.validate.ValidatorUtil;
import com.trade.service.DictConstants;
import com.trade.service.FileTypeEnum;
import com.trade.service.TransStruct;
import com.trade.service.filestorage.entity.BusinessRelateFile;
import com.trade.service.filestorage.service.BusinessRelateFileBaseService;
import com.trade.service.serialNum.service.SerialNumberGenerator;
import com.trade.service.tradingPlatform.domain.TradingPlatform;
import com.trade.service.tradingPlatform.domain.TradingPlatformInsurance;
import com.trade.service.tradingPlatform.domain.TradingPlatformQualification;
import com.trade.service.tradingPlatform.dto.*;
import com.trade.service.tradingPlatform.service.TradingPlatformBaseService;
import com.trade.service.tradingPlatform.service.TradingPlatformInsuranceBaseService;
import com.trade.service.tradingPlatform.service.TradingPlatformQualificationBaseService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 贸易平台服务实现类
 *
 * @author hlb
 * @since 2024-06-05 17:00:44
 */
@Service("tradingPlatformService")
public class TradingPlatformServiceImpl implements TradingPlatformService {
    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);

    @Resource
    private TradingPlatformBaseService tradingPlatformBaseService;
    @Resource
    private TradingPlatformQualificationBaseService tradingPlatformQualificationBaseService;
    @Resource
    private TradingPlatformInsuranceBaseService tradingPlatformInsuranceBaseSService;
    @Resource
    private SerialNumberGenerator serialNumberGenerator;
    @Resource
    private BusinessRelateFileBaseService businessRelateFileBaseService;
    @Resource
    private TransStruct transStruct;

    @Override
    public GridPage<TradingPlatformBaseInfo> getPages(TradingPlatformSearchDto search) {
        Page<TradingPlatformBaseInfo> page = PageHelper.startPage(search.getPage(), search.getRows());
        List<TradingPlatformBaseInfo> result = tradingPlatformBaseService.findBySearch(search);
        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), result);
    }

    @Override
    public TradingPlatformDto queryById(Long id) {
        return tradingPlatformBaseService.findDetailInfoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveTradingPlatform(Boolean confirmed, TradingPlatformDto tradingPlatformDto) {
        if (tradingPlatformDto.getId() == null) {
            String tradePlatformCode = serialNumberGenerator.nextValue(ConstantUtil.TRADE_PLATFORM);
            tradingPlatformDto.setPlatformCode(tradePlatformCode);
            this.checkParams(confirmed, tradingPlatformDto);
        } else {
            if (StrUtil.isEmpty(tradingPlatformDto.getPlatformCode())) {
                throw new ValidatorException(HttpStatus.ERROR, "平台编码不能为空！");
            }
            this.checkParams(true, tradingPlatformDto);
        }
        return save(tradingPlatformDto);
    }

    private Long save(TradingPlatformDto tradingPlatformDto) {
        TradingPlatform tradingPlatform = new TradingPlatform();
        BeanUtils.copyProperties(tradingPlatformDto, tradingPlatform, "createBy", "gmtCreate", "updateBy", "gmtModified");
        tradingPlatformBaseService.saveOrUpdate(tradingPlatform);

        TradingPlatformInsuranceDto insuranceDto = tradingPlatformDto.getInsurance();
        if (insuranceDto != null) {
            TradingPlatformInsurance tradePlatformInsurance = new TradingPlatformInsurance();
            BeanUtils.copyProperties(insuranceDto, tradePlatformInsurance, "id", "createBy", "gmtCreate", "updateBy", "gmtModified");
            tradePlatformInsurance.setPlatformId(tradingPlatform.getId());
            tradePlatformInsurance.setPlatformCode(tradingPlatform.getPlatformCode());
            TradingPlatformInsurance rawOne = tradingPlatformInsuranceBaseSService.findByPlatformId(tradingPlatform.getId());
            if (rawOne != null) {
                tradePlatformInsurance.setId(rawOne.getId());
            }
            tradingPlatformInsuranceBaseSService.saveOrUpdate(tradePlatformInsurance);
        }
        TradingPlatformQualificationDto qualificationDto = tradingPlatformDto.getQualification();
        if (qualificationDto != null) {
            TradingPlatformQualification tradingPlatformQualification = transStruct.transDto2TradingPlatformQualification(qualificationDto);
            tradingPlatformQualification.setPlatformId(tradingPlatform.getId());
            tradingPlatformQualification.setPlatformCode(tradingPlatform.getPlatformCode());
            TradingPlatformQualification rawOne = tradingPlatformQualificationBaseService.findByPlatformId(tradingPlatform.getId());
            if (rawOne != null) {
                tradingPlatformQualification.setId(rawOne.getId());
            }
            tradingPlatformQualificationBaseService.saveOrUpdate(tradingPlatformQualification);
            if (qualificationDto.getCommoditySpecialQualification() != null) {
                BusinessRelateFile commoditySpecialLicense = Builder.of(BusinessRelateFile.class)
                        .with(BusinessRelateFile::setBelongId, tradingPlatform.getId())
                        .with(BusinessRelateFile::setBelongType, ConstantUtil.TRADING_PLATFORM)
                        .with(BusinessRelateFile::setFileType, FileTypeEnum.COMMODITY_SPECIAL_LICENSE.getCode())
                        .with(BusinessRelateFile::setFileId, qualificationDto.getCommoditySpecialQualification().getId())
                        .build();
                businessRelateFileBaseService.upsertBusinessRelateFiles(commoditySpecialLicense);
            }
        }

        return tradingPlatform.getId();
    }

    private void checkParams(Boolean confirmed, TradingPlatformDto tradingPlatformDto) {
        if (confirmed) {
            ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, tradingPlatformDto);
            if (tradingPlatformDto.getInsurance() != null) {
                ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, tradingPlatformDto.getInsurance());
            }
            if (tradingPlatformDto.getQualification() == null) {
                throw new ValidatorException(HttpStatus.ERROR, "贸易平台的资质信息不能为空！");
            }
            ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, tradingPlatformDto.getQualification());
            if (DictConstants.SYS_YES.equals(tradingPlatformDto.getHasSinosureInsurance()) && tradingPlatformDto.getInsurance() == null) {
                throw new ValidatorException(HttpStatus.ERROR, "贸易平台的保险信息不能为空！");
            }
        } else {
            ValidatorUtil.validator(ValidatorGroup.ValidatorType.ADD, tradingPlatformDto);
            if (tradingPlatformDto.getInsurance() != null) {
                ValidatorUtil.validator(ValidatorGroup.ValidatorType.ADD, tradingPlatformDto.getInsurance());
            }
            if (tradingPlatformDto.getQualification() != null) {
                ValidatorUtil.validator(ValidatorGroup.ValidatorType.ADD, tradingPlatformDto.getQualification());
            }
        }
    }

}

