package com.xy.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.collections.list.JArrayList;
import com.xy.dto.*;
import com.xy.dto.be.MercDto;
import com.xy.entity.DeviceAlgorithmChargingHistory;
import com.xy.mapper.DeviceAlgorithmChargingHistoryMapper;
import com.xy.service.be.MercService;
import com.xy.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

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

import static com.xy.utils.Beans.copy;
import static com.xy.utils.PlusBeans.toIPage;
import static com.xy.utils.PlusBeans.toPageBean;

/**
 * <p>
 * 设备算法计费历史表 服务实现类
 * </p>
 *
 * @author lijin
 * @since 2023-06-29
 */
@Service
@AllArgsConstructor
@Api(tags = "设备算法计费历史表")
public class DeviceAlgorithmChargingHistoryServiceImpl extends ServiceImpl<DeviceAlgorithmChargingHistoryMapper, DeviceAlgorithmChargingHistory> implements DeviceAlgorithmChargingHistoryService {

    private OrderMercManageService orderMercManageService;
    private MercService mercService;
    private DeviceTypeAlgorithmBeforConfigServiceImpl deviceTypeAlgorithmBeforConfigService;
    private DeviceInfoService deviceInfoService;
    private MercFeeConfigService mercFeeConfigService;


    @Override
    @ApiOperation("分页查询")
    public R<PageBean<DeviceAlgorithmChargingHistoryDto.Vo>> page(@RequestBody DeviceAlgorithmChargingHistoryDto.Page page) {
        LambdaQueryWrapper<DeviceAlgorithmChargingHistory> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, DeviceAlgorithmChargingHistory.class).build();
        IPage<DeviceAlgorithmChargingHistory> iPage = page(PlusBeans.toIPage(page.getPage()), lambdaQueryWrapper);
        PageBean<DeviceAlgorithmChargingHistoryDto.Vo> pageBean = toPageBean(DeviceAlgorithmChargingHistoryDto.Vo.class, iPage);
        List<DeviceAlgorithmChargingHistoryDto.Vo> records = pageBean.getRecords();
        if (Emptys.check(records)) {
            copy(records).target(
                    () -> orderMercManageService.list(new OrderMercManageDto.SelectList().setId(new JArrayList<>(records).getProperty(DeviceAlgorithmChargingHistoryDto.Vo::getOrderId))).getData()
                    , DeviceAlgorithmChargingHistoryDto.Vo::getOrderId, DeviceAlgorithmChargingHistoryDto.Vo::getFiles, OrderMercManageDto.Vo::getId, OrderMercManageDto.Vo::getFiles
            ).builder();
        }
        return R.ok(pageBean);
    }

    public R<PageBean<DeviceAlgorithmChargingHistoryDto.PageByTopMercVO>> pageByTopMerc(DeviceAlgorithmChargingHistoryDto.PageByTopMerc page) {
        Long curMercId = page.getCurMercId();
        Long chooseMercId = page.getChooseMercId();
        List<Long> mercIds = new ArrayList<>();
        if (chooseMercId == null) {
            mercIds = R.feignCheckData(mercService.getChildMercIds(new MercDto.QuerySubDTO().setParentMercID(curMercId)));
        } else {
            // 指定商户ID
            mercIds.add(chooseMercId);
        }
        if (CollUtil.isEmpty(mercIds)) {
            return R.ok();
        }
        PageBean pageBean = page.getPage();
        LambdaQueryWrapper<DeviceAlgorithmChargingHistory> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, DeviceAlgorithmChargingHistory.class)
                .ge(DeviceAlgorithmChargingHistory::getCreateTime, page.getBeginCreateTime())
                .le(DeviceAlgorithmChargingHistory::getCreateTime, page.getEndCreateTime())
                .in(DeviceAlgorithmChargingHistory::getMercId, mercIds)
                .build()
                .orderByDesc(!Emptys.check(pageBean.getOrders()), DeviceAlgorithmChargingHistory::getCreateTime);
        IPage<DeviceAlgorithmChargingHistory> iPage = page(toIPage(pageBean), lambdaQueryWrapper);
        PageBean<DeviceAlgorithmChargingHistoryDto.PageByTopMercVO> voPageBean = toPageBean(DeviceAlgorithmChargingHistoryDto.PageByTopMercVO.class, iPage);
        List<DeviceAlgorithmChargingHistoryDto.PageByTopMercVO> records = voPageBean.getRecords();
        if (Emptys.check(records)) {
            // 佣金配置查询
            List<MercFeeConfigDto.ListFeeConfigByMercVO> feeConfigByMercVOS = R.feignCheckData(mercFeeConfigService.listFeeConfigByMerc(new MercFeeConfigDto.ListFeeConfigByMercDTO().setMercId(curMercId)));
            Map<Long, MercFeeConfigDto.ListFeeConfigByMercVO> configByMercVOMap = MapUtil.newHashMap();
            if (CollUtil.isNotEmpty(feeConfigByMercVOS)) {
                configByMercVOMap = feeConfigByMercVOS.stream().collect(Collectors.toMap(MercFeeConfigDto.ListFeeConfigByMercVO::getMercId, f -> f));
            }


            List<Long> deviceIds = records.stream().map(DeviceAlgorithmChargingHistoryDto.PageByTopMercVO::getDeviceId).distinct().collect(Collectors.toList());

            List<DeviceInfoDto.Vo> deviceList = R.feignCheckData(deviceInfoService.listCommon(new DeviceInfoDto.ListCommon().setDeviceIds(deviceIds)));
            Map<Long, DeviceInfoDto.Vo> devcieMap = deviceList.stream().collect(Collectors.toMap(DeviceInfoDto.Vo::getDeviceId, d -> d));
            copy(records)
                    .target(() -> orderMercManageService.list(new OrderMercManageDto.SelectList().setId(new JArrayList<>(records).getProperty(DeviceAlgorithmChargingHistoryDto.PageByTopMercVO::getOrderId))).getData()
                            , DeviceAlgorithmChargingHistoryDto.PageByTopMercVO::getOrderId, DeviceAlgorithmChargingHistoryDto.PageByTopMercVO::getFiles, OrderMercManageDto.Vo::getId, OrderMercManageDto.Vo::getFiles
                    ).target(() -> mercService.list(new MercDto.SelectList().setMercIds(new JArrayList<>(records).getProperty(DeviceAlgorithmChargingHistoryDto.PageByTopMercVO::getMercId).comparing())).getData()
                            , DeviceAlgorithmChargingHistoryDto.PageByTopMercVO::getMercId, DeviceAlgorithmChargingHistoryDto.PageByTopMercVO::getMercName, MercDto.Vo::getId, MercDto.Vo::getName)
                    .builder();
            for (DeviceAlgorithmChargingHistoryDto.PageByTopMercVO record : records) {
                // 初始0 佣金费用
                int extraMoney = 0;
                Long mercId = record.getMercId();
                MercFeeConfigDto.ListFeeConfigByMercVO listFeeConfigByMercVO = configByMercVOMap.get(mercId);
                if (listFeeConfigByMercVO != null) {
                    extraMoney = listFeeConfigByMercVO.getFeeConfig().getFeeActive();
                }
                record.setAgentMoney(extraMoney);
            }
        }
        return R.ok(voPageBean);

    }

    /**
     * 财务管理-支出管理-设备激活费明细
     *
     * @param page
     * @return
     */
    public R<PageBean<DeviceAlgorithmChargingHistoryDto.MySpendPageVO>> mySpendPage(DeviceAlgorithmChargingHistoryDto.PageByTopMerc page) {
        Long curMercId = page.getCurMercId();
        List<Long> mercIds = new ArrayList<>();
        // 指定商户ID
        mercIds.add(curMercId);
        PageBean pageBean = page.getPage();
        LambdaQueryWrapper<DeviceAlgorithmChargingHistory> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, DeviceAlgorithmChargingHistory.class)
                .ge(DeviceAlgorithmChargingHistory::getCreateTime, page.getBeginCreateTime())
                .le(DeviceAlgorithmChargingHistory::getCreateTime, page.getEndCreateTime())
                .in(DeviceAlgorithmChargingHistory::getMercId, mercIds)
                .build()
                .orderByDesc(!Emptys.check(pageBean.getOrders()), DeviceAlgorithmChargingHistory::getCreateTime);
        IPage<DeviceAlgorithmChargingHistory> iPage = page(toIPage(pageBean), lambdaQueryWrapper);
        PageBean<DeviceAlgorithmChargingHistoryDto.MySpendPageVO> voPageBean = toPageBean(DeviceAlgorithmChargingHistoryDto.MySpendPageVO.class, iPage);
        List<DeviceAlgorithmChargingHistoryDto.MySpendPageVO> records = voPageBean.getRecords();
        if (Emptys.check(records)) {
            List<OrderMercManageDto.Vo> orderMercManages = orderMercManageService.list(new OrderMercManageDto.SelectList().setId(new JArrayList<>(records).getProperty(DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getOrderId))).getData();
            copy(records)
                    .target(() -> orderMercManages, DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getOrderId, DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getFiles, OrderMercManageDto.Vo::getId, OrderMercManageDto.Vo::getFiles)
                    .target(() -> orderMercManages, DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getOrderId, DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getBalanceMone, OrderMercManageDto.Vo::getId, OrderMercManageDto.Vo::getBalanceMoney)
                    .target(() -> mercService.list(new MercDto.SelectList().setMercIds(new JArrayList<>(records).getProperty(DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getMercId).comparing())).getData()
                            , DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getMercId, DeviceAlgorithmChargingHistoryDto.MySpendPageVO::getMercName, MercDto.Vo::getId, MercDto.Vo::getName)
                    .builder();
        }
        return R.ok(voPageBean);

    }
}
