package com.hzs.third.job;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.member.account.CuMemberRecharge;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.member.account.IMemberJobServiceApi;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Slf4j
@ConditionalOnProperty(name = "xxl-job.start", havingValue = "true")
@Component
public class OrderJob {

    @DubboReference
    ISaOrderServiceApi orderServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;
    @DubboReference
    IMemberJobServiceApi memberJobServiceApi;

    /**
     * 定时关单  订单三十分钟未支付自动关闭
     */
    @XxlJob("autoCloseOrder")
    public void timingCloseOrder() {
        orderServiceApi.closeOrder();
    }

    /*
     * @description: 定时发送业绩短信
     **/
    @XxlJob("sendOrderAchieve")
    public void sendOrderAchieveMsg() {
        Date startDate = DateUtils.currentDate();
        Date endDate = DateUtils.afterDate(1, ChronoUnit.DAYS);
        List<SaOrderExt> saOrderExtList = orderServiceApi.listSaOrderByDay(startDate, endDate, null).getData();
        if (CollectionUtil.isNotEmpty(saOrderExtList)) {
            BigDecimal registerAchieve = BigDecimal.ZERO;
            BigDecimal updateAchieve = BigDecimal.ZERO;
            BigDecimal repurchaseAchieve = BigDecimal.ZERO;
            BigDecimal haiFunAchieve = BigDecimal.ZERO;
            BigDecimal directSupplyAchieve = BigDecimal.ZERO;
            Map<Integer, CurrencyDTO> currencyDtoMap = new HashMap<>();
            for (SaOrderExt saOrderExt : saOrderExtList) {
                if (EYesNo.NO.getIntValue() == saOrderExt.getDelFlag()) {
                    continue;
                }
                BigDecimal orderAmount = saOrderExt.getOrderAmount();
                if (!Objects.equals(CountryConstants.CHINA_COUNTRY, saOrderExt.getPkCountry())) {
                    BigDecimal outRate;
                    if (currencyDtoMap.containsKey(saOrderExt.getPkRate())) {
                        outRate = currencyDtoMap.get(saOrderExt.getPkRate()).getInExchangeRate();
                    } else {
                        CurrencyDTO currencyDTO = currencyServiceApi.getCurrencyByPkId(saOrderExt.getPkRate()).getData();
                        outRate = currencyDTO.getInExchangeRate();
                        currencyDtoMap.put(saOrderExt.getPkCountry(), currencyDTO);
                    }
                    orderAmount = ComputeUtil.computeMultiply(ComputeUtil.computeDivide(orderAmount, outRate), 1);
                }
                if (Objects.equals(EOrderType.REGISTER_ORDER.getValue(), saOrderExt.getOrderType()) ||
                        Objects.equals(EOrderType.SPECIAL_UPGRADE_ORDER.getValue(), saOrderExt.getOrderType())) {
                    registerAchieve = ComputeUtil.computeAdd(registerAchieve, orderAmount);
                } else if (Objects.equals(EOrderType.UPGRADE_ORDER.getValue(), saOrderExt.getOrderType()) ||
                        Objects.equals(EOrderType.SPECIAL_REGISTER_ORDER.getValue(), saOrderExt.getOrderType())) {
                    updateAchieve = ComputeUtil.computeAdd(updateAchieve, orderAmount);
                } else {
                    if (Objects.equals(EOrderType.CONSUME_ORDER.getValue(), saOrderExt.getOrderType())) {
                        orderAmount = ComputeUtil.computeSubtract(orderAmount, saOrderExt.getConsumeAmount());
                    }
                    repurchaseAchieve = ComputeUtil.computeAdd(repurchaseAchieve, orderAmount);
                }

            }
            BigDecimal rechargeTotalAmount = selectRechargeTotalAmount(startDate, endDate);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("尊敬的董事长您好！今日A=").append(calculateAchieve(registerAchieve))
                    .append("，B=").append(calculateAchieve(updateAchieve))
                    .append("，C=").append(calculateAchieve(repurchaseAchieve))
                    .append("，D=").append(calculateAchieve(haiFunAchieve))
                    .append("，合计=").append(calculateAchieve(registerAchieve.add(updateAchieve)
                    .add(repurchaseAchieve).add(haiFunAchieve).add(directSupplyAchieve))).append("，Q=").append(calculateAchieve(rechargeTotalAmount)).append("。");
        }
    }

    /**
     * 查询充值现金币的总金额
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return BigDecimal
     */
    private BigDecimal selectRechargeTotalAmount(Date startDate, Date endDate) {
        CuMemberRecharge cuMemberRecharge = memberJobServiceApi.selectRechargeTotalAmount(startDate, endDate).getData();
        if (null != cuMemberRecharge) {
            return cuMemberRecharge.getRechargeAmount();
        } else {
            return BigDecimal.ZERO;
        }
    }

    private BigDecimal calculateAchieve(BigDecimal achieve) {
        return ComputeUtil.computeDivide(achieve, BigDecimal.valueOf(10000)).setScale(2, RoundingMode.HALF_UP);
    }

}
