package com.ruoyi.system.service.impl;

import cn.hutool.core.util.IdUtil;
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.StringUtils;
import com.ruoyi.system.config.UmengConfig;
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;

@Transactional
@Service
public class CShopUserServiceImpl implements ShopUserService {

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

    @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(shopUser.getPhone());
                String reqCode = shopUser.getCode();
                if (code.equals(reqCode)){
                    // 登录
                    return loginAndRegis(shopUser);
                }else {
                    ShopUser msg = new ShopUser();
                    msg.setMsg("验证码错误");
                    return msg;
                }
            case "3":
                // 一键 todo： 完善功能
                String uMtoken = shopUser.getUMtoken();
                umengConfig.send(uMtoken);
                break;
        }
        return null;
    }

    public ShopUser loginAndRegis(ShopUserResq shopUser) {
        ShopUser member = shopUserMapper.selectShopUserByPhone(shopUser.getUsername());
        if (StringUtils.isNull(member)) {
           // 走注册在登录
            member = new ShopUser();
            member.setUserId(IdUtil.getSnowflakeNextId());
            member.setUsername(shopUser.getPhone());
            member.setPhone(shopUser.getPhone());
            member.setPassword(IdUtil.fastUUID());
            member.setUsername(shopUser.getUsername());
           int insertCount = shopUserMapper.insert(member);
           if (insertCount > 0){
               return member;
           }else {
               return null;
           }
        }
        return member;
    }

}
