package com.zcloud.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.User;
import com.zcloud.service.system.UeditorService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.AliSmsToolUtil;
import com.zcloud.util.Const;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.RedisUtil;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * 微信公众号绑定相关
 *
 * @author fangjiakai
 * @date 2022/08/09 8:53
 */
@Controller
@RequestMapping("/wxpost")
public class WxPostController extends BaseController {
    String APPID = "wx641d6a98d89ddd03";
    String SECRET = "22cd2198a03e5a1a70351f55b3d7687d";
    @Autowired
    private RedisUtil redisutil;
    @Autowired
    private UsersService usersservice;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取openid
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping("/getopenid")
    @ResponseBody
    public Object getopenid(String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println(code);
        String wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";
        String jsonString = sendGet(wxLoginUrl, param);
        JSONObject json = JSONObject.parseObject(jsonString);
        String openid = json.getString("openid");
        System.out.println("###############" + openid);
        PageData pd = new PageData();
        pd.put("OPENID", openid);
        pd = usersservice.findByOPENID(pd);
        if (pd != null) {
            map.put("result", "fail");
            map.put("msg", "您绑定的账号已被绑定,无需重复绑定!");
            return map;
        }
        map.put("result", "success");
        map.put("openid", openid);
//        return openid;
        return map;
    }


    /**
     * 获取验证码
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/getVerifyCode")
    @ResponseBody
    public Object getVerifyCode() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("USERNAME", pd.getString("phone"));
        PageData user = usersservice.findByUsername(pd);
        if (user == null) {
            map.put("result", "fail");
            map.put("msg", "您绑定的手机号不存在!");
            return map;
        } else if (user.get("OPENID") != null && user.get("OPENID") != "") {
            map.put("result", "fail");
            map.put("msg", "您绑定的手机号已被绑定,无法重复绑定!");
            return map;
        }
        String verifycode = CAPTCHA(4);

        redisutil.set(pd.getString("phone"), verifycode, 300);
        //发送短信
        // 第1个参数
        List<PageData> paramsList = new ArrayList<PageData>();
        PageData params = new PageData();
        params.put("name", "code");// 存入短信模板中的参数名称
        params.put("value", verifycode);// 存入上面参数名称所传递的值
        paramsList.add(params);
        try {
            SendSmsResponse ssms = send("SMS_213355099", pd.getString("phone"), paramsList);
            System.out.println("短信接口返回的数据----------------");
            System.out.println("Code=" + ssms.getCode());
            System.out.println("Message=" + ssms.getMessage());
            System.out.println("RequestId=" + ssms.getRequestId());
            System.out.println("BizId=" + ssms.getBizId());
//            if (ssms.getCode().equals("OK")) {
//                map.put("result", "success");
//            } else {
//                map.put("result", "fail");
//                map.put("msg", "您的操作过去频繁，请稍后重试!");
//                return map;
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        map.put("verifycode", verifycode);				//返回结果
//        map.put("rediscode", redisutil.get(pd.getString("phone")));				//返回结果
        map.put("result", "success");
        return map;
    }

    /**
     * 获取验证码
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/verify")
    @ResponseBody
    public Object verify() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        PageData pd = new PageData();
        pd = this.getPageData();

        String verifyCode = redisutil.get(pd.getString("USERNAME")).toString();
        if (verifyCode.equals(pd.getString("verifyCode"))) {
            usersservice.editOPENID(pd);
        } else {
            map.put("result", "fail");
            map.put("msg", "验证码错误!");
            return map;
        }
        map.put("result", "success");
        return map;
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    private static String CAPTCHA(int n) {
        Random r = new Random();
        String code = "";//分配一个空字符内存
        for(int i = 0; i < n; i++) {
            int m = r.nextInt(9);//生成0~9的随机数
            code += (m + 1);
        }
        return code;
    }

    /**
     * 发送短信
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public SendSmsResponse send(String templateCode, String phone, List<PageData> paramsList) throws Exception {
        Map<String, Object> mes = new HashMap<String, Object>();
        mes.put("phone", phone);
        mes.put("templateCode", templateCode);
        // 发送短信
        SendSmsResponse ssms = AliSmsToolUtil.sendSms(mes, paramsList);
        return ssms;
    }
}
