package com.kym.service.miniapp.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.kym.common.utils.CommUtil;
import com.kym.entity.admin.queryParams.CustomChargeOrdersQueryParam;
import com.kym.entity.admin.queryParams.StatQueryParam;
import com.kym.entity.admin.vo.CustomOrderVo;
import com.kym.entity.admin.vo.StationStatVo;
import com.kym.entity.common.PageBean;
import com.kym.entity.miniapp.ChargeOrder;
import com.kym.mapper.miniapp.ChargeOrderMapper;
import com.kym.service.miniapp.ChargeOrderService;
import com.kym.service.utils.KymCache;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 充电订单表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2023-08-08
 */
@Service
@DS("db-miniapp")
public class ChargeOrderServiceImpl extends ServiceImpl<ChargeOrderMapper, ChargeOrder> implements ChargeOrderService {

    private final KymCache kymCache;

    public ChargeOrderServiceImpl(KymCache kymCache) {
        this.kymCache = kymCache;
    }

    @Override
    public ChargeOrder getChargingOrderByUserId(Long userId) {
        return lambdaQuery()
                .eq(ChargeOrder::getUserId, userId)
                .in(ChargeOrder::getChargeStatus, ChargeOrder.CHARGE_STATUS_启动中, ChargeOrder.CHARGE_STATUS_充电中)
                .one();
    }

    @Override
    public ChargeOrder getChargingOrderByStartChargeSeq(String startChargeSeq) {
        return lambdaQuery().eq(ChargeOrder::getStartChargeSeq, startChargeSeq).one();
    }

    @Override
    public PageBean<CustomOrderVo> customChargeOrders(CustomChargeOrdersQueryParam params) {
        if (params.getConnectorId() != null) {
            var connectorId = kymCache.getConnectorId(params.getConnectorId());
            params.setConnectorId(connectorId);
        }
        // 判断数据权限
        var adminStationId = kymCache.getAdminUserStationId(StpUtil.getLoginIdAsLong());
        if (adminStationId != null) {
            params.setStationId(adminStationId);
        }
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        // 查询订单列表（订单编号，手机号，充电站，充电桩SN/短码，订单状态，建单时间，结算时间，充电电量，实付金额，付款状态）
        var result = baseMapper.listChargeOrders(params);
        var page = new PageBean<>(result);
        page.setList(result.stream().map(item -> item.setShortId(kymCache.getShortId(item.getConnectorId().substring(0, 15))).setStationName(kymCache.getStationName(item.getConnectorId()))).collect(Collectors.toList()));
        var map = baseMapper.statChargeOrders(params);
        return page.setExtraData(map);
    }

    @Override
    public Object orderDetail(String startChargeSeq) {
        // TODO: 2023-08-22 订单详情（基本信息、收费信息） 上面接口貌似已经实现了
        /*
         * 基本信息：订单编号，订单状态，所属用户，所属电站，充电桩序列号，建单时间，结算时间，桩启动充电时间，桩停止充电时间
         * 收费详情：充电电量，充电电费，服务费，总费用，支付状态
         */
        return null;
    }

    @Override
    public ChargeOrder orderDetailForApp(String startChargeSeq) {
        // TODO: 2023-08-24 后面跟上面接口合并
        return lambdaQuery().eq(ChargeOrder::getStartChargeSeq, startChargeSeq).one();
    }

    /**
     * 站点统计
     *
     * @param params
     * @return
     */
    @Override
    public PageBean<StationStatVo> stationStat(StatQueryParam params) {
        // 判断数据权限
        var adminStationId = kymCache.getAdminUserStationId(StpUtil.getLoginIdAsLong());
        if (adminStationId != null) {
            params.setStationId(adminStationId);
        }
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        var res = baseMapper.stationStat(params).stream().peek(item -> {
            item.setElecMoneyPercent((new BigDecimal(item.getElecMoney())).divide(new BigDecimal(Math.max(1, item.getTotalMoney())), 2, RoundingMode.HALF_UP));
            item.setServiceMoneyPercent(BigDecimal.ONE.subtract(item.getElecMoneyPercent()));
        }).collect(Collectors.toList());
        var map = Map.of(
                "totalPower", res.stream().mapToDouble(StationStatVo::getTotalPower).sum(),
                "serviceMoney", res.stream().mapToInt(StationStatVo::getServiceMoney).sum()
        );
        return new PageBean<>(res).setExtraData(map);
    }

    /**
     * 充电站当日统计
     *
     * @return
     */
    @Override
    public Map<String, Object> stationTodayStat(String stationId) {
        if (CommUtil.null2Long(stationId) <= 0) {
            // 判断数据权限
            stationId = kymCache.getAdminUserStationId(StpUtil.getLoginIdAsLong());
        }

        return baseMapper.stationTodayStat(stationId);
    }

    /**
     * 订单号批量查询订单
     *
     * @param startChargeSeqs
     * @return
     */
    @Override
    public List<ChargeOrder> getChargeOrdersBySeqs(String[] startChargeSeqs) {
        return lambdaQuery().in(ChargeOrder::getStartChargeSeq, Arrays.stream(startChargeSeqs).toList()).list();
    }


}
