/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.depotGrainInfo.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotGrainInfo.file.DepotGrainInfoFile;
import vip.xiaonuo.biz.modular.depotGrainInfo.param.*;
import vip.xiaonuo.biz.modular.depotGrainInfoPrice.service.DepotGrainInfoPriceService;
import vip.xiaonuo.biz.modular.depotGrainInfoWarn.service.DepotGrainInfoWarnService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotGrainInfo.entity.DepotGrainInfo;
import vip.xiaonuo.biz.modular.depotGrainInfo.mapper.DepotGrainInfoMapper;
import vip.xiaonuo.common.prop.CommonProperties;
import vip.xiaonuo.common.util.BeanCopyUtil;
import vip.xiaonuo.common.util.BigDecimalUtil;
import vip.xiaonuo.dev.api.DevFileApi;
import vip.xiaonuo.dev.modular.file.entity.DevFile;
import vip.xiaonuo.dev.modular.file.enums.DevFileEngineTypeEnum;
import vip.xiaonuo.dev.modular.file.param.DevFileListParam;
import vip.xiaonuo.dev.modular.file.service.DevFileService;
import vip.xiaonuo.sys.modular.relation.entity.SysRelation;
import vip.xiaonuo.sys.modular.relation.enums.SysRelationCategoryEnum;
import vip.xiaonuo.sys.modular.relation.service.SysRelationService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 企业客户信息表Service接口实现类
 *
 * @author xiang
 * @date 2023/09/14 15:00
 **/
@Service
public class DepotGrainInfoService extends ServiceImpl<DepotGrainInfoMapper, DepotGrainInfo> {

    @Resource
    DepotGrainService depotGrainService;
    @Resource
    private SysRelationService sysRelationService;
    @Resource
    private DevFileService devFileService;
    @Resource
    private DevFileApi devFileApi;
    @Resource
    private DepotGrainInfoPriceService grainInfoPriceService;
    @Resource
    private DepotGrainInfoWarnService depotGrainInfoWarnService;
    @Resource
    private CommonProperties commonProperties;

    public Page<DepotGrainInfo> page(DepotGrainInfoPageParam param) {
        QueryWrapper<DepotGrainInfo> queryWrapper = new QueryWrapper<>();
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        queryWrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotGrainInfo::getDepotId, depotIdLst);
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            queryWrapper.lambda().eq(DepotGrainInfo::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getContractCode())) {
            queryWrapper.lambda().like(DepotGrainInfo::getContractCode, param.getContractCode());
        }
        if (ObjectUtil.isNotEmpty(param.getAddressCity())) {
            if (param.getAddressCity().contains("市"))
                param.setAddressCity(param.getAddressCity().replaceAll("市", ""));
            queryWrapper.lambda().like(DepotGrainInfo::getAddressCity, param.getAddressCity());
        }
        if (ObjectUtil.isNotEmpty(param.getAddressCounty())) {
            queryWrapper.lambda().like(DepotGrainInfo::getAddressCounty, param.getAddressCounty());
        }
        if (ObjectUtil.isNotEmpty(param.getAddressTown())) {
            queryWrapper.lambda().like(DepotGrainInfo::getAddressTown, param.getAddressTown());
        }
        if (ObjectUtil.isNotEmpty(param.getLoanEndDate())) {
            queryWrapper.lambda().eq(DepotGrainInfo::getLoanEndDate, param.getLoanEndDate());
        }
        if (ObjectUtil.isNotEmpty(param.getCreditCode())) {
            queryWrapper.lambda().like(DepotGrainInfo::getCreditCode, param.getCreditCode());
        }
        if (ObjectUtil.isAllNotEmpty(param.getSortField(), param.getSortOrder())) {
            CommonSortOrderEnum.validate(param.getSortOrder());
            queryWrapper.orderBy(true, param.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(param.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(DepotGrainInfo::getId);
        }
        Page<DepotGrainInfo> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        //匹配种类价格
        grainInfoPriceService.putPrice(page.getRecords());
        return page;
    }

    /**
     * 企业客户信息表列表
     *
     * @author xiang
     * @date 2023/09/14 15:00
     **/
    public List<DepotGrainInfo> list(DepotGrainInfoPageParam param) {
        List<DepotGrainInfo> list = lst(param);
        //匹配粮库名称
        depotGrainService.putDepotName(list);
        return list;
    }

    public List<DepotGrainInfo> listByDepotId(String depotId) {
        LambdaQueryWrapper<DepotGrainInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DepotGrainInfo::getDepotId, depotId);
        return list(wrapper);
    }

    /**
     * 企业客户信息表列表
     *
     * @author xiang
     * @date 2023/09/14 15:00
     **/
    public List<DepotGrainInfo> lst(DepotGrainInfoPageParam param) {
        LambdaQueryWrapper<DepotGrainInfo> wrapper = new LambdaQueryWrapper<>(BeanUtil.toBean(param, DepotGrainInfo.class));
        param.setDepotIdLst(param.getDepotIdLst() != null && param.getDepotIdLst().isEmpty() ? depotGrainService.lstOrgGrep(param.getLoginFlag()) : param.getDepotIdLst());
        wrapper.in(CollUtil.isNotEmpty(param.getDepotIdLst()), DepotGrainInfo::getDepotId, param.getDepotIdLst());
        return list(wrapper);
    }

    /**
     * 企业客户信息
     *
     * @author xiang
     * @date 2023/09/14 15:00
     **/
    public DepotGrainInfo oneByDepotId(String depotId) {
        return getOne(new LambdaQueryWrapper<>(new DepotGrainInfo(depotId)));
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(DepotGrainInfoAddParam param) {
        checkInfo(new DepotGrainInfo(null, param.getDepotId(), param.getContractCode()));
        grainInfoPriceService.editPriceChildren(param.getPriceChildren(), param.getDepotId());
        DepotGrainInfo depotGrainInfo = BeanUtil.toBean(param, DepotGrainInfo.class);
        depotGrainInfo.setLoanBalance(depotGrainInfo.getLoanLimit());
        this.save(depotGrainInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(DepotGrainInfoEditParam param) {
        checkInfo(new DepotGrainInfo(param.getId(), null, param.getContractCode()));
        DepotGrainInfo info = this.queryEntity(param.getId());
        String loanEndDate = info.getLoanEndDate();
        //粮食种类价格修改
        grainInfoPriceService.editPriceChildren(param.getPriceChildren(), info.getDepotId());
        if (info.getLoanBalance() == null)
            info.setLoanBalance(BigDecimal.ZERO);
        if (info.getLoanSum() == null)
            info.setLoanSum(BigDecimal.ZERO);
        if (param.getLoanLimit() != null && param.getLoanLimit().compareTo(info.getLoanBalance()) != 0) {
            info.setLoanBalance(param.getLoanLimit().subtract(info.getLoanSum()));
        }
        BeanUtil.copyProperties(param, info);
        this.updateById(info);
        if (Strings.isNotBlank(info.getLoanEndDate()) && !Objects.equals(loanEndDate, info.getLoanEndDate()))
            depotGrainInfoWarnService.loanDateWarns(info.getDepotId());
    }

    private void checkInfo(DepotGrainInfo info) {
        List<DepotGrainInfo> infos = lst(new DepotGrainInfoPageParam());
        for (DepotGrainInfo one : infos) {
            if (Objects.equals(info.getId(), one.getId()))
                continue;
            if (Objects.equals(info.getDepotId(), one.getDepotId()))
                throw new CommonException("重复的企业客户档案❗");
            if (Objects.equals(info.getContractCode(), one.getContractCode()))
                throw new CommonException("重复的企业客户合同号❗");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotGrainInfoIdParam> depotGrainInfoIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(depotGrainInfoIdParamList, DepotGrainInfoIdParam::getId));
    }

    public DepotGrainInfo detail(DepotGrainInfo param) {
        DepotGrainInfo info = null;
        if (Strings.isNotBlank(param.getId())) {
            info = this.queryEntity(param.getId());
        } else if (Strings.isNotBlank(param.getDepotId())) {
            info = oneByDepotId(param.getDepotId());
        } else {
            List<String> depotIdLst = depotGrainService.lstOrgGrep();
            if (depotIdLst.size() == 1)
                info = oneByDepotId(depotIdLst.get(0));
        }
        if (info != null) {
            info.setDepotGrainName(depotGrainService.getNameByDepotId(info.getDepotId()));
            info.setPriceChildren(grainInfoPriceService.lstPriceChildren(info.getDepotId()));
        }
        return info;
    }

    public DepotGrainInfo detail(DepotGrainInfoIdParam depotGrainInfoIdParam) {
        DepotGrainInfo info = this.queryEntity(depotGrainInfoIdParam.getId());
        info.setPriceChildren(grainInfoPriceService.lstPriceChildren(info.getDepotId()));
        return info;
    }

    public DepotGrainInfo queryEntity(String id) {
        DepotGrainInfo depotGrainInfo = this.getById(id);
        if (ObjectUtil.isEmpty(depotGrainInfo)) {
            depotGrainInfo = oneByDepotId(id);
            if (depotGrainInfo == null)
                throw new CommonException("企业客户信息表不存在，id值为：{}", id);
        }
        depotGrainInfo.setDepotGrainName(depotGrainService.getNameByDepotId(depotGrainInfo.getDepotId()));
        return depotGrainInfo;
    }

    /**
     * 上传文件
     *
     * @author xiang
     * @date 2023-01-01
     */
    public void fileUpload(MultipartFile file, String id) {
        String fileId = devFileService.uploadReturnId(DevFileEngineTypeEnum.LOCAL.getValue(), file);
        bindFileUpload(new DepotGrainInfoFileParam(id, fileId, 1));
    }

    /**
     * 获取上传文件
     *
     * @author xiang
     * @date 2023-01-01
     */
    public List<DepotGrainInfoFile> fileLst(String depotId) {
        List<String> fileIdLst = sysRelationService.getRelationTargetIdListByObjectIdAndCategory(depotId, SysRelationCategoryEnum.SYS_DEPOT_INFO_HAS_FILE.getValue());
        if (fileIdLst.isEmpty()) return null;
        List<DevFile> files = devFileService.list(new DevFileListParam(fileIdLst));
        List<DepotGrainInfoFile> depotGrainInfoFiles = BeanCopyUtil.copyListProperties(files, DepotGrainInfoFile::new);
        depotGrainInfoFiles.forEach(f -> {
            String url = devFileApi.storageFilePathReturnUrl(f.getStoragePath());
            f.setFileUrl(StringUtils.join(commonProperties.getBackendUrl(), url));
            f.setKkFileUrl(StringUtils.join(commonProperties.getKkFileUrl(), url));
        });
        return depotGrainInfoFiles;
    }

    /**
     * 绑定文件
     *
     * @author xiang
     * @date 2023-01-01
     */
    public void bindFileUpload(DepotGrainInfoFileParam fileParam) {
        //绑定
        if (Objects.equals(fileParam.getFileState(), 1)) {
            sysRelationService.saveRelationWithAppend(fileParam.getId(), fileParam.getFileId(), SysRelationCategoryEnum.SYS_DEPOT_INFO_HAS_FILE.getValue());
        }
        //解绑
        else {
            List<SysRelation> lst = sysRelationService.getRelationListByTargetIdAndCategory(fileParam.getFileId(), SysRelationCategoryEnum.SYS_DEPOT_INFO_HAS_FILE.getValue());
            sysRelationService.removeBatchByIds(lst.stream().map(SysRelation::getId).collect(Collectors.toList()));
        }
    }

    /**
     * 新增入库
     *
     * @param tonAddCount 公斤
     * @author xiang
     * @date 2023-01-01
     */
    public void inInventory(String depotId, BigDecimal tonAddCount, BigDecimal orderAmount) {
        DepotGrainInfo info = oneByDepotId(depotId);
        //库存量
        info.setDepotCount(BigDecimalUtil.addVal(info.getDepotCount(), tonAddCount.movePointLeft(4)));
        //新增入库量
        info.setTonInCount(BigDecimalUtil.addVal(info.getTonInCount(), tonAddCount));
        //新增车量
        info.setTruckInCount(BigDecimalUtil.addVal(info.getTruckInCount(), BigDecimal.ONE));
        //入库交易额
        info.setInAmount(BigDecimalUtil.addVal(info.getInAmount(), orderAmount));
        this.updateById(info);
    }

    /**
     * 新增入库申请
     *
     * @param info              客户
     * @param tonInCheckCount   申请数量
     * @param truckInCheckCount 申请车辆
     * @author xiang
     * @date 2023/09/14 15:00
     **/
    @Transactional(rollbackFor = Exception.class)
    public void loanSyncCheck(DepotGrainInfo info, BigDecimal tonInCheckCount, BigDecimal truckInCheckCount) {
        //待申请数量
        info.setTonInCount(BigDecimalUtil.addVal(info.getTonInCount(), tonInCheckCount.negate()));
        //待申请车量
        info.setTruckInCount(BigDecimalUtil.addVal(info.getTruckInCount(), truckInCheckCount.negate()));
        //待审批数量
        info.setTonInCheckCount(BigDecimalUtil.addVal(info.getTonInCheckCount(), tonInCheckCount));
        this.updateById(info);
    }

    /**
     * 审批入库申请
     *
     * @param depotId       客户id
     * @param grainGroup    粮食种类
     * @param loanSum       放款金额
     * @param mortgageCount 质押吨数
     * @author xiang
     * @date 2023/09/14 15:00
     **/
    @Transactional(rollbackFor = Exception.class)
    public void loanSync(String depotId, String grainGroup, BigDecimal loanSum, BigDecimal mortgageCount) {
        DepotGrainInfo info = oneByDepotId(depotId);
        //贷款金额
        info.setLoanSum(BigDecimalUtil.addVal(info.getLoanSum(), loanSum));
        //贷款余额
        info.setLoanBalance(BigDecimalUtil.addVal(info.getLoanLimit(), info.getLoanSum().negate()));
        //已质押库存数(万吨)
        info.setMortgageCount(BigDecimalUtil.addVal(info.getMortgageCount(), mortgageCount.movePointLeft(4)));
        //待审批量
        info.setTonInCheckCount(BigDecimalUtil.addVal(info.getTonInCheckCount(), mortgageCount.negate()));
        //累计贷款金额
        info.setLoanSumTotal(BigDecimalUtil.addVal(info.getLoanSumTotal(), loanSum));
        //累计质押库存数(万吨)
        info.setMortgageCountTotal(BigDecimalUtil.addVal(info.getMortgageCountTotal(), mortgageCount.movePointLeft(4)));
        this.updateById(info);
        grainInfoPriceService.loanSync(depotId, grainGroup, mortgageCount);
    }

    /**
     * 审批出库申请
     *
     * @param depotId        客户id
     * @param repayPrincipal 还款金额
     * @param repayInterest  还款利息
     * @param repayCount     还款吨数
     * @author xiang
     * @date 2023/09/14 15:00
     **/
    @Transactional(rollbackFor = Exception.class)
    public void repaySync(String depotId, BigDecimal repayPrincipal, BigDecimal repayInterest, BigDecimal repayCount, String grainGroup) {
        DepotGrainInfo info = oneByDepotId(depotId);
        //贷款金额
        info.setLoanSum(BigDecimalUtil.addVal(info.getLoanSum(), repayPrincipal.negate()));
        //贷款余额
        info.setLoanBalance(BigDecimalUtil.addVal(info.getLoanLimit(), info.getLoanSum().negate()));
        //贷款利息
        info.setLoanInterest(BigDecimalUtil.addVal(info.getLoanInterest(), repayInterest));
        //已质押库存数(万吨)
        info.setMortgageCount(BigDecimalUtil.addVal(info.getMortgageCount(), repayCount.negate().movePointLeft(4)));
        //已审批待出库
        info.setTonOutFinishCount(BigDecimalUtil.addVal(info.getTonOutFinishCount(), repayCount));
        //累计还款金额
        info.setRepaySumTotal(BigDecimalUtil.addVal(info.getRepaySumTotal(), repayPrincipal));
        this.updateById(info);

        //粮食种类 已质押库存数(万吨)
        grainInfoPriceService.subStorage(depotId, repayCount, grainGroup);
    }

    /**
     * 出库
     *
     * @param realWeight 重量(吨)
     * @param realAmount 交易金额
     * @author xiang
     * @date 2023-01-01
     */
    public void outInventory(String depotId, BigDecimal realWeight, BigDecimal realAmount) {
        DepotGrainInfo info = oneByDepotId(depotId);
        //库存量
        info.setDepotCount(BigDecimalUtil.addVal(info.getDepotCount(), realWeight.negate().movePointLeft(4)));
        //已审批待出库
        info.setTonOutFinishCount(BigDecimalUtil.addVal(info.getTonOutFinishCount(), realWeight.negate()));
        //出库交易额
        info.setOutAmount(BigDecimalUtil.addVal(info.getOutAmount(), realAmount));
        this.updateById(info);
    }

    /**
     * 还款额校验
     *
     * @param depotId  粮库
     * @param repaySum 还款额
     * @author xiang
     * @date 2023-01-01
     */
    public void loanSumCheck(String depotId, BigDecimal repaySum) {
        DepotGrainInfo info = oneByDepotId(depotId);
        if (repaySum.doubleValue() > info.getLoanSum().doubleValue())
            throw new CommonException(String.format("还款金额(%s) 已经超出贷款金额(%s)", repaySum, info.getLoanSum()));
    }

}
