package com.yinet.web.controller.xcqh;

import com.alibaba.fastjson.JSONObject;
import com.yinet.common.core.domain.AjaxResult;
import com.yinet.wx.service.WxService;
import com.yinet.xcqh.domain.Xcqh;
import com.yinet.xcqh.service.XcqhService;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

/**
 * 现场取号列表Controller
 *
 * @author yinet
 * @date 2019-09-02
 */
@Controller
@RequestMapping("/xcqh/web")
public class XcqhBaseController {
    public static final String TOKEN = "yinet";

    private String prefix = "xcqh/";
    @Autowired
    private XcqhService xcqhService;
    @Autowired
    private WxService wxService;

    @GetMapping("/index")
    public String index(String code, String state, ModelMap mmap) throws IOException {
        JSONObject openIdByCode = wxService.getOpenIdByCode(code);
        Map<String, String> sign = wxService.sign("http://hfs.free.idcfengye.com/xcqh/web/index?code=" + code + "&state=" + state);
        mmap.addAttribute("sign", sign);
        mmap.addAttribute("openid", openIdByCode.getString("openid"));
        return prefix + "/xcqh";
    }

    @GetMapping("/wxApi")
    @ResponseBody
    public String wxApi(String signature, String timestamp, String nonce, String echostr) throws NoSuchAlgorithmException {
        // 开发者提交信息后，微信服务器将发送GET请求到填写的服务器地址URL上，GET请求携带参数
        // 将token、timestamp、nonce三个参数进行字典序排序
        String[] params = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(params);
        // 将三个参数字符串拼接成一个字符串进行sha1加密
        String clearText = params[0] + params[1] + params[2];
        String algorithm = "SHA-1";
        String sign = new String(
                Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes()), true));
        // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (signature.equals(sign)) {
            return echostr;
        } else {
            return "";
        }
    }

    @PostMapping()
    @ResponseBody()
    public AjaxResult callUser() {
        return AjaxResult.success("呼叫成功");
    }

    @PostMapping("/saveXcqh")
    @ResponseBody
    public String saveXcqh(Xcqh xcqh) throws IOException {
        int i = xcqhService.insertXcqh(xcqh);
        return String.valueOf(i);
    }
    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa0dc5575b0f05d2c&redirect_uri=http://hfs.free.idcfengye.com/xcqh/web/wxApiGetUser&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
}