package com.xy.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.dto.MercFeeCountMonthDto;
import com.xy.dto.be.MercDto;
import com.xy.entity.MercFeeCountMonth;
import com.xy.entity.MercFeeStatistic;
import com.xy.mapper.MercFeeCountMonthMapper;
import com.xy.service.be.MercFeignService;
import com.xy.utils.Emptys;
import com.xy.utils.MybatisPlusQuery;
import com.xy.utils.PageBean;
import com.xy.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
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 谭斌
 * @since 2024-04-23
 */
@Service
@AllArgsConstructor
@Api(tags = "商户佣金费用收益每月统计（不含本月）")
public class MercFeeCountMonthServiceImpl extends ServiceImpl<MercFeeCountMonthMapper, MercFeeCountMonth> implements MercFeeCountMonthService {

    private MercFeignService mercFeignService;
    private MercFeeStatisticServiceImpl mercFeeStatisticService;

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

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

    /**
     * 收益概览-分页查询
     *
     * @param page
     * @return
     */
    public R<PageBean<MercFeeCountMonthDto.Vo>> page(MercFeeCountMonthDto.Page page) {

        PageBean pageBean = page.getPage();


        String start = page.getBeginTime();
        String end = page.getEndTime();

        LambdaQueryWrapper<MercFeeCountMonth> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, MercFeeCountMonth.class)
                .build()

                .orderByDesc(MercFeeCountMonth::getDateValue);

        if (StrUtil.isNotEmpty(start) && StrUtil.isNotEmpty(end)) {
            // 2024-04-03
            String startDate = start.replaceAll("-", "");
            String endDate = end.replaceAll("-", "");
            int s = Integer.parseInt(startDate.substring(0, 4) + startDate.substring(5, 7));
            int e = Integer.parseInt(endDate.substring(0, 4) + endDate.substring(5, 7));
            lambdaQueryWrapper.between(MercFeeCountMonth::getDateValue, s, e);
        }
        IPage<MercFeeCountMonth> iPage = page(toIPage(pageBean), lambdaQueryWrapper);
        PageBean<MercFeeCountMonthDto.Vo> pageData = toPageBean(MercFeeCountMonthDto.Vo.class, iPage);
        List<MercFeeCountMonthDto.Vo> records = pageData.getRecords();
        if (Emptys.check(records)) {
            List<Long> mercIds = records.stream().map(MercFeeCountMonthDto.Vo::getMercId).distinct().collect(Collectors.toList());
            List<MercDto.Vo> mercList = R.feignCheckData(mercFeignService.listMerc(new MercDto.ListDTO().setIds(mercIds)));
            Map<Long, String> mercMap = mercList.stream().collect(Collectors.toMap(MercDto.Vo::getId, MercDto.Vo::getName));
            for (MercFeeCountMonthDto.Vo record : records) {
                Long mercId = record.getMercId();
                // 反显商户名称
                String mercName = mercMap.get(mercId);
                record.setMercName(mercName);
            }
            pageData.setRecords(records);
        }
        return R.ok(pageData);
    }

    /**
     * 确认佣金
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public R confirm(MercFeeCountMonthDto.ConfirmDTO dto) {
        Long id = dto.getId();
        Long parentMercId = dto.getParentMercId();
        MercFeeCountMonth countMonth = getOne(Wrappers.<MercFeeCountMonth>lambdaQuery()
                .eq(MercFeeCountMonth::getParentMercId, parentMercId)
                .eq(MercFeeCountMonth::getId, id)
        );
        if (countMonth != null) {
            // 确认
            countMonth.setVerify(true);
            countMonth.setVerifyTime(LocalDateTime.now());
            updateById(countMonth);
            // 确认后，更新统计表
            MercFeeStatistic mercFeeStatistic = mercFeeStatisticService.getByMercId(parentMercId);
            // 更新确认金额,可结算金额
            mercFeeStatistic.setVerifyMoney(mercFeeStatistic.getVerifyMoney() + countMonth.getBrokerage());
            mercFeeStatistic.setUnSettleMoney(mercFeeStatistic.getUnSettleMoney() + countMonth.getBrokerage());
            mercFeeStatisticService.updateById(mercFeeStatistic);
        }
        return R.ok();
    }

    @PostMapping("save")
    @ApiOperation("添加")
    public R save(@RequestBody @Validated MercFeeCountMonthDto.Save save) {
        MercFeeCountMonth saveInfo = copy(MercFeeCountMonth.class, save);
        save(saveInfo);
        return R.ok();
    }

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