package com.limap.controller.work;


import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.limap.common.core.controller.BaseController;
import com.limap.common.core.domain.AjaxResult;
import com.limap.common.core.domain.entity.SysUser;
import com.limap.common.core.domain.model.LoginBody;
import com.limap.common.core.redis.RedisCache;
import com.limap.common.log.annotation.Log;
import com.limap.common.utils.SecurityUtils;
import com.limap.common.utils.StringUtils;
import com.limap.common.utils.ali.SendSmsUtil;
import com.limap.common.utils.http.HttpUtils;
import com.limap.system.service.ISysUserService;
import com.limap.system.service.SysLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author jjb
 */
@Api(tags = "短息登录")
@RestController
@RequestMapping("/sms")
@Slf4j
public class AppLoginController extends BaseController {
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;


    private  static String appId = "wx26776caf9fbb6a1d";
    private  static String secret = "8c6a2fd12255dc490322de3acb1bc32a";

    private final static String KEY_INDEX = "phoneCode:";

    @ApiOperation("获取验证码")
    @Log(title = "获取验证码")
    @PostMapping("/getCode")
    public AjaxResult getCode(@RequestBody LoginBody loginBody) throws Exception {
        String username = loginBody.getTel();
        if(StringUtils.isBlank(username)){
            return AjaxResult.error("手机号不能为空");
        }else{
            if(!StringUtils.isPhoneNumberValid(username)){
                return AjaxResult.error("请输入正确手机号");
            }
            Object cacheObject = redisCache.getCacheObject(KEY_INDEX + username);
            if (cacheObject != null) {
                redisCache.deleteObject(KEY_INDEX + username);
            }
            String s = RandomUtil.randomNumbers(6);
            JSONObject object = new JSONObject();
            object.put("code",s);
            boolean b = SendSmsUtil.sendCodeSms(object, username);
            if(b){
                redisCache.setCacheObject(KEY_INDEX + username,s,31, TimeUnit.MINUTES);
                return AjaxResult.success();
            }
        }
        return AjaxResult.error("获取验证码失败,请稍后再试");
    }

    @ApiOperation("用户登录")
    @Log(title = "用户登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) throws Exception {
        return loginService.login(loginBody);
    }




    public static String creatCode(int n) {
        //3、定义一个字符串变量记录生成的随机字符
        String code = "";
        Random r = new Random();
        //2、定义一个for循环，循环n次，依次生成随机字符
        for (int i = 0; i < n; i++) {
            //i=0 1 2
            //3、生成一个随机字符，英文大、小写 数字（0 1 2 ）
            int type = r.nextInt(3);
            switch (type) {
                case 0:
                    //大写字符（A 65-Z 65+25）
                    char ch = (char) (r.nextInt(26) + 65);
                    code += ch;
                    break;
                case 1:
                    //小写字符（a 97-z 97+25）
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                case 2:
                    //数字字符
                    code += r.nextInt(10);//0-9
                    break;
                default:
                    break;
            }
        }
        return code;
    }

    private static String random3() {
        // nextInt(int origin, int bound) 范围：[origin,bound)
        // 包左 不包右
        return String.valueOf(ThreadLocalRandom.current().nextInt(100000, 1000000));
    }

    public  String getOpenId(String code) {
        String openId = null;
        String resultOpen = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session?"+
                "appid="  + appId +
                "&secret=" + secret+
                "&js_code="+ code +
                "&grant_type=authorization_code",null);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(resultOpen);
        if (jsonObject.containsKey("errcode")) {
            log.info("code无效，openId获取失败——小程序获取");
            return  null;
        }
        openId = jsonObject.get("openid").toString();
        return openId ;
    }

    public String getWxToken(){
        String wxAccessToken = (String)redisCache.getCacheObject("wx_accessToken");
        if(wxAccessToken!= null){
            return wxAccessToken;
        }
        String s = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret=" +secret);
        try{
            JSONObject object = JSONObject.parseObject(s);
            String accessToken = object.getString("access_token");
            Integer expiresIn = object.getInteger("expires_in");
            redisCache.setCacheObject("wx_accessToken",accessToken,expiresIn,TimeUnit.SECONDS);
            return accessToken;
        }catch (Exception e){
            return null;
        }
    }

    public String getWxPhone(String code){
        String wxToken = getWxToken();
        if(wxToken == null){
            throw new RuntimeException("获取微信token失败");
        }
        Map<String,String> params = new HashMap<>();
        params.put("code",code);
        String s = HttpUtils.sendPost("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + wxToken, JSONObject.toJSONString(params));
        try{
            JSONObject object = JSONObject.parseObject(s);
            JSONObject phone_info = object.getJSONObject("phone_info");
            return phone_info.getString("purePhoneNumber");
        }catch (Exception e){
           log.error("获取微信用户手机号异常：{}",e.getMessage());
        }
        return null;
    }
}
