package shop.alien.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeSys;
import shop.alien.entity.store.UserLoginInfo;
import shop.alien.entity.store.vo.SystemLoginVo;
import shop.alien.store.config.BaseRedisService;
import shop.alien.mapper.LifeSysMapper;
import shop.alien.store.service.SystemService;
import shop.alien.util.common.JwtUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 商家会员记录 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-02-20
 */
@Service
@RequiredArgsConstructor
public class SystemServiceImpl implements SystemService {

    private final LifeSysMapper lifeSysMapper;

    private final BaseRedisService baseRedisService;

    @Value("${jwt.expiration-time}")
    private String effectiveTime;

    @Override
    public SystemLoginVo login(String username, String password) {
        int effectiveTimeInt = Integer.parseInt(effectiveTime.substring(0, effectiveTime.length() - 1));
        String effectiveTimeUnit = effectiveTime.substring(effectiveTime.length() - 1);
        long effectiveTimeIntLong = 0L;
        switch (effectiveTimeUnit) {
            case "s": {
                effectiveTimeIntLong = effectiveTimeInt * 1000L;
                break;
            }
            case "m": {
                effectiveTimeIntLong = effectiveTimeInt * 60L * 1000L;
                break;
            }
            case "h": {
                effectiveTimeIntLong = effectiveTimeInt * 60L * 60L * 1000L;
                break;
            }
            case "d": {
                effectiveTimeIntLong = effectiveTimeInt * 24L * 60L * 60L * 1000L;
                break;
            }
        }
        SystemLoginVo result = new SystemLoginVo();
        //给密码加密MD5，查询用户是否存在
        LifeSys lifeSys = lifeSysMapper.selectOne(
                new LambdaQueryWrapper<LifeSys>()
                        .eq(LifeSys::getUserName, username)
        );
        if (lifeSys != null && lifeSys.getUserPassword().equals(encryptToMD5(password))) {
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("phone", "123456");
            tokenMap.put("userName", lifeSys.getUserName());
            tokenMap.put("userId", String.valueOf(lifeSys.getId()));
            tokenMap.put("userType", "web");
            //存入token
            result.setToken(JwtUtil.createJWT("web_" + lifeSys.getId(), lifeSys.getUserName(), JSONObject.toJSONString(tokenMap), effectiveTimeIntLong));
            baseRedisService.setString("web_" + lifeSys.getUserName(), result.getToken());
            //登录结果
            result.setResult(true);
            //登录结果
            result.setMessage("登录成功！！");
        } else {
            result.setResult(false);
            result.setMessage("用户名或者密码错误，请确认！！");
        }
        return result;
    }

    @Override
    public SystemLoginVo logout(UserLoginInfo userLoginInfo) {
        //JWT移除token
        return null;
    }

    @Override
    public R<LifeSys> register(String userName, String password, String roleId) {
        // 校验必填字段
        if (!StringUtils.hasText(userName)) {
            return R.fail("用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            return R.fail("密码不能为空");
        }

        // 校验用户名是否已存在
        LambdaQueryWrapper<LifeSys> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeSys::getUserName, userName);
        LifeSys existingUser = lifeSysMapper.selectOne(queryWrapper);
        if (existingUser != null) {
            return R.fail("该用户名已存在，请更换其他用户名");
        }

        // 创建新用户
        LifeSys lifeSys = new LifeSys();
        lifeSys.setUserName(userName);
        // 密码使用MD5加密后存储
        lifeSys.setUserPassword(encryptToMD5(password));
//        if (StringUtils.hasText(roleId)) {
//            lifeSys.setRoleId(roleId);
//        }
        lifeSys.setDeleteFlag(0); // 未删除

        // 保存用户
        int result = lifeSysMapper.insert(lifeSys);
        if (result > 0) {
            return R.data(lifeSys, "注册成功");
        }
        return R.fail("注册失败，请稍后重试");
    }

    public static String encryptToMD5(String input) {
        try {
            // 获取 MD5 算法的 MessageDigest 实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 将输入的字符串转换为字节数组，并进行 MD5 计算
            byte[] messageDigest = md.digest(input.getBytes());

            // 创建一个 StringBuilder 用于存储十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                // 将字节转换为十六进制字符串
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    // 如果十六进制字符串长度为 1，则在前面补 0
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回最终的 MD5 加密后的十六进制字符串
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            // 若指定的算法（MD5）不可用，抛出运行时异常
            throw new RuntimeException(e);
        }
    }

}
