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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserVipDao;
import com.sqx.modules.app.dao.VipDetailsDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserVip;
import com.sqx.modules.app.entity.VipDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.service.UserVipService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.tbCoupon.entity.TbCoupon;
import jodd.util.StringUtil;
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.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class UserVipServiceImpl extends ServiceImpl<UserVipDao, UserVip> implements UserVipService {

    @Autowired
    private VipDetailsDao vipDetailsDao;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;

    @Override
    public UserVip selectUserVipByUserId(Long userId) {
        QueryWrapper<UserVip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public Result isUserVip(Long userId) {
        boolean isVip = false;
        //查询用户是否是会员
        QueryWrapper<UserVip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserVip userVip = baseMapper.selectOne(queryWrapper);
        if (userVip != null) {
            if (userVip.getIsVip() == 1) {
                isVip = true;
            }
        }
        return Result.success().put("data", isVip);
    }

    @Override
    public Result setMember(Long vipId, Long userId){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查看要开通会员类型
        VipDetails vipDetails = vipDetailsDao.selectOne(new QueryWrapper<VipDetails>().eq("id", vipId));
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        MessageInfo messageInfo = new MessageInfo();
        userMoneyDetails.setMoney(vipDetails.getMoney());
        userMoneyDetails.setUserId(userId);
        if ((vipDetails.getVipNameType().equals(0))) {
            //月
            userMoneyDetails.setContent("开通月卡会员");
            messageInfo.setContent("开通会员成功");
        } else if ((vipDetails.getVipNameType()).equals(1)) {
            //季
            userMoneyDetails.setContent("开通季卡会员");
            messageInfo.setContent("开通会员成功");
        } else {
            //年
            userMoneyDetails.setContent("开通年费会员");
            messageInfo.setContent("开通会员成功");
        }
        userMoneyDetails.setTitle("开通会员");
        userMoneyDetails.setType(2);
        userMoneyDetails.setClassify(1);
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);
        UserEntity userEntity = userService.selectUserById(userId);
        UserEntity zhiUser = userService.queryByInvitationCode(userEntity.getInviterCode());
        if(zhiUser!=null){
            BigDecimal zhiRate = new BigDecimal(zhiUser.getDivideScale());
            if(zhiRate.doubleValue()>0){
                BigDecimal zhiMoney = zhiRate.multiply(vipDetails.getMoney()).setScale(2,BigDecimal.ROUND_DOWN);
                userMoneyService.updateInviteMoney(1,zhiUser.getUserId(),zhiMoney.doubleValue());
                userMoneyDetails=new UserMoneyDetails();
                userMoneyDetails.setTitle("一级开通会员");
                userMoneyDetails.setContent("到账收益："+zhiMoney);
                userMoneyDetails.setUserType(1);
                userMoneyDetails.setUserId(zhiUser.getUserId());
                userMoneyDetails.setMoney(zhiMoney);
                userMoneyDetails.setType(1);
                userMoneyDetails.setClassify(8);
                userMoneyDetails.setUserLevel(1);
                userMoneyDetails.setRelationId(userEntity.getUserId());
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
            }
            UserEntity feiUser = userService.queryByInvitationCode(zhiUser.getInviterCode());
            if(feiUser!=null){
                BigDecimal feiRate = new BigDecimal(feiUser.getDivideTwoScale());
                if(feiRate.doubleValue()>0){
                    BigDecimal feiMoney = feiRate.multiply(vipDetails.getMoney()).setScale(2,BigDecimal.ROUND_DOWN);
                    userMoneyService.updateInviteMoney(1,zhiUser.getUserId(),feiMoney.doubleValue());
                    userMoneyDetails=new UserMoneyDetails();
                    userMoneyDetails.setTitle("二级开通会员");
                    userMoneyDetails.setContent("到账收益："+feiMoney);
                    userMoneyDetails.setUserType(1);
                    userMoneyDetails.setUserId(zhiUser.getUserId());
                    userMoneyDetails.setMoney(feiMoney);
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setClassify(8);
                    userMoneyDetails.setUserLevel(2);
                    userMoneyDetails.setRelationId(userEntity.getUserId());
                    userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                    userMoneyDetailsService.save(userMoneyDetails);
                }

            }
        }


        //查看用户是否是会员
        UserVip userVip = baseMapper.selectOne(new QueryWrapper<UserVip>().eq("user_id", userId));
        //日历
        Calendar cal = Calendar.getInstance();
        if (userVip != null) {
            userVip.setIsVip(1);
            //是会员
            //查看会员到期时间
            Date endDate = null;
            try {
                endDate = simpleDateFormat.parse(userVip.getEndTime());
            } catch (Exception e) {
                e.getMessage();
            }
            //查看会员是否到期
            if (endDate != null && System.currentTimeMillis() < (endDate.getTime())) {
                //没有到期
                if (vipDetails != null) {
                    //设置会员到期时间到日历
                    cal.setTime(endDate);
                    //判断会员的续费时间
                    if ((vipDetails.getVipNameType().equals(0))) {
                        //月
                        cal.add(Calendar.MONTH, 1);
                    } else if ((vipDetails.getVipNameType()).equals(1)) {
                        //季
                        cal.add(Calendar.MONTH, 3);
                    } else {
                        //年
                        cal.add(Calendar.YEAR, 1);
                    }
                    //设置会员的到期时间
                    userVip.setEndTime(simpleDateFormat.format(cal.getTime()));
                    //更新会员信息
                    baseMapper.updateById(userVip);
                    return Result.success("开通成功！");
                }
            } else {
                //到期了
                //将现在的时间设置到日历中去
                cal.setTime(new Date());
                //判断会员续费的时间
                if ((vipDetails.getVipNameType()).equals(0)) {
                    //月
                    cal.add(Calendar.MONTH, 1);
                } else if ((vipDetails.getVipNameType()).equals(1)) {
                    //季
                    cal.add(Calendar.MONTH, 3);
                } else {
                    //年
                    cal.add(Calendar.YEAR, 1);
                }
                //设置会员的到期时间
                userVip.setEndTime(simpleDateFormat.format(cal.getTime()));
                //更新会员信息
                baseMapper.updateById(userVip);
                return Result.success("开通成功！");
            }

        } else {
            //不是会员
            //创建会员对象
            UserVip userVip1 = new UserVip();
            //设置会员类型
            userVip1.setVipNameType(vipDetails.getVipNameType());
            //设置开通会员的用户id
            userVip1.setUserId(userId);
            //设置会员的购买时间
            userVip1.setCreateTime(simpleDateFormat.format(new Date()));
            //将现在时间设置到日历中
            cal.setTime(new Date());
            //判断会员的续费时间
            if ((vipDetails.getVipNameType()).equals(0)) {
                //月
                cal.add(Calendar.MONTH, 1);
            } else if ((vipDetails.getVipNameType()).equals(1)) {
                //季
                cal.add(Calendar.MONTH, 3);
            } else {
                //年
                cal.add(Calendar.YEAR, 1);
            }
            //设置会员的到期时间
            userVip1.setEndTime(simpleDateFormat.format(cal.getTime()));
            userVip1.setIsVip(1);
            //设置会员
            baseMapper.insert(userVip1);
        }
        return Result.success("开通成功！");
    }


    /**
     * 会员到期检测
     */
    @Scheduled(cron = "0/2 * * * * ?", zone = "Asia/Shanghai")
    public void userVipCheck() {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<UserVip> userVipList = baseMapper.selectList(new QueryWrapper<UserVip>().eq("is_vip", 1));
        for (UserVip userVip : userVipList) {
            if (LocalDateTime.now().isAfter(LocalDateTime.parse(userVip.getEndTime(), fmt))) {
                userVip.setIsVip(2);
                baseMapper.updateById(userVip);
            }
        }
    }

}
