package com.xy.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xy.device.EnumAlgorithmPayConfig;
import com.xy.device.EnumAlgorithmTypes;
import com.xy.device.EnumDeviceCharging;
import com.xy.device.EnumDeviceChargingConfigType;
import com.xy.dto.*;
import com.xy.dto.be.MercDto;
import com.xy.entity.DeviceChargingConfig;
import com.xy.entity.DeviceTypeAlgorithmBeforConfig;
import com.xy.entity.MercFeeConfigAlgorithmType;
import com.xy.entity.SysDictRedis;
import com.xy.error.CommRuntimeException;
import com.xy.mapper.MercFeeConfigAlgorithmTypeMapper;
import com.xy.service.MercFeeConfigAlgorithmTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.service.be.MercService;
import com.xy.utils.*;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;

import java.util.*;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.validation.annotation.Validated;

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


/**
 * <p>
 * 商户算法扣费标准配置扩展 服务实现类
 * </p>
 *
 * @author 谭斌
 * @since 2024-04-07
 */
@Service
@AllArgsConstructor
@Api(tags = "商户算法扣费标准配置扩展")
public class MercFeeConfigAlgorithmTypeServiceImpl extends ServiceImpl<MercFeeConfigAlgorithmTypeMapper, MercFeeConfigAlgorithmType> implements MercFeeConfigAlgorithmTypeService {

    private MercService mercService;
    private AlgorithmService algorithmService;

    @PostMapping("obj")
    @ApiOperation("对象查询")
    public R<MercFeeConfigAlgorithmTypeDto.Vo> obj(@RequestBody MercFeeConfigAlgorithmTypeDto.Vo vo) {
        MercFeeConfigAlgorithmTypeDto.SelectList selectList = copy(MercFeeConfigAlgorithmTypeDto.SelectList.class, vo);
        List<MercFeeConfigAlgorithmTypeDto.Vo> list = list(selectList).getData();
        if (Emptys.check(list)) {
            return R.ok(list.get(0));
        }
        return R.ok();
    }

    @PostMapping("list")
    @ApiOperation("集合查询")
    public R<List<MercFeeConfigAlgorithmTypeDto.Vo>> list(@RequestBody MercFeeConfigAlgorithmTypeDto.SelectList selectList) {
        LambdaQueryWrapper<MercFeeConfigAlgorithmType> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(selectList, MercFeeConfigAlgorithmType.class).build();
        List<MercFeeConfigAlgorithmType> list = list(lambdaQueryWrapper);
        return R.ok(copy(MercFeeConfigAlgorithmTypeDto.Vo.class, list));
    }

    @Override
    @ApiOperation("设备算法费用配置查询")
    public R<MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmConfigVO> listByFeeConfig(@RequestBody @Validated MercFeeConfigAlgorithmTypeDto.ListByFeeConfigDTO dto) {
        MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmConfigVO data = new MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmConfigVO();
        Long mercId = dto.getMercId();
        MercDto.Vo merc = R.feignCheckData(mercService.obj(new MercDto.Vo().setId(mercId)));

        //查询默认算法信息
        //算法费-平台默认配置
        List<MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmPlatformVO> deviceAcPlatformList = new ArrayList<>();
        List<AlgorithmDto.ListNameId> listNameIds = R.feignCheckData(algorithmService.ListNameId());
        List<Long> algorithmIds = listNameIds.stream().map(AlgorithmDto.ListNameId::getId).collect(Collectors.toList());
//        Map<Long, String> agMap = listNameIds.stream().collect(Collectors.toMap(AlgorithmDto.ListNameId::getId, AlgorithmDto.ListNameId::getName));
        Map<Long, String> algorithmPayConfigMap = new HashMap<>();
        for (Long algorithmId : algorithmIds) {
            SysDictRedis moonAlgorithmTypes = SysDictUtils.get(EnumAlgorithmTypes.Code.CODE.getCode(), String.valueOf(algorithmId));
            //算法类型对应的字典配置的默认激活费（无设备类型）
            SysDictRedis algorithmPayConfig = SysDictUtils.get(EnumAlgorithmPayConfig.Code.CODE.getCode(), String.valueOf(algorithmId));
            if (Emptys.check(algorithmPayConfig)) {
                MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmPlatformVO dap = new MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmPlatformVO();
                dap.setAlgorithmId(algorithmId);
                DeviceAlgorithmChargingDto.AlgorithmMoonConfig algorithmMoonConfig = JSONUtil.parseObj(algorithmPayConfig.getValue()).toBean(DeviceAlgorithmChargingDto.AlgorithmMoonConfig.class);
//                DeviceAlgorithmChargingDto.AlgorithmMoonConfig.Inf inf = algorithmMoonConfig.getInf();
                DeviceAlgorithmChargingDto.AlgorithmMoonConfig.Moon moon = algorithmMoonConfig.getMoon();
                dap.setMoonMoney(moon.getMoney());
                dap.setMoonSize(moon.getSize());
                dap.setSingleMoney(algorithmMoonConfig.getPrice());
                deviceAcPlatformList.add(dap);
                algorithmPayConfigMap.put(algorithmId, algorithmPayConfig.getValue());
            }
        }

        // 设备管理费-商家自定义费用
        List<MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmMercVO> deviceAcMercList = new ArrayList<>();
        LambdaQueryWrapper<MercFeeConfigAlgorithmType> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(dto, MercFeeConfigAlgorithmType.class)
                .in(MercFeeConfigAlgorithmType::getAlgorithmId, algorithmIds)
                .eq(MercFeeConfigAlgorithmType::getMercCode, merc.getMercCode())
                .build();
        //默认配置 type 2预充 1赠送天数
        List<MercFeeConfigAlgorithmType> list = list(lambdaQueryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            for (MercFeeConfigAlgorithmType cfg : list) {
                MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmMercVO damVo = BeanUtil.copyProperties(cfg, MercFeeConfigAlgorithmTypeDto.DeviceAlgorithmMercVO.class);
                Long algorithmId = damVo.getAlgorithmId();
                String algorithmPayConfig = algorithmPayConfigMap.get(algorithmId);
                DeviceAlgorithmChargingDto.AlgorithmMoonConfig algorithmMoonConfig = JSONUtil.parseObj(algorithmPayConfig).toBean(DeviceAlgorithmChargingDto.AlgorithmMoonConfig.class);
                DeviceAlgorithmChargingDto.AlgorithmMoonConfig.Inf inf = algorithmMoonConfig.getInf();
                DeviceAlgorithmChargingDto.AlgorithmMoonConfig.Moon moon = algorithmMoonConfig.getMoon();
                damVo.setMoonMoney(moon.getMoney());
                damVo.setMoonSize(moon.getSize());
                damVo.setSingleMoney(algorithmMoonConfig.getPrice());
                deviceAcMercList.add(damVo);
            }
        }
        data.setDeviceAcMercList(deviceAcMercList);
        data.setDeviceAcPlatformList(deviceAcPlatformList);
        return R.ok(data);
    }


    @PostMapping("page")
    @ApiOperation("分页查询")
    public R<PageBean<MercFeeConfigAlgorithmTypeDto.Vo>> page(@RequestBody MercFeeConfigAlgorithmTypeDto.Page page) {
        PageBean pageBean = page.getPage();
        LambdaQueryWrapper<MercFeeConfigAlgorithmType> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, MercFeeConfigAlgorithmType.class).build();
        IPage<MercFeeConfigAlgorithmType> iPage = page(toIPage(pageBean), lambdaQueryWrapper);
        return R.ok(toPageBean(MercFeeConfigAlgorithmTypeDto.Vo.class, iPage));
    }

    @PostMapping("save")
    @ApiOperation("添加")
    public R save(@RequestBody @Validated MercFeeConfigAlgorithmTypeDto.Save save) {
        Long mercId = save.getMercId();
        Long algorithmId = save.getAlgorithmId();
        MercFeeConfigAlgorithmType mc = this.getOne(Wrappers.<MercFeeConfigAlgorithmType>lambdaQuery()
                .eq(MercFeeConfigAlgorithmType::getMercId, mercId)
                .eq(MercFeeConfigAlgorithmType::getAlgorithmId, algorithmId)
        );
        if (mc != null) {
            throw new CommRuntimeException("该类型配置已存在，请勿重复添加！");
        }
        MercDto.Vo merc = R.feignCheckData(mercService.obj(new MercDto.Vo().setId(mercId)));
        String mercCode = merc.getMercCode();
        MercFeeConfigAlgorithmType saveInfo = copy(MercFeeConfigAlgorithmType.class, save);
        saveInfo.setMercCode(mercCode);
        save(saveInfo);
        return R.ok();
    }

    @PostMapping("update")
    @ApiOperation("修改")
    public R update(@RequestBody @Validated MercFeeConfigAlgorithmTypeDto.Update update) {
        MercFeeConfigAlgorithmType updateInfo = copy(MercFeeConfigAlgorithmType.class, update);
        updateById(updateInfo);
        return R.ok();
    }
}
