package com.ruoyi.system.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.UmResp;
import com.ruoyi.common.core.domain.entity.ActivityInfo;
import com.ruoyi.common.core.domain.entity.ShopUser;
import com.ruoyi.common.core.domain.entity.ShopUserResq;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.MusicUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.config.UmengConfig;
import com.ruoyi.system.mapper.ActivityInfoMapper;
import com.ruoyi.system.mapper.ShopUserMapper;
import com.ruoyi.system.service.ShopUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Transactional
@Service
public class CShopUserServiceImpl implements ShopUserService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UmengConfig umengConfig;
    @Autowired
    private ShopUserMapper shopUserMapper;
    @Autowired
    private ActivityInfoMapper activityInfoMapper;

    @Override
    public ShopUser login(ShopUserResq shopUser) {
        switch (shopUser.getMethod()){
            case "1":
                // 账号密码
                // 生成令牌
                ShopUser member = shopUserMapper.selectShopUserByUsernameAndPass(shopUser.getUsername(),shopUser.getPassword());
                if (member == null){
                    ShopUser msg = new ShopUser();
                    msg.setMsg("用户名或密码错误");
                    return msg;
                }else {
                    return member;
                }
            case "2":
                // 验证码
                //String code = redisCache.getCacheObject("sms_code:"+shopUser.getPhone());
                // TODO:写死
                String code="9527";
                String reqCode = shopUser.getCode();
                if (code != null && code.equals(reqCode)){
                    // 登录
                    shopUser.setUsername(shopUser.getPhone());
                    return loginAndRegis(shopUser);
                }else {
                    ShopUser msg = new ShopUser();
                    msg.setMsg("验证码错误");
                    return msg;
                }
            case "3":
                // 一键 todo： 完善功能
                String uMtoken = shopUser.getToken();
                String deviceType = shopUser.getDeviceType();
                String deviceTypeUp = deviceType.toUpperCase();
                UmResp resp = umengConfig.send(uMtoken, deviceTypeUp);
                if (resp != null && resp.isSuccess()){
                    String phone = (String) resp.getData().get("mobile");
                    shopUser.setPhone(phone);
                    return loginAndRegis(shopUser);
                }
                break;
        }
        return null;
    }

    @Override
    public ShopUser modifyUser(ShopUser shopUser) {
        // 先修改 在查询活动 在校验字段
        shopUserMapper.updateShopUser(shopUser);
        ActivityInfo activityInfo = activityInfoMapper.selectActivityShelfInfo();
        if (activityInfo != null) {
            // 获取当前时间
            Date date = new Date();
            Date start = activityInfo.getStartTime();
            Date end = activityInfo.getEndTime();
            // 判断 date 是否在 start 和 end 之间（包含边界）
            boolean isBetween = !date.before(start) && !date.after(end);
            // 或者如果你不想包含边界（即严格在 start 和 end 之间）
            // boolean isBetween = date.after(start) && date.before(end);
            if (isBetween) {
                // 查询用户是否已经参与过活动
                ActivityInfo activity = activityInfoMapper.selectActivityInfoByUserId(shopUser.getUserId());
                if (activity != null) {
                    return shopUser;
                }
                // 查询用户信息
                ShopUser selectShopUser = shopUserMapper.selectShopUserByUserId(shopUser.getUserId());
                if (selectShopUser.getNickname() != null &&
                        selectShopUser.getSex() != null &&
                        selectShopUser.getBirthday() != null &&
                        selectShopUser.getAddr() != null) {
                    String content = activityInfo.getContent();
                    // 查询用户是否是vip 非vip 才送
                    if (selectShopUser.getVip() == 2) {
                        selectShopUser.setVip(1L);
                        selectShopUser.setVipStartTime(new Date());
                        Date endDate = MusicUtil.getDateAfterNDays(Integer.parseInt(content));
                        selectShopUser.setVipEndTime(endDate);
                        activityInfoMapper.insertActivityUser(shopUser.getUserId(),activityInfo.getId());
                        shopUserMapper.updateShopUser(selectShopUser);
                    }
                }
            }
        }
        return shopUser;
    }

    public ShopUser loginAndRegis(ShopUserResq shopUser) {
        ShopUser member = shopUserMapper.selectShopUserByPhone(shopUser.getPhone());
        if (shopUser.getPhone() != null && StringUtils.isNull(member)) {
           // 走注册在登录
            member = new ShopUser();
            member.setUserId(IdUtil.getSnowflakeNextId());
            member.setUsername(shopUser.getPhone());
            member.setPhone(shopUser.getPhone());
            member.setStatus(1L);
            member.setVip(2L);
            member.setRegisterTime(new Date());
            member.setPassword(IdUtil.fastUUID());
            member.setUsername(shopUser.getUsername());
            member.setDeviceId(shopUser.getDeviceId());
            member.setDeviceType(shopUser.getDeviceType());
            member.setHeadImg("/file/download/user/head.jpg");
           int insertCount = shopUserMapper.insert(member);
           if (insertCount > 0){
               return member;
           }else {
               return null;
           }
        }
        return member;
    }



}
