package com.ruoyi.project.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.business.domain.TbAgentTarget;
import com.ruoyi.project.business.domain.thirdparty.Gj;
import com.ruoyi.project.business.domain.vo.agent.AgentTargetReq;
import com.ruoyi.project.business.domain.vo.agent.AgentTargetRes;
import com.ruoyi.project.business.mapper.TbAgentTargetMapper;
import com.ruoyi.project.business.service.GjService;
import com.ruoyi.project.business.service.ITbAgentTargetService;
import com.ruoyi.project.business.service.ITbAreaService;
import com.ruoyi.project.business.service.ITcProjectService;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 代理商考核Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-16
 */
@Service
@RequiredArgsConstructor
public class TbAgentTargetServiceImpl extends ServiceImpl<TbAgentTargetMapper, TbAgentTarget> implements
    ITbAgentTargetService {

    public static final DecimalFormat formatter = new DecimalFormat("#,###");

    private final TbAgentTargetMapper tbAgentTargetMapper;

    private final GjService gjService;

    private final ITcProjectService tcProjectService;

    private final ITbAreaService tbAreaService;


    /**
     * 查询代理商考核列表
     *
     * @param agentTargetReq 代理商考核
     * @return 代理商考核
     */
    @Override
    @SuppressWarnings("NonAsciiCharacters")
    public List<AgentTargetRes> selectTbAgentTargetList(AgentTargetReq agentTargetReq, Boolean needPage) {
        PageHelper.clearPage();
        agentTargetReq.setPermissionChar(SecurityUtils.getPermissionCharIns());
        if (Boolean.TRUE.equals(needPage)) {
            PageHelper.<AgentTargetRes>startPage(agentTargetReq.getPageNum(), agentTargetReq.getPageSize());
        }
        List<AgentTargetRes> agentTargetRes = tbAgentTargetMapper.selectTbAgentTargetList(agentTargetReq);
        if (agentTargetRes.isEmpty()) {
            return agentTargetRes;
        }
        List<String> agentNos = agentTargetRes.stream().map(AgentTargetRes::getAgentNo).collect(Collectors.toList());

        // TODO 目前这里的查询是没有关联 年份的，需要加上年份的条件
        List<Gj> gjs = gjService.selectList(Wrappers.lambdaQuery(Gj.class).in(Gj::get代理商, agentNos));
        // List<Gj> gjs = gjService.list(Wrappers.lambdaQuery(Gj.class).in(Gj::get代理商, agentNos));
        Map<String, Double> agentNo2Count = gjs.stream()
            .collect(Collectors.groupingBy(Gj::get代理商, Collectors.summingDouble(Gj::get数量)));
        Map<String, Double> agentNo2Amount = gjs.stream()
            .collect(Collectors.groupingBy(Gj::get代理商, Collectors.summingDouble(Gj::get已收金额)));

        for (AgentTargetRes agent : agentTargetRes) {
            Optional.ofNullable(agentNo2Count.get(agent.getAgentNo()))
                .ifPresent(item -> agent.setActualElevatorCount(item.longValue()));
            Optional.ofNullable(agentNo2Amount.get(agent.getAgentNo()))
                .ifPresent(item -> agent.setActualMoney(BigDecimal.valueOf(item)));
            //计算完成率
            if (Objects.nonNull(agent.getTargetElevatorCount())
                && Objects.nonNull(agent.getActualElevatorCount())
                && agent.getTargetElevatorCount() != 0) {
                String result = getCompletionRate(new BigDecimal(agent.getTargetElevatorCount()),
                    new BigDecimal(agent.getActualElevatorCount()));
                agent.setCompletionRate1(result);
            }
        }

        return agentTargetRes;
    }

    private static String getCompletionRate(BigDecimal target, BigDecimal act) {
        BigDecimal divide = (act.divide(
            target, 4, RoundingMode.HALF_UP)).multiply(new BigDecimal(100)).setScale(2,
            RoundingMode.HALF_UP);
        return divide.toPlainString() + "%";
    }

    @Override
    public boolean add(TbAgentTarget tbAgentTarget) {
        boolean exist = baseMapper.exists(Wrappers.
            lambdaQuery(TbAgentTarget.class)
            .eq(TbAgentTarget::getAgentId, tbAgentTarget.getAgentId())
            .eq(TbAgentTarget::getTargetYear, tbAgentTarget.getTargetYear()));
        // 当前代理商该年度考核计划已存在
        if (exist) {
            throw new RuntimeException("当前代理商该年度考核计划已存在");
        }

        return save(tbAgentTarget);
    }


    @Override
    public AgentTargetRes getInfoByQuery(AgentTargetReq agentTargetReq) {
        // List<TbAgentTarget> list = list(Wrappers.lambdaQuery(TbAgentTarget.class)
        //     .eq(TbAgentTarget::getAgentId, agentTargetReq.getAgentId())
        //     .eq(TbAgentTarget::getTargetYear, agentTargetReq.getTargetYear())
        //     .orderByDesc(TbAgentTarget::getTargetId));
        // if (CollUtil.isNotEmpty(list)) {
        //     return BeanUtil.copyProperties(list.get(0), AgentTargetRes.class);
        // } else {
        //     return null;
        // }

        TbAgentTarget one = getOne(Wrappers.lambdaQuery(TbAgentTarget.class)
                .eq(TbAgentTarget::getAgentId, agentTargetReq.getAgentId())
                .eq(TbAgentTarget::getTargetYear, agentTargetReq.getTargetYear())
                .orderByDesc(TbAgentTarget::getTargetId), false);
        if (Objects.isNull(one)) {
            return null;
        }
        return BeanUtil.copyProperties(one, AgentTargetRes.class);
    }

    public static void main(String[] args) {
        String connectionUrl = "jdbc:sqlserver://116.198.226.220:1433;DatabaseName=KOYO;encrypt=true;trustServerCertificate=true";
        try (Connection connection = DriverManager.getConnection(connectionUrl, "sa", "qing.sqlserver.FK")) {
            System.out.println("Connected successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void convertAmount(List<AgentTargetRes> list) {
        for (AgentTargetRes agentTargetRes : list) {
            String s1 = Optional.ofNullable(agentTargetRes.getTargetMoney()).map(formatter::format).orElse("");
            agentTargetRes.setTargetMoneyStr(s1);
            String s2 = Optional.ofNullable(agentTargetRes.getActualMoney()).map(formatter::format).orElse("");
            agentTargetRes.setActualMoneyStr(s2);
        }
    }
}
