package cn.pluss.platform.job;


import cn.pluss.platform.entity.MerchantRate;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.mapper.MerchantRateMapper;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.userApp.UserAppService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 超级服务商交易量检查
 */
@Deprecated
//@Configuration
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class CheckSuperMerchantTradeJob {


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserAppService userAppService;
    @Autowired
    private MerchantOrderService merchantOrderService;
    @Autowired
    private MerchantRateMapper merchantRateMapper;

    /**
     * 超级代理商每个月月末交易量检查
     * 费率阶梯：不足200w 费率0.25%
     *         超过200w小于400w 费率0.24%
     *         超过400w小于700w 费率0.23%
     *         超过700w小于1000w 费率0.22%
     *         超过1000w 费率0.21%
     */
    @Scheduled(cron = "0 55 23 28,29,30,31 * ? ")
    public void checkSuperMercTradeTask(){
        logger.info("=================>检查超级代理商当月交易量情况定时任务开始，并更新超级代理商费率<====================");
        Calendar c = Calendar.getInstance();
        if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
            QueryWrapper<UserApp> queryWrapper = new QueryWrapper<UserApp>().eq("userType","agent");
            //过滤固定的超级服务商费率的费率
            queryWrapper.and(wrapper ->wrapper.eq("isfixedDelay","0").or().isNull("isfixedDelay"));
            List<UserApp> userAppList = userAppService.list(queryWrapper);
            logger.info("=================>等待执行的超级代理商数量为：{}<====================",userAppList.size());
            if(userAppList.isEmpty()){
                logger.info("=================>待更新的超级代理商为空，定时任务结束<====================");
                return;
            }
            List<Long> userIdList = new ArrayList<Long>();
            userAppList.forEach(userApp -> {
                userIdList.add(userApp.getUserId());
            });
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("list",userIdList);

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar date = Calendar.getInstance();
            date.add(Calendar.MONTH, 0);
            date.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            String first = format.format(date.getTime());
            //获取当前月最后一天
            Calendar ca = Calendar.getInstance();
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            String last = format.format(ca.getTime());

            params.put("firstDate",first + " 00:00:00");
            params.put("lastDate",last + " 23:59:59");
            if(userIdList != null && userIdList.size() > 0){
                List<Map<String,Object>> list = merchantOrderService.getSuperMerchantToDayTradeMoneyCount(params);
                List<MerchantRate> updateRateList = new ArrayList<MerchantRate>(list.size());
                if(list != null && list.size() > 0){
                    for (int i=0;i<list.size();i++){
                        MerchantRate rate = new MerchantRate();
                        Map<String, Object> r = list.get(i);
                        Double tradeMoney = (Double) r.get("tradeCountMoney");
                        if(tradeMoney < 2000000d){
                            rate.setRate(25);
                        }else if(tradeMoney >= 2000000d && tradeMoney < 4000000){
                            rate.setRate(24);
                        }else if(tradeMoney >= 4000000d && tradeMoney < 7000000d){
                            rate.setRate(23);
                        }else if(tradeMoney >= 7000000d && tradeMoney < 10000000d){
                            rate.setRate(22);
                        }else{
                            rate.setRate(21);
                        }
                        rate.setUserId(r.get("agentId").toString());
                        rate.setUpdateTime(new Date());
                        updateRateList.add(rate);
                    }
                    merchantRateMapper.batchUpdateRate(updateRateList);
                }
            }
        }
        logger.info("=================>超级代理商费率更新定时任务结束<====================");
    }
}
