package com.xy.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xy.annotate.RestMappingController;
import com.xy.dto.MercFeeCountDayDto;
import com.xy.dto.MercFeeCountMonthDto;
import com.xy.entity.MercFeeCountMonth;
import com.xy.error.CommRuntimeException;
import com.xy.service.MercFeeCountDayServiceImpl;
import com.xy.service.MercFeeCountMonthServiceImpl;
import com.xy.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;


/**
 * 商户佣金费用收益每月统计任务（不含本月） 每月1号凌晨2点执行
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Api(tags = "商户佣金费用收益每月统计任务")
@RestMappingController("job/feeCountMonth")
public class MercFeeCountMonthJob {

    private final MercFeeCountDayServiceImpl mercFeeCountDayService;
    private final MercFeeCountMonthServiceImpl mercFeeCountMonthService;

    @PostMapping("excuteJob")
    @ApiOperation("指定日期执行")
    public R excuteJob(@RequestBody @Validated MercFeeCountMonthDto.ExcuteDayDTO dto) {
        return R.ok(monthJob(dto.getDate()));
    }

    /**
     * 商户佣金费用收益每月统计任务（不含今天）
     * 类型 1设备管理费。2设备激活费。3算法扣费标准。4流量卡费
     *
     * @param date yyyyMM
     * @return
     */
    @XxlJob("mercFeeCountMonthJob")
    public ReturnT<String> monthJob(String date) {
        //获取上个月
        DateTime lastMonth = DateUtil.lastMonth();
        String queryDay = DateUtil.format(lastMonth, DatePattern.SIMPLE_MONTH_PATTERN);
        if (StrUtil.isNotEmpty(date)) {
            queryDay = date;
            //指定日期需要判断是否重复执行
            MercFeeCountMonthDto.SelectList selectList = new MercFeeCountMonthDto.SelectList();
            selectList.setDateValue(Integer.valueOf(DateUtil.format(lastMonth, DatePattern.PURE_DATE_PATTERN)));
            List<MercFeeCountMonthDto.Vo> vos = R.feignCheckData(mercFeeCountMonthService.list(selectList));
            if (CollUtil.isNotEmpty(vos)) {
                throw new CommRuntimeException("已存在日期【" + date + "】的数据，请勿重复执行！");
            }
        }
        //年月
        Integer monthValue = Integer.valueOf(queryDay);
        // 按商户id,父商户ID,缴费类型  统计指定月份 缴费总和、佣金总和
        List<MercFeeCountDayDto.CountByMonthVO> countByMonthVOS = mercFeeCountDayService.countByMonth(new MercFeeCountDayDto.CountByMonth().setMonthValue(monthValue));
        if (CollUtil.isNotEmpty(countByMonthVOS)) {
            List<MercFeeCountMonth> mercFeeCountMonths = BeanUtil.copyToList(countByMonthVOS, MercFeeCountMonth.class);
            mercFeeCountMonths.forEach(mfm -> {
                mfm.setDateValue(monthValue);
            });
            mercFeeCountMonthService.saveBatch(mercFeeCountMonths);
        }

        return ReturnT.SUCCESS;
    }
}
