package com.xhpc.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.xhpc.auth.form.LoginBody;
import com.xhpc.auth.service.SysLoginService;
import com.xhpc.common.api.SmsService;
import com.xhpc.common.core.constant.HttpStatus;
import com.xhpc.common.core.utils.HttpUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.system.api.model.LoginUser;

import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RedisService redisService;
    public static final String URL = "http://sms.daiyicloud.com/sms/apiSend/add";
    public static final String ACCOUNT ="scxhkj";
    public static final String PASSWD ="6A9628548C4CBECCE80A2479CD77679F";
    public static final String PRODUCTLD ="20191130000001";

    /**
     * 平台管理员登陆
     * @param form
     * @return
     */
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(),0);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 运营商登陆
     * @param form
     * @return
     */
    @PostMapping("operatorLogin")
    public R<?> operatorLogin(@RequestBody LoginBody form)
    {
        //验证 输入的验证码
        String captcha = redisService.getCacheObject("pcToken:" + form.getUsername());
        if (!form.getPassword().equals(captcha)) {
            return R.fail(HttpStatus.ERROR_STATUS, "验证码错误");
        }
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), "123456",1);
        // 获取登录token
        redisService.deleteObject("pcToken:"+form.getUsername());
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 获取验证码
     * @param
     * @return
     */
    @GetMapping("sms")
    public R<?> sms(@RequestParam String phone)
    {
        //验证 输入的验证码
        //调用接口
        String pattern = "^([1][0-9]{10})";
        Pattern compile = Pattern.compile(pattern);
        Matcher m = compile.matcher(phone);
        boolean isMatch = m.matches();
        if (!isMatch) {
            return R.fail("1003", "请输入正确的手机号");
        }
        String random = getRandom();
        String content ="【小华充电】您的验证码是："+random+"，有效期为5分钟。如非本人操作，可不用理会。";
        //添加短信记录
        try {
            //用户使用的Key
            String pvToken = "pcToken:"+phone;
            //用户频繁调用的判断的Key
            String token = "pCToken:"+phone;
            String cacheObject = redisService.getCacheObject(token);
            if(cacheObject !=null){
                return R.fail("1012","操作过于频繁，请于1分钟后重试");
            }
            String req = HttpUtils.postFormData(URL, null, assembleSmsReq(phone,content));
            JSONObject json = JSONObject.parseObject(req);

            String ok = json.getString("ok");
            if("true".equals(ok)){
                redisService.setCacheObject(pvToken,random,300L, TimeUnit.SECONDS);
                //1分钟有效时间设置，防止用户频繁调用
                redisService.setCacheObject(token,random,60L, TimeUnit.SECONDS);
                return R.ok();
            }else{

                return R.fail(1012,"服务器繁忙，请稍后再试");
            }
        } catch (Exception e) {
            //e.printStackTrace();
            return R.fail(1010,"服务器繁忙，请稍后再试");
        }
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    private static HashMap<String, String> assembleSmsReq(String phone, String content) {
        HashMap<String, String> params = new HashMap<>();
        params.put("account", ACCOUNT);
        params.put("password", PASSWD);
        params.put("content", content);
        params.put("mobiles", phone);
        params.put("productId", PRODUCTLD);
        return params;
    }

    private String getRandom(){
        Random rnd = new Random();
        int i = rnd.nextInt(999999);
        if(i<100000){
            i=i+100000;
        }
        return i+"";
    }
}
