package com.ruoyi.web.controller.chenyanlogin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * @Project : huimv.shiwan
 * @Package : com.ruoyi.web.controller.chenyanlogin
 * @Description : TODO
 * @Author : yuxuexuan
 * @Create : 2025-09-11 15:14
 **/
@Api(tags = "获取账号信息")
@RestController
@RequestMapping("/system")
public class ChenYanLoginController {



    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysLoginService loginService;

    @GetMapping("/phoneToken")
    public AjaxResult phoneToken( ) throws Exception {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> user = new HashMap<>();
        user.put("phone", sysUserService.selectUserById(userId).getPhonenumber());
        user.put("time", System.currentTimeMillis());

        String s = JSONUtil.toJsonStr(user);

        String encryptedData = AESUtil.encrypt(s);
        System.out.println("加密后的数据: " + encryptedData);
        return success("生成成功",encryptedData);

    }

    @PostMapping("/getToken")
    public AjaxResult list(HttpServletRequest httpServletRequest, @RequestBody LoginVo loginVo) throws ParseException {
//        try {
            if (ObjectUtil.isEmpty(loginVo)) {
                return error("数据格式不正确");
            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder
                    .append(loginVo.getTime())
                    .append("be5312e95c43624b52399a24ac268876")
                    .append(loginVo.getPhone());
            String mac = loginVo.getMac();
            String s = DigestUtils.md5DigestAsHex(stringBuilder.toString().getBytes()).toLowerCase();
            System.out.println(s);
            System.out.println(mac);
            if (!s.equals(mac)) {
                return error("序列校验不通过");
            }
            System.out.println(loginVo.toString());
            if (!isValidPhoneNumber(loginVo.getPhone())){
                return error("手机号格式不正确");
            }
            SysUser phonenumber = sysUserService.selectUserByPhone(loginVo.getPhone());
            if (ObjectUtil.isEmpty(phonenumber)){
                phonenumber  = new SysUser();
                phonenumber.setUserName(loginVo.getPhone());
                phonenumber.setPhonenumber(loginVo.getPhone());
                phonenumber.setNickName("测试");
                phonenumber.setSex("0");
                phonenumber.setPassword("$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2");
                sysUserService.registerUser(phonenumber);
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(4L);
                SysUser sysUser = sysUserService.selectUserByPhone(loginVo.getPhone());
                sysUserRole.setUserId(sysUser.getUserId());
                List list = new ArrayList();
                list.add(sysUserRole);
                sysUserRoleMapper.batchUserRole(list);

                AjaxResult ajax = AjaxResult.success();
                // 生成令牌
                String token = loginService.loginNoCaptcha(sysUser.getUserName(), "admin123");
                ajax.put(Constants.TOKEN, token);
                return ajax;
            }else{
                AjaxResult ajax = AjaxResult.success();
                String token = loginService.loginNoCaptcha(phonenumber.getUserName(),"admin123");
                ajax.put(Constants.TOKEN, token);
                return ajax;
            }
//        }catch (Exception e){
//            System.out.println(e);
//            return error("其它异常");
//        }

    }

    public static boolean isValidPhoneNumber(String phoneNumber) {

        // 处理空值或null情况
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false;
        }
        // 使用正则表达式校验
        return phoneNumber.matches( "^1[3-9]\\d{9}$");
    }
    public static void main(String[] args) {
        try {
//            String secretKey = AESUtil.generateKey();
//            System.out.println("生成的密钥（保存好，解密时需用）: " + secretKey);
            String jiami = jiami();

            jiemi(jiami);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   public static String jiami() throws Exception {
//        String originalData = "13140429955";
       Map<String, Object> user = new HashMap<>();
       user.put("phone", "13140429955");
       user.put("time", System.currentTimeMillis());

       String s = JSONUtil.toJsonStr(user);

       String encryptedData = AESUtil.encrypt(s);
        System.out.println("加密后的数据: " + encryptedData);
        return encryptedData;

    }
    public static void  jiemi(String jiami) throws Exception {
        String decryptedData = AESUtil.decrypt(jiami);
            System.out.println("解密后的数据: " + decryptedData);

    }

}
