package com.sqx.modules.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.modules.artificer.dao.ArtificerDao;
import com.sqx.modules.artificer.dao.BlArtificerZqhzDao;
import com.sqx.modules.artificer.dao.OrdersDao;
import com.sqx.modules.artificer.dao.UserRechargeDao;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.entity.BlArtificerZqhz;
import com.sqx.modules.artificer.entity.Orders;
import com.sqx.modules.artificer.entity.UserRecharge;
import com.sqx.modules.bl.userZxsc.dao.BlUserZxscDao;
import com.sqx.modules.bl.userZxsc.entity.BlUserZxsc;
import com.sqx.modules.common.dao.ArtificerPartitioningDetailsMapper;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.entity.ArtificerPartitioningDetails;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.shopping.utils.DateUtil;
import com.sqx.modules.task.service.AllTaskSercice;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AllTaskServiceImpl implements AllTaskSercice {


    @Autowired
    private ArtificerDao artificerDao;

    @Autowired
    private ArtificerPartitioningDetailsMapper artificerPartitioningDetailsMapper;

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private BlUserZxscDao blUserZxscDao;

    @Autowired
    public CommonInfoDao commonInfoDao;

    @Autowired
    private UserRechargeDao userRechargeDao;

    @Autowired
    private BlArtificerZqhzDao blArtificerZqhzDao;

    /**
     * 计算技师升级规则 每天半夜1点执行，预留12点到01点之间的计算间隔，用于触发其他计算逻辑
     * A0,A1,A2,A3,A4,A5等
     */
//    @Scheduled(cron = "0 * * * * ?")
    @Scheduled(cron = "0 00 21 * * ?")
    public void upgradeJishi() {
        System.out.println("------------计算技师升级规则-----------");
        //1.获取全部参与积分规则的技师
        List<Artificer> jslist = artificerDao.getYxjsList();
        //2.获取计算周期，从几号到几号例如1号-10号为一个周期，11号到20号第二个周期，21号-月底是第三个周期
        Calendar calendar = Calendar.getInstance();
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(dayOfMonth);
        String startTime = "";
        String endTime = "";
        //获取执行时间
        if(dayOfMonth == 1){
            Calendar calendar4 = Calendar.getInstance();
            calendar4.set(Calendar.DAY_OF_MONTH, 1);
            calendar4.add(Calendar.DAY_OF_MONTH, -1);
            int lastDayOfMonth = calendar4.get(Calendar.DAY_OF_MONTH);
            Calendar calendar2 = Calendar.getInstance();
            calendar2.add(Calendar.MONTH, -1); // 获取上个月
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            String lastMonth = format.format(calendar2.getTime());
            startTime = lastMonth+"-16 00:00:00";
            endTime = lastMonth+"-"+lastDayOfMonth+" 23:59:59";
        }else if(dayOfMonth == 16){
            Calendar calendar4 = Calendar.getInstance();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            String lastMonth = format.format(calendar4.getTime());
            startTime = lastMonth+"-01 00:00:00";
            endTime = lastMonth+"-15 23:59:59";
        }
        System.out.println("startTime：" + startTime);
        System.out.println("endTime：" + endTime);

//        startTime = "2024-06-21 00:00:00";
//        endTime = "2024-06-30 23:59:59";
        //不为空则继续执行，否则不到时间不计算升级规则
        if(StringUtils.isNotEmpty(startTime)){
            //3.查询升级规则配置表
            QueryWrapper<ArtificerPartitioningDetails> sjgzQuery = new QueryWrapper<ArtificerPartitioningDetails>();
            sjgzQuery.ne("grade","新");
            sjgzQuery.orderByDesc("outstanding_achievement","duration_online");
            List<ArtificerPartitioningDetails> sjgzAllList = artificerPartitioningDetailsMapper.selectList(sjgzQuery);
            //4.根据技师的服务类型查找对应的配置规则，
            for (Artificer jsPar : jslist) {
                //获取技师是否参与积分规则，如果参与积分规则则继续执行，否则不变分成比例
                Integer ynJfgz = jsPar.getYnJfgz();//是否参与积分规则计算（0不参与 1参与）

                //4.1获取 技师销售金额(order表的 price)  只查询完成的单子
                BigDecimal jsdqyj = ordersDao.selectOrdersArtificerIntegralEarnings(jsPar.getArtificerId(),endTime,startTime);
                jsdqyj = jsdqyj.setScale(0,BigDecimal.ROUND_DOWN);
                //4.2获取 技师加钟率(order表的parent_id为空则是正常订单，不为空则是加钟订单  用加钟订单/正常订单为加钟率)
                String jsjzl = ordersDao.selectOrdersArtificerIntegraladdNum(jsPar.getArtificerId(),endTime,startTime);
                //4.3获取 在线时长（通过积分表和兑换比例反推在线时长 user_rechange的type=1）
                String jszxsc = ordersDao.selectOrdersZxscNum(jsPar.getArtificerId(),startTime,endTime);
                CommonInfo commonInfo = commonInfoDao.findOne(100000);
                String minute = commonInfo.getValue();//多少分钟等于1积分
                Double zxscHour = Double.parseDouble(jszxsc)*Double.parseDouble(minute)/60;
                //4.4获取 积分（充值积分 user_rechange的type=2）
                String jsjfStr = ordersDao.selectOrdersStoredValueIntegral(jsPar.getArtificerId(),endTime,startTime);
                if(ynJfgz==1){
                    //4.5根据对应的收益，判断属于哪个等级，并修改artificer的yn_jfgz（等级标识）及rate(百分比)
                    //组装对应的升级规则集合
                    Long classifyId = jsPar.getClassifyId();
//                    List<ArtificerPartitioningDetails> sjgzList = new ArrayList<>();
                    Double zddj = Double.parseDouble(jsdqyj+"");
                    Double jzl = Double.parseDouble(jsjzl);
                    Double zxsc = zxscHour;
                    Double jsjf = Double.parseDouble(jsjfStr);
                    String jsdj = "";//
                    BigDecimal rate = BigDecimal.valueOf(0.6);
                    for (ArtificerPartitioningDetails sjgzPar : sjgzAllList){
                        //当技师的服务类型=升级规则的服务类型，才可以添加到升级规则里去
                        if(StringUtils.equals(sjgzPar.getClassifyId(),String.valueOf(classifyId))){
//                            sjgzList.add(sjgzPar);
                            //最低业绩
                            Double zddjPar = Double.parseDouble(sjgzPar.getOutstandingAchievement()+"");
                            //加钟率
                            Double jzlPar = Double.parseDouble(sjgzPar.getClockRate()+"");
                            //在线时长
                            Double zxscPar = Double.parseDouble(sjgzPar.getDurationOnline()+"");
                            //充值积分
                            Double czjfPar = Double.parseDouble(sjgzPar.getIntegral()+"");
                            System.out.println("============================"+sjgzPar.getGrade()+"================================");
                            System.out.println("最低业绩："+zddj+">"+zddjPar);
                            System.out.println("加钟率A："+jzl+">"+jzlPar);
                            System.out.println("在线时长："+zxsc+">"+zxscPar);
                            System.out.println("充值积分："+jsjf+">"+czjfPar);
                            System.out.println("============================================================");
                            if(zddj>=zddjPar && jzl >=jzlPar && zxsc >= zxscPar && jsjf >= czjfPar){
                                jsdj = sjgzPar.getGrade();
                                rate = BigDecimal.valueOf(Double.parseDouble(sjgzPar.getProportionalSharing()));
                                break;
                            }
                        }
                    }
                    //如果都不符合，则给最低等级（保底）
                    if(StringUtils.isEmpty(jsdj)){
                        QueryWrapper<ArtificerPartitioningDetails> sjgzQuery1 = new QueryWrapper<ArtificerPartitioningDetails>();
                        sjgzQuery1.eq("grade","A0");
                        sjgzQuery1.eq("classify_id",classifyId);
                        sjgzQuery1.last("limit 1");
                        ArtificerPartitioningDetails zddjgz = artificerPartitioningDetailsMapper.selectOne(sjgzQuery1);
                        jsdj = zddjgz.getGrade();
                        rate = BigDecimal.valueOf(Double.parseDouble(zddjgz.getProportionalSharing()));
                    }
                    //如果还查不出来，则保持原样，一点办法都没有了
                    if(StringUtils.isNotEmpty(jsdj)){
                        Artificer jsUp = new Artificer();
                        jsUp.setRate(rate);
                        jsUp.setGrade(jsdj);
                        jsUp.setArtificerId(jsPar.getArtificerId());
                        artificerDao.updateById(jsUp);
                    }
                }

                //技师汇总逻辑
                QueryWrapper<BlArtificerZqhz> blArtificerZqhzQueryWrapper = new QueryWrapper<>();
                blArtificerZqhzQueryWrapper.eq("artificer_id",jsPar.getArtificerId());
                blArtificerZqhzQueryWrapper.ge("start_time",startTime);
                blArtificerZqhzQueryWrapper.ge("end_time",endTime);
                blArtificerZqhzDao.delete(blArtificerZqhzQueryWrapper);


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                BlArtificerZqhz blArtificerZqhz = new BlArtificerZqhz();
                blArtificerZqhz.setArtificerId(jsPar.getArtificerId());
                try {
                    blArtificerZqhz.setStartTime(sdf.parse(startTime));
                    blArtificerZqhz.setEndTime(sdf.parse(endTime));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                blArtificerZqhz.setXsje(jsdqyj+"");
                blArtificerZqhz.setJzl(jsjzl);
                blArtificerZqhz.setZxsc(zxscHour+"");
                blArtificerZqhz.setJf(jsjfStr);
                blArtificerZqhzDao.insert(blArtificerZqhz);
            }
        }
    }




    /**
     * 计算技师在线时长，每10分钟计算一积分
     */
    @Scheduled(cron = "0 * * * * ?")
    public void upJishiZxsc() throws ParseException {
        System.out.println("----------------计算技师在线时长，每10分钟计算一积分-------------");
        CommonInfo commonInfo = commonInfoDao.findOne(100000);
        String minute = commonInfo.getValue();//多少分钟等于1积分

        Artificer artificer = new Artificer();
        artificer.setStatus(1);
        List<Artificer> artificerList = artificerDao.selectInlineList(artificer);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Artificer par:artificerList){
            //取最新的一回的获得积分时间
            QueryWrapper<BlUserZxsc> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("artificer_id",par.getArtificerId());
            queryWrapper.orderByDesc("create_time");
            queryWrapper.last("limit 1");
            BlUserZxsc blUserZxsc = blUserZxscDao.selectOne(queryWrapper);
            if(blUserZxsc == null){
                BigDecimal recharge = new BigDecimal(1);
                BlUserZxsc newBlUserZxsc = new BlUserZxsc();
                newBlUserZxsc.setArtificerId(par.getArtificerId());
                newBlUserZxsc.setUserRecharge(recharge);
                newBlUserZxsc.setCreateTime(sdf.format(new Date()));
                blUserZxscDao.insert(newBlUserZxsc);
            }else{
                String createTime = blUserZxsc.getCreateTime();
                //上一回时间加十分钟
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(sdf.parse(createTime));
                calendar.add(Calendar.MINUTE, Integer.parseInt(minute));
                Date nextDate = calendar.getTime();
                if (now.getTime()>=nextDate.getTime()) {//nowTime < newTime
                    BigDecimal recharge = new BigDecimal(1);
                    BlUserZxsc newBlUserZxsc = new BlUserZxsc();
                    newBlUserZxsc.setArtificerId(par.getArtificerId());
                    newBlUserZxsc.setUserRecharge(recharge);
                    newBlUserZxsc.setCreateTime(sdf.format(new Date()));
                    blUserZxscDao.insert(newBlUserZxsc);
                }
            }

        }
    }

    /**
     * 积分汇总 t+1进行汇总
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void tongjiJishiGrade() {
        System.out.println("----------------每日积分汇总 定时任务-------------");
        //当前时间减一天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);//上一天
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(calendar.getTime());
        BlUserZxsc blUserZxscParam = new BlUserZxsc();
        blUserZxscParam.setCreateTime(date);
        List<BlUserZxsc> blUserZxsc = blUserZxscDao.selectGrouplist(blUserZxscParam);
        String dateStr = sdf2.format(calendar.getTime());
        for(BlUserZxsc blUserZxscPar:blUserZxsc){

            QueryWrapper<UserRecharge> delWrapper = new QueryWrapper<UserRecharge>();
            delWrapper.eq("artificer_id",blUserZxscPar.getArtificerId());
            delWrapper.eq("type",1);
            delWrapper.ge("create_time",date);
            delWrapper.le("create_time",date+" 23:59:59");
            userRechargeDao.delete(delWrapper);

            UserRecharge userRecharge = new UserRecharge();
            userRecharge.setArtificerId(blUserZxscPar.getArtificerId());
            userRecharge.setUserRecharge(blUserZxscPar.getUserRecharge());
            userRecharge.setType("1");
            userRecharge.setUserId(null);
            userRecharge.setCreateTime(dateStr);
            userRechargeDao.insert(userRecharge);
        }
    }
}
