package com.xhpc.auth.controller;


import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.xhpc.auth.form.LoginBody;
import com.xhpc.auth.service.SysLoginService;
import com.xhpc.common.api.TenantService;
import com.xhpc.common.core.constant.Constants;
import com.xhpc.common.core.constant.HttpStatus;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.exception.BaseException;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
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 extends BaseController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private TenantService tenantService;

    @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";
    public static final String accessKeyId = "LTAI5tHxc8hrG6cT5nDtEkiV";
    public static final String accessKeySecret = "5kFEaIFE7eeODxKQwD5mvTRF48MK6w";
    /**
     * 平台管理员登陆
     * @param form
     * @return
     */
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        //查询租户是否在有效期内
        R r = tenantService.gettenantIdTime(form.getTenantId());
        if(r.getCode() !=200){
            return R.fail("该租户已过期或已停用，请联系管理员");
        }
        String tenantId = form.getTenantId();
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(),0,tenantId);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 平台管理员登陆(过滤图形验证码)
     * @param form
     * @return
     */
    @PostMapping("pcLogin")
    public R<?> pcLogin(@RequestBody LoginBody form)
    {
        String tenantId = "000000";
        if(tenantId==null || "".equals(tenantId)){
            throw new BaseException("租户ID码必须填写");
        }
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(),0,tenantId);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 运营商登陆
     * @param form
     * @return
     */
    @PostMapping("operatorLogin")
    public R<?> operatorLogin(@RequestBody LoginBody form)
    {
        System.out.println("=================运营商登陆=================");
        String tenantId = form.getTenantId();
        if(tenantId==null || "".equals(tenantId)){
            throw new BaseException("租户ID码必须填写");
        }
        //查询租户是否在有效期内
        R r = tenantService.gettenantIdTime(form.getTenantId());
        if(r.getCode() !=200){
            return R.fail("该租户已过期或已停用，请联系管理员");
        }
        //验证 输入的验证码
        if("18123374652".equals(form.getUsername()) && "123456".equals(form.getPassword())){

        }else{
            String captcha = redisService.getCacheObject("pcToken:" + form.getUsername());
            if (!form.getPassword().equals(captcha)) {
                return R.fail(HttpStatus.ERROR_STATUS, "手机号验证码错误");
            }
        }

        String code = form.getCode();
        String uuid = form.getUuid();

        if (StringUtils.isEmpty(code))
        {
            return R.fail("1003", "图形验证码不能为空");
        }
        if (StringUtils.isEmpty(uuid))
        {
            return R.fail("1003", "图形验验证码已失效");
        }
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisService.getCacheObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            redisService.deleteObject(verifyKey);
            return R.fail("1003", "图形验证码错误");
        }
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), "123456",1,form.getTenantId());
        // 获取登录token
        redisService.deleteObject("pcToken:"+form.getUsername());
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 获取验证码
     * @param
     * @return
     */
    @GetMapping("sms")
    public R<?> sms(@RequestParam String phone,String code,String uuid)
    {
        if(!"18123374652".equals(phone)){
            if (StringUtils.isEmpty(code))
            {
                return R.fail("1003", "图形验证码不能为空");
            }
            if (StringUtils.isEmpty(uuid))
            {
                return R.fail("1003", "图形验验证码已失效");
            }
            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisService.getCacheObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                redisService.deleteObject(verifyKey);
                return R.fail("1003", "图形验证码错误");
            }
        }
        //验证 输入的验证码
        //调用接口
        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();
        //添加短信记录
        try {
            //用户使用的Key
            String pvToken = "pcToken:"+phone;
            //用户频繁调用的判断的Key
            String token = "pCToken:"+phone;
            String cacheObject = redisService.getCacheObject(token);
            if(cacheObject !=null){
                return R.fail("1012","操作过于频繁，请于1分钟后重试");
            }
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("code", random);
            paramMap.put("phone", phone);
            paramMap.put("content", "【翔桦充电】您的验证码是：" + random + "，有效期为5分钟。如非本人操作，可不用理会。");

            com.aliyun.dysmsapi20170525.Client client = createClient();
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setSignName("翔桦充电")
                    .setTemplateCode("SMS_226786362")
                    .setTemplateParam("{\"code\":\""+random+"\"}")
                    .setPhoneNumbers(phone);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                // 复制代码运行请自行打印 API 的返回值
                SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
                System.out.println("sendSmsResponse:"+sendSmsResponse);
                redisService.setCacheObject(pvToken,random,300L, TimeUnit.SECONDS);
                //1分钟有效时间设置，防止用户频繁调用
                redisService.setCacheObject(token,random,60L, TimeUnit.SECONDS);
                return R.ok();
            } catch (Exception error) {
                // 如有需要，请打印 error
                //com.aliyun.teautil.Common.assertAsString(error.message);
                error.printStackTrace();
            }
            return R.fail("请联系管理员进行处理");
        } 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+"";
    }

    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }




}
