package com.bofeng.wx;

import com.bofeng.support.WeChatProperties;
import com.yvan.ModelOps;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by luoyifan on 2017/8/24.
 */
@RestController
@Slf4j
public class WxController {

    private final WeChatProperties weChatProperties;
    private final WxMpService wxService;
    private final WxMpMessageRouter wxMpMessageRouter;

    @Autowired
    public WxController(WeChatProperties weChatProperties, WxMpService wxService, WxMpMessageRouter wxMpMessageRouter) {
        this.weChatProperties = weChatProperties;
        this.wxService = wxService;
        this.wxMpMessageRouter = wxMpMessageRouter;
    }

    @GetMapping("/wx/mp")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);

        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }


    @PostMapping("/wx/mp")
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();

        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return wxMpMessageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }
        return null;
    }

    @RequestMapping(value = "/wx/create_menu", method = RequestMethod.GET)
    public ModelOps createMenu() throws WxErrorException {
        val menu = new WxMenu();

        //推介客户
        val btn1 = new WxMenuButton();
        btn1.setName("进入");
        btn1.setType(WxConsts.MenuButtonType.VIEW);
        btn1.setUrl(
                wxService.oauth2buildAuthorizationUrl(weChatProperties.getDomain() +
                                "/user/home.html",
                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null)
        );

//        val btn2 = new WxMenuButton();
//        btn2.setName("业委会");
//
//        val btn21 = new WxMenuButton();
//        btn21.setName("每日上报");
//        btn21.setType(WxConsts.MenuButtonType.VIEW);
//        btn21.setUrl(
//                wxService.oauth2buildAuthorizationUrl(weChatProperties.getDomain() +
//                                "/cust/commission.html",
//                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null)
//        );
//
//        val btn22 = new WxMenuButton();
//        btn22.setName("求助");
//        btn22.setType(WxConsts.MenuButtonType.VIEW);
//        btn22.setUrl(
//                wxService.oauth2buildAuthorizationUrl(weChatProperties.getDomain() +
//                                "/cust/history.html",
//                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null)
//        );
//
//        btn2.getSubButtons().add(btn21);
//        btn2.getSubButtons().add(btn22);
//
//
//        //我的
//        val btn3 = new WxMenuButton();
//        btn3.setName("我的家");
//
//        val btn31 = new WxMenuButton();
//        btn31.setName("健康日报");
//        btn31.setType(WxConsts.MenuButtonType.VIEW);
//        btn31.setUrl(
//                wxService.oauth2buildAuthorizationUrl(weChatProperties.getDomain() +
//                                "/cust/account.html",
//                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null)
//        );
//
//        val btn32 = new WxMenuButton();
//        btn32.setName("家庭求助");
//        btn32.setType(WxConsts.MenuButtonType.VIEW);
//        btn32.setUrl(
//                wxService.oauth2buildAuthorizationUrl(weChatProperties.getDomain() +
//                                "/cust/sub.html",
//                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null)
//        );
//
//        val btn33 = new WxMenuButton();
//        btn33.setName("我的二维码");
//        btn33.setType(WxConsts.MenuButtonType.VIEW);
//        btn33.setUrl(
//                wxService.oauth2buildAuthorizationUrl(weChatProperties.getDomain() +
//                                "/cust/user_place_list.html",
//                        WxConsts.OAuth2Scope.SNSAPI_USERINFO, null)
//        );
//
//        btn3.getSubButtons().add(btn31);
//        btn3.getSubButtons().add(btn32);
//        btn3.getSubButtons().add(btn33);

        menu.getButtons().add(btn1);
//        menu.getButtons().add(btn2);
//        menu.getButtons().add(btn3);
        wxService.getMenuService().menuCreate(menu);
        return ModelOps.newSuccess();
    }

    /*

    @RequestMapping(value = "/wx/create_menu", method = RequestMethod.GET)
    public boolean createMenu() throws IOException, URISyntaxException {

        Menu menu = new Menu();

        //推介客户
        val btn1 = menu.addButton("推介客户");
        btn1.setType(Menu.VIEW);
        btn1.setUrl(
                weChatService.createGetOpenIdUrl(properties.getDomain() + "/cust/market.htm", "")
        );

        //佣金
        val btn2 = menu.addButton("佣金");
        val btn21 = btn2.addSubButton("我的佣金");
        btn21.setType(Menu.VIEW);
        btn21.setUrl(
                weChatService.createGetOpenIdUrl(properties.getDomain() + "/cust/commission.htm", "")
        );

        val btn22 = btn2.addSubButton("历史订单");
        btn22.setType(Menu.VIEW);
        btn22.setUrl(
                weChatService.createGetOpenIdUrl(properties.getDomain() + "/cust/history.htm", "")
        );

        //我的
        val btn3 = menu.addButton("我的");
        val btn31 = btn3.addSubButton("我的账号");
        btn31.setType(Menu.VIEW);
        btn31.setUrl(
                weChatService.createGetOpenIdUrl(properties.getDomain() + "/cust/account.htm", "")
        );

        val btn32 = btn3.addSubButton("二级分销");
        btn32.setType(Menu.VIEW);
        btn32.setUrl(
                weChatService.createGetOpenIdUrl(properties.getDomain() + "/cust/sub.htm", "")
        );

        val btn33 = btn3.addSubButton("我的二维码");
        btn33.setType(Menu.VIEW);
        btn33.setUrl(
                weChatService.createGetOpenIdUrl(properties.getDomain() + "/cust/qr.htm", "")
        );

        weChatService.createMenu(menu);
        return true;
    }
    */
}
