package com.xy.service;

import cn.hutool.core.collection.CollUtil;
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.dto.MercFeeSettleDto;
import com.xy.dto.be.MercDto;
import com.xy.entity.MercFeeSettle;
import com.xy.entity.MercFeeStatistic;
import com.xy.mapper.MercFeeSettleMapper;
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 com.xy.utils.enums.MercFeeSettleSate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
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(onConstructor_ = @Lazy)
@Api(tags = "商户佣金费用结算")
public class MercFeeSettleServiceImpl extends ServiceImpl<MercFeeSettleMapper, MercFeeSettle> implements MercFeeSettleService {

    private MercFeeStatisticServiceImpl mercFeeStatisticService;
    private MercFeignService mercFeignService;


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

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

    @PostMapping("page")
    @ApiOperation("平台运营-佣金结算记录分页")
    public R<PageBean<MercFeeSettleDto.Vo>> page(@RequestBody MercFeeSettleDto.Page page) {
        PageBean pageBean = page.getPage();
        LambdaQueryWrapper<MercFeeSettle> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, MercFeeSettle.class)
                .ge(MercFeeSettle::getCreateTime, page.getBeginCreateTime())
                .le(MercFeeSettle::getCreateTime, page.getEndCreateTime())
                .build().orderByDesc(!Emptys.check(pageBean.getOrders()), MercFeeSettle::getCreateTime);
        IPage<MercFeeSettle> iPage = page(toIPage(pageBean), lambdaQueryWrapper);
        PageBean<MercFeeSettleDto.Vo> pb = toPageBean(MercFeeSettleDto.Vo.class, iPage);
        List<MercFeeSettleDto.Vo> records = pb.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            List<Long> mercIds = records.stream().map(MercFeeSettleDto.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 (MercFeeSettleDto.Vo record : records) {
                Long mercId = record.getMercId();
                // 反显商户名称
                String mercName = mercMap.get(mercId);
                record.setMercName(mercName);
            }
            pb.setRecords(records);
        }
        return R.ok(pb);
    }


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

    @PostMapping("doSettle")
    @ApiOperation("运营端结算完成操作")
    public R doSettle(@RequestBody @Validated MercFeeSettleDto.DoSettle update) {
        List<Long> ids = update.getIds();
        List<MercFeeSettle> mercFeeSettles = this.listByIds(ids);
        mercFeeSettles.forEach(mfs -> {
            mfs.setSettleState(MercFeeSettleSate.S3.getCode());
            mfs.setFinishSettleTime(LocalDateTime.now());
            // 结算完成需要更新统计表
            Long mercId = mfs.getMercId();
            MercFeeStatistic mercFeeStatistic = mercFeeStatisticService.getByMercId(mercId);
            // 累计已结算金额
            mercFeeStatistic.setSettleMoney(mercFeeStatistic.getSettleMoney() + mfs.getSettleMoney());
            mercFeeStatisticService.updateById(mercFeeStatistic);
        });
        return R.ok(updateBatchById(mercFeeSettles));
    }

    /**
     * 结算申请
     *
     * @param dto
     * @return
     */
    public R<Boolean> applySettle(MercFeeSettleDto.ApplyDTO dto) {
        MercFeeSettle saveInfo = copy(MercFeeSettle.class, dto);
        saveInfo.setSettleState(MercFeeSettleSate.S2.getCode());
        return R.ok(save(saveInfo));
    }

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