package cn.pluss.platform.task;


import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.UserRoleEnum;
import cn.pluss.platform.mapper.InviteRateMapper;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.officialActivity.OfficialActivityService;
import cn.pluss.platform.userInfo.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class MercIncomSetRateHandler {


    private final UserAppMapper userAppMapper;

    private final InviteRateMapper inviteRateMapper;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantBaseInfoService merchantBaseInfoService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private UserInfoService userInfoService;

    private final OfficialActivityService officialActivityService;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public void installSuperMerchantRate(UserApp userApp){
        log.info("==============>统计当前进件商户上级要求人数是否达标，开始,进件商户:{}<=================",userApp);
         QueryWrapper<UserApp> queryWrapper = new QueryWrapper<UserApp>().eq("userId",userApp.getParentId());
         UserApp parentApp = null;
         try {
             parentApp = userAppMapper.selectOne(queryWrapper);
         }catch (RuntimeException e){
             e.printStackTrace();
         }
         if(parentApp == null){
             log.info("==============当前进件商户的上级用户信息为空！<=================");
             return;
         }
         if(!"promoter".equals(parentApp.getUserType())){
             log.info("==============当前进件商户的上级不为服务商！<=================");
             return;
         }
        if(UserRoleEnum.ZY_BST.getCode().equals(parentApp.getRoleCode())){
            log.info("==============直营团队用户暂不支持该活动！<=================");
            return;
        }
         QueryWrapper<InviteRate> queryRate = new QueryWrapper<InviteRate>().eq("type","merchant").orderByAsc("number");
         List<InviteRate> inviteRateList = inviteRateMapper.selectList(queryRate);
         if(inviteRateList.isEmpty()){
             log.info("==============未获取到邀请好友费率阶梯设置表记录<=================");
             return;
         }
         InviteRate rate = inviteRateList.get(0);
         OfficialActivity act = officialActivityService.getById(rate.getActId());
         if(act == null){
             log.info("==============未获取到当前活动信息<=================");
             return;
         }
         if(!"2".equalsIgnoreCase(act.getStatus())){
             log.info("==============活动已过期或还未开始！<=================");
             return;
         }
         Page<MerchantBaseInfo> merchantPage = new Page<MerchantBaseInfo>();
         merchantPage.setCurrent(1);
         merchantPage.setSize(10);
         parentApp.setStartDate(act.getStartTime());
         parentApp.setEndDate(act.getEndTime());
         merchantPage = merchantBaseInfoService.pageJoinData(merchantPage,parentApp);
         long total = merchantPage.getTotal();
         try {
             log.info("==============当前进件商户上级拥有推广商户总数为:{},阶梯费率修改所需要的进件商户数量为：{}<=================",total,rate.getNumber());
             if(total < rate.getNumber()){
                 log.info("==============当前进件商户上级商户邀请人数为:{},不满足设置的人数:{},无需修改费率<=================",total,rate.getNumber());
                 return;
             }else if(total >= rate.getNumber()){
                 log.info("==============当前商户进件上级满足第一梯队，上级推广商户数量为：{}，费率阶梯第一梯队需要进件商户数量为：{}<=================",total,rate.getNumber());
                 InviteRate nextRate = inviteRateList.get(1);
                 if(total < nextRate.getNumber()){
                     log.info("==============当前商户进件上级满足第一梯队不满足第二梯队，上级推广商户数量为：{}，费率阶梯第二梯队需要进件商户数量为：{}<=================",total,nextRate.getNumber());
                     userInfoService.changeRate(parentApp.getUserId()+"",rate.getRate().multiply(new BigDecimal(100)).intValue());
                 }else if(total >= nextRate.getNumber()){
                     log.info("==============当前商户进件上级满足第一梯队,满足第二梯队，上级推广商户数量为：{}，费率阶梯第二梯队需要进件商户数量为：{}<=================",total,nextRate.getNumber());
                     userInfoService.changeRate(parentApp.getUserId()+"",nextRate.getRate().multiply(new BigDecimal(100)).intValue());
                 }
             }else{
                 log.info("============>未知判断，当前商户上级拥有商户总数为:{},费率阶梯需要商户进件的数量为：{}====================",total,rate.getNumber());
             }
         }catch (RuntimeException e){
             e.printStackTrace();
             log.info("修改费率异常，异常：{}",e.getMessage());
         }
    }

    /**
     * 修改商户费率
     * @param userApp
     * @param rate
     */
//    public void setUpMerchantRate(UserApp userApp, BigDecimal rate,Date startTime,Date endTime) {
//        log.info("设置商户:{}，费率为:{}===============>",userApp,rate);
//        MerchantRateRecord rateRecord = new MerchantRateRecord();
//        QueryWrapper<MerchantRate> queryWrapper = new QueryWrapper<MerchantRate>().eq("userId",userApp.getUserId());
//        List<MerchantRate> merchantRateList = merchantRateMapper.selectList(queryWrapper);
//        Integer rateValue = rate.multiply(new BigDecimal("100")).intValue();
//        rateRecord.setRate(rateValue);
//        rateRecord.setUserId(String.valueOf(userApp.getUserId()));
//        rateRecord.setCreateTime(new Date());
//        if(merchantRateList.isEmpty()){
//            // 该商户没有设置过费率
//            userInfoService.changeRate(String.valueOf(userApp.getUserId()),
//                    rateValue);
////            sxfChangeRateService.process(String.valueOf(userApp.getUserId()),rateValue,null);
//            MerchantRate merchantRate = new MerchantRate();
//            merchantRate.setUserId(String.valueOf(userApp.getUserId()));
//            merchantRate.setRate(rateValue);
//            merchantRate.setPreviousRate(38);
//            merchantRate.setStartTime(startTime);
//            merchantRate.setEndTime(endTime);
//            merchantRate.setIsFixedRate("0");
//            merchantRateMapper.insert(merchantRate);
//            rateRecord.setRate(rateValue);
//            merchantRateRecordMapper.insert(rateRecord);
//            log.info("设置商户:{}费率，费率为:{},设置成功！===============>",userApp,rate);
//        }else{
//            MerchantRate merchantRate = merchantRateList.get(0);
//            if(merchantRate.getRate() > rateValue){
//                userInfoService.changeRate(String.valueOf(userApp.getUserId()),
//                        rateValue);
//                merchantRate.setPreviousRate(merchantRate.getRate());
//                merchantRate.setRate(rateValue);
//                merchantRate.setUpdateTime(new Date());
//                merchantRate.setIsFixedRate("0");
//                merchantRate.setStartTime(startTime);
//                merchantRate.setEndTime(endTime);
//                merchantRateMapper.updateById(merchantRate);
//                merchantRateRecordMapper.insert(rateRecord);
//                log.info("设置商户:{}费率，原始费率:{},更新后的费率为:{},设置成功！===============>",userApp,merchantRate.getRate(),rateValue);
//            }else{
//                log.info("设置商户:{}费率，商户原始费率:{},需更新的费率:{},当前商户费率低于需要更新的费率,无需更新===============>",userApp,merchantRate.getRate(),rateValue);
//            }
//        }
//        log.info("设置商户费率结束");
//    }
}
