/*
 * 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 com.unis.financialSupervision.modular.bizFsSettleDataCheck.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.basic.info.modular.enumInfo.entity.BasicEnum;
import com.unis.basic.info.modular.enumInfo.mapper.BasicEnumMapper;
import com.unis.basic.info.modular.orgInfo.entity.OrgInfo;
import com.unis.basic.info.modular.orgInfo.mapper.OrgInfoMapper;
import com.unis.common.util.OrderNumberUtil;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.param.*;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.vo.BizFsSettleDataCheckDetailVO;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.vo.BizFsSettleDataCheckPageVO;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.vo.BusinessContractDetailVO;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.vo.GetBusinessContractDetailVO;
import com.unis.financialSupervision.modular.bizFsSettleDataCheckItem.entity.BizFsSettleDataCheckItem;
import com.unis.financialSupervision.modular.bizFsSettleDataCheckItem.mapper.BizFsSettleDataCheckItemMapper;
import com.unis.financialSupervision.modular.businessContract.entity.BusinessContract;
import com.unis.financialSupervision.modular.businessContract.mapper.BusinessContractMapper;
import com.unis.financialSupervision.modular.businessContract.param.BusinessContractIdParam;
import com.unis.financialSupervision.modular.businessStoreWareDetail.entity.BusinessStoreWareDetail;
import com.unis.financialSupervision.modular.businessStoreWareDetail.mapper.BusinessStoreWareDetailMapper;
import com.vividsolutions.jts.operation.buffer.BufferBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.exception.CommonException;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.entity.BizFsSettleDataCheck;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.mapper.BizFsSettleDataCheckMapper;
import com.unis.financialSupervision.modular.bizFsSettleDataCheck.service.BizFsSettleDataCheckService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 清算数据提取及业务处室核验Service接口实现类
 *
 * @author hjc
 * @date 2024/07/01 10:37
 **/
@Service
public class BizFsSettleDataCheckServiceImpl extends ServiceImpl<BizFsSettleDataCheckMapper, BizFsSettleDataCheck> implements BizFsSettleDataCheckService {

    @Autowired
    private BizFsSettleDataCheckMapper bizFsSettleDataCheckMapper;

    @Autowired
    private OrgInfoMapper orgInfoMapper;

    @Autowired
    private BusinessContractMapper businessContractMapper;

    @Autowired
    private BusinessStoreWareDetailMapper businessStoreWareDetailMapper;

    @Autowired
    private BasicEnumMapper basicEnumMapper;

    @Autowired
    private BizFsSettleDataCheckItemMapper bizFsSettleDataCheckItemMapper;


    @Override
    public Page<BizFsSettleDataCheckPageVO> page(BizFsSettleDataCheckPageParam pageParam) {

        Page<BizFsSettleDataCheckPageVO> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        return bizFsSettleDataCheckMapper.selectMyPage(page, pageParam.getOrgName());

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizFsSettleDataCheckAddParam bizFsSettleDataCheckAddParam) {
        //生成贷款单号
        String s = OrderNumberUtil.frontData("DKXX", 3, 1);
        BizFsSettleDataCheck bizFsSettleDataCheck = BeanUtil.toBean(bizFsSettleDataCheckAddParam, BizFsSettleDataCheck.class);
        bizFsSettleDataCheck.setLoanNumber(s);
        this.save(bizFsSettleDataCheck);

        List<BusinessContractIdParam> list = bizFsSettleDataCheckAddParam.getBusinessContractIdList();
        if (CollectionUtil.isNotEmpty(list)) {
            for (BusinessContractIdParam idParam : list) {
                BizFsSettleDataCheckItem bizFsSettleDataCheckItem = new BizFsSettleDataCheckItem();
                bizFsSettleDataCheckItem.setFsSettleDataCheckId(bizFsSettleDataCheck.getId());
                bizFsSettleDataCheckItem.setContractId(idParam.getId());
                bizFsSettleDataCheckItemMapper.insert(bizFsSettleDataCheckItem);
            }
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizFsSettleDataCheckEditParam bizFsSettleDataCheckEditParam) {
        BizFsSettleDataCheck bizFsSettleDataCheck = this.queryEntity(bizFsSettleDataCheckEditParam.getId());
        BeanUtil.copyProperties(bizFsSettleDataCheckEditParam, bizFsSettleDataCheck);
        this.updateById(bizFsSettleDataCheck);
    }

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

    @Override
    public BizFsSettleDataCheckDetailVO detail(BizFsSettleDataCheckIdParam bizFsSettleDataCheckIdParam) {


        return null;
    }

    @Override
    public BizFsSettleDataCheck queryEntity(String id) {
        BizFsSettleDataCheck bizFsSettleDataCheck = this.getById(id);
        if (ObjectUtil.isEmpty(bizFsSettleDataCheck)) {
            throw new CommonException("清算数据提取及业务处室核验不存在，id值为：{}", id);
        }
        return bizFsSettleDataCheck;
    }

    /**
     * 清算数据提取及业务处室核验-核验
     *
     * @author hjc
     * @date 2024/07/01 10:37
     */
    @Override
    public void verification(VerificationParam param) {
        BizFsSettleDataCheck bizFsSettleDataCheck = this.queryEntity(param.getId());
        bizFsSettleDataCheck.setCheckStatus(1);
        this.updateById(bizFsSettleDataCheck);
    }

    /**
     * 获取库区名称
     *
     * @author hjc
     * @date 2024/07/01 10:37
     */
    @Override
    public List<OrgInfo> getOrgInfo() {
        return orgInfoMapper.selectList(null);
    }

    /**
     * 获取合同编号
     *
     * @author hjc
     * @date 2024/07/01 10:37
     */
    @Override
    public List<BusinessContract> getBusinessContract() {
        return businessContractMapper.selectList(new LambdaQueryWrapper<BusinessContract>()
                .eq(BusinessContract::getAuditState, 2));
    }

    /**
     * 通过合同id获取品种，数量，单价，价款
     *
     * @author hjc
     * @date 2024/07/01 10:37
     */
    @Override
    public GetBusinessContractDetailVO getBusinessContractDetail(BizFsSettleDataCheckIdParam param) {

        GetBusinessContractDetailVO vo = new GetBusinessContractDetailVO();
        List<BusinessStoreWareDetail> businessStoreWareDetailList = businessStoreWareDetailMapper.selectList(
                new LambdaQueryWrapper<BusinessStoreWareDetail>()
                        .eq(BusinessStoreWareDetail::getZid, param.getId())
                        .eq(BusinessStoreWareDetail::getType, "contract"));
        if (CollectionUtil.isNotEmpty(businessStoreWareDetailList)) {
            List<String> grainKindNameList = new ArrayList<>();
            List<Double> inCountList = new ArrayList<>();
            List<Double> totalPriceList = new ArrayList<>();
            for (BusinessStoreWareDetail businessStoreWareDetail : businessStoreWareDetailList) {
                //获取品种信息
                BasicEnum basicEnum = basicEnumMapper.selectById(businessStoreWareDetail.getGrainKind());
                grainKindNameList.add(basicEnum.getEnumname());

                //获取数量
                inCountList.add(Double.valueOf(businessStoreWareDetail.getInCount()));
                //获取总价款
                // Double totalPrice = Double.parseDouble(businessStoreWareDetail.getInCount()) * Double.parseDouble(businessStoreWareDetail.getInPrice());
                totalPriceList.add(Double.valueOf(businessStoreWareDetail.getInDetailTotalPrice()));
            }

            //拼接并设置品种
            String grainKindNames = String.join(",", grainKindNameList);
            vo.setGrainKindName(grainKindNames);
            //求数量总和
            Double inCount = inCountList.stream().reduce(Double::sum).orElse(0.0);
            vo.setInCount(String.valueOf(inCount));
            Double totalPrices = totalPriceList.stream().reduce(Double::sum).orElse(0.0);
            vo.setInDetailTotalPrice(String.valueOf(totalPrices));
        }

        return vo;

    }

    /**
     * 清算数据生成-分页
     *
     * @author hjc
     * @date 2024/07/01 10:37
     */
    @Override
    public Page<BizFsSettleDataCheckPageVO> liquidationPage(liquidationPageParam pageParam) {
        Page<BizFsSettleDataCheckPageVO> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        return bizFsSettleDataCheckMapper.liquidationPage(page, pageParam.getOrgName());

    }

    /**
     * 清算核定及确认-分页
     *
     * @author hjc
     * @date 2024/07/01 10:37
     */
    @Override
    public Page<BizFsSettleDataCheckPageVO> checkLiquidationPage(CheckLiquidationPageParam pageParam) {
        Page<BizFsSettleDataCheckPageVO> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
        return bizFsSettleDataCheckMapper.liquidationPage(page, pageParam.getOrgName());
    }

    /**
     * 清算核定及确认-一键清算
     *
     * @author hjc
     * @date 2024/07/01 10:37
     */
    @Override
    public void checkClearStatus(VerificationParam param) {
        BizFsSettleDataCheck bizFsSettleDataCheck = bizFsSettleDataCheckMapper.selectById(param.getId());
        bizFsSettleDataCheck.setClearStatus(1);
        this.updateById(bizFsSettleDataCheck);
    }

    @Override
    public JSONObject getDetailJSON(BizFsSettleDataCheckIdParam bizFsSettleDataCheckIdParam) {

        JSONObject jsonObject = new JSONObject();
        //获取清算数据提取及业务处室核验
        BizFsSettleDataCheck bizFsSettleDataCheck = this.queryEntity(bizFsSettleDataCheckIdParam.getId());
        //获取库区信息
        OrgInfo orgInfo = orgInfoMapper.selectById(bizFsSettleDataCheck.getOrgId());
        bizFsSettleDataCheck.setOrgName(orgInfo.getOrgName());
        jsonObject.put("bizFsSettleDataCheck", bizFsSettleDataCheck);

        //获取合同信息
        List<BizFsSettleDataCheckItem> bizFsSettleDataCheckItemList = bizFsSettleDataCheckItemMapper.selectList(new LambdaQueryWrapper<BizFsSettleDataCheckItem>()
                .eq(BizFsSettleDataCheckItem::getFsSettleDataCheckId, bizFsSettleDataCheck.getId()));
        List<Integer> contractIdList = bizFsSettleDataCheckItemList.stream().map(BizFsSettleDataCheckItem::getContractId).collect(Collectors.toList());
        List<BusinessContractDetailVO> list = new ArrayList<>();
        for (Integer contractId : contractIdList) {

            BusinessContractDetailVO vo = new BusinessContractDetailVO();

            List<String> grainKindNameList = new ArrayList<>();
            List<Double> inCountList = new ArrayList<>();
            List<Double> totalPriceList = new ArrayList<>();
            //获取合同
            BusinessContract businessContract = businessContractMapper.selectById(contractId);
            vo.setContractNumber(businessContract.getContractNumber());

            //获取合同详情
            List<BusinessStoreWareDetail> businessStoreWareDetailList = businessStoreWareDetailMapper.selectList(
                    new LambdaQueryWrapper<BusinessStoreWareDetail>()
                            .eq(BusinessStoreWareDetail::getZid, contractId)
                            .eq(BusinessStoreWareDetail::getType, "contract"));
            if (CollectionUtil.isNotEmpty(businessStoreWareDetailList)) {

                for (BusinessStoreWareDetail businessStoreWareDetail : businessStoreWareDetailList) {
                    //获取品种信息
                    BasicEnum basicEnum = basicEnumMapper.selectById(businessStoreWareDetail.getGrainKind());
                    grainKindNameList.add(basicEnum.getEnumname());

                    //获取数量
                    inCountList.add(Double.valueOf(businessStoreWareDetail.getInCount()));
                    //获取总价款
                    // Double totalPrice = Double.parseDouble(businessStoreWareDetail.getInCount()) * Double.parseDouble(businessStoreWareDetail.getInPrice());
                    totalPriceList.add(Double.valueOf(businessStoreWareDetail.getInDetailTotalPrice()));
                }

                //拼接并设置品种
                String grainKindNames = String.join(",", grainKindNameList);
                vo.setGrainKindName(grainKindNames);
                //求数量总和
                Double inCount = inCountList.stream().reduce(Double::sum).orElse(0.0);
                vo.setInCount(String.valueOf(inCount));
                Double totalPrices = totalPriceList.stream().reduce(Double::sum).orElse(0.0);
                vo.setInDetailTotalPrice(String.valueOf(totalPrices));
                list.add(vo);
            }

        }
        jsonObject.put("BusinessContractVO", list);

        return jsonObject;
    }
}
