package com.fjs.scenic.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fjs.scenic.entity.user.User;
import com.fjs.scenic.service.user.StatisticalPermissionsService;
import com.fjs.scenic.service.user.UserService;
import com.fjs.scenic.utils.ReturnResult;
import com.fjs.scenic.utils.WXPayUtil;

import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.api.WxConsts.MenuButtonType;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
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.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Controller
@RequestMapping("/api/wx")
public class WeChatController {

    private static Logger log = LoggerFactory.getLogger(WeChatController.class);
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserService userService;
    @Autowired
    private StatisticalPermissionsService statisticalPermissionsService;

    /**
     * 微信验证服务器信息-接入微信验证
     *
     * @throws WxErrorException
     */
    @ApiOperation(value = "", hidden = true)
    @GetMapping(value = "/check")
    public void check(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        boolean checkSignature = wxMpService.checkSignature(timestamp, nonce, signature);
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (checkSignature) {
            log.info("服务器验证签名成功");
            response.getWriter().write(echostr);
        }
        response.getWriter().write("fail");
    }

    @ApiOperation(value = "入口", hidden = false)
    @GetMapping("/login")
    public void login(String param, HttpServletResponse response) throws Exception {
        //String url = "http://wx.fjsfjq.com/api/wx/oauth";
    	//String url = "http://t.cqhsrj.com/api/wx/oauth";
    	String url = "https://wx.fjsstlyq.com/api/wx/oauth";
        //String url = "http://jq.fjsfjq.com/api/wx/oauth";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                StringUtils.isBlank(param) ? null : URLEncoder.encode(param, "UTF-8"));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        response.sendRedirect(redirectURL);
    }

    @ApiOperation(value = "微信授权", hidden = true)
    @GetMapping("/oauth")
    public void oauth(@RequestParam("code") String code, @RequestParam("state") String data,
                      HttpServletRequest request, HttpServletResponse response) throws Exception {
        //String url = "http://wx.fjsfjq.com:8088/#";
    	String url = "https://wx.fjsstlyq.com/dist/#";
    	//String url = "http://t.cqhsrj.com:8087/#";
    	//String url = "http://jq.fjsfjq.com:8088/#";
    	log.info("【微信网页授权】code={}，state={},url={}", code, data, url);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            if (wxMpUser == null) {
                log.error("获取用户信息失败");
                response.sendRedirect(url);
            }
            User user = new User();
            user.setCreateTime(new Date());
            user.setHeadPic(wxMpUser.getHeadImgUrl());
            user.setNickName(wxMpUser.getNickname());
            user.setOpenid(wxMpUser.getOpenId());
            user.setSex(wxMpUser.getSex() + "");
            ReturnResult result = userService.optionUser(user);
            if (result.getStatus() != 200) {
                log.error("获取用户信息失败");
                response.sendRedirect(url);
            }
            log.info("用户token={}", result.getData());
            if (StringUtils.isNotBlank(data)) {
                url = url + data;
            } else {
                url = url + "/index";
            }

            // 操作用户，如果该用户存在就跟新，不存在就修改（附加功能设置推荐人，分销用户记录）
            //将token写入cook
            setCookie(response, (String) result.getData());
            log.info("【微信网页授权】openId={}", "");
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
        }
        response.sendRedirect(url);
    }

    @ApiOperation(value = "微信被动消息回复", hidden = true)
    @RequestMapping(value = "check", method = RequestMethod.POST, produces = {"application/xml; charset=UTF-8"})
    public void toMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("微信返回了--------Weichart_Return");
//		Integer userId =(Integer) redisTemplate.opsForValue().get(request.getHeader(Cons.TOKEN.WECHAT));
//        Integer userId = 64;
        //String resXml = "";
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String reqXmlStr;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((reqXmlStr = in.readLine()) != null) {
            sb.append(reqXmlStr);
        }
        in.close();
        inputStream.close();
        log.info(sb.toString());
        try {
            Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
            String toUserName = map.get("ToUserName").toString();//开发者微信号
            String fromUserName = map.get("FromUserName").toString();//发送方帐号（一个OpenID）
            String createTime = map.get("CreateTime").toString();//消息创建时间 （整型）
            String msgType = map.get("MsgType").toString();//消息类型
            String content = map.get("Content");//消息内容
           // String msgId = map.get("MsgId").toString();//消息id，64位整型
            if (msgType.equals("text") && content.equals("查询")&&statisticalPermissionsService.getByOpenID(fromUserName).size()>0) {
                LinkedHashMap<String, String> replyMap = new LinkedHashMap<>();
                replyMap.put("ToUserName", "<![CDATA[" + fromUserName + "]]>");
                replyMap.put("FromUserName", "<![CDATA[" + toUserName + "]]>");
                replyMap.put("CreateTime", createTime);
                replyMap.put("MsgType", "<![CDATA[text]]>");
                replyMap.put("Content", "<![CDATA[<a href='https://wx.fjsstlyq.com/dist/#/echartIndex'>查询</a>]]>");
                String replyMapStr = WXPayUtil.mapToXml(replyMap).replaceAll("&lt;", "<").replaceAll("&gt;", ">");
                log.info(replyMapStr);
                response.setCharacterEncoding("UTF-8");
                response.getWriter().print(replyMapStr);
            }else if(msgType.equals("text") && content.contains("发票")){
            	LinkedHashMap<String, String> replyMap = new LinkedHashMap<>();
                replyMap.put("ToUserName", "<![CDATA[" + fromUserName + "]]>");
                replyMap.put("FromUserName", "<![CDATA[" + toUserName + "]]>");
                replyMap.put("CreateTime", createTime);
                replyMap.put("MsgType", "<![CDATA[text]]>");
                StringBuilder rssb = new StringBuilder();
                rssb.append("【订单信息】").append("\n")
                .append("姓名：XXXXXXXX").append("\n")
                .append("身份证号码：XXXXXXXXXXXXXXX（仅用于查询订单及使用情况）").append("\n")
                .append("手机号码：XXX  XXXX  XXXX（必须与订单联系人手机号一致）").append("\n")
                .append("接收电子发票的邮箱：XXXXXXXXXXXXXXX").append("\n")
                .append("申请开票金额：XXX.XX(不超过订单总金额)").append("\n")
                .append("【增值税普通发票信息】").append("\n")
                .append("【个人】").append("\n")
                .append("发票抬头姓名：XXXXXXXX").append("\n")
                .append("【公司】").append("\n")
                .append("发票对应公司名称：XXXXXXXXXXXXXXXX ").append("\n")
                .append("发票对应公司纳税识别号：XXXXXXXXXXXXXX").append("\n")
                .append("----------------------------").append("\n")
                .append("请按照上述模板将信息发送至邮箱（2046291416@qq.com）").append("\n");
                replyMap.put("Content", rssb.toString());
                String replyMapStr = WXPayUtil.mapToXml(replyMap).replaceAll("&lt;", "<").replaceAll("&gt;", ">");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().print(replyMapStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 写入客服端cookie
     *
     * @param response
     */
    private void setCookie(HttpServletResponse response, String token) {
        // 生成cookie
        Cookie cookie = new Cookie("USER_TOKEN", token);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 2);
        response.addCookie(cookie);
    }

    

    @ApiOperation(value = "获取菜单", hidden = false)
    @GetMapping("/menuCreate")
    @ResponseBody
    public String menuCreate() throws Exception {
        WxMenu menu = new WxMenu();
        WxMenuButton button1 = new WxMenuButton();
        button1.setType(MenuButtonType.VIEW);
        button1.setName("快速购票");
        button1.setUrl("https://wx.fjsstlyq.com/api/wx/login");
        
        WxMenuButton button2 = new WxMenuButton();
        button2.setType(MenuButtonType.VIEW);
        button2.setName("购票指南");
        button2.setUrl("https://mp.weixin.qq.com/s/q7BQdX8zj0q8JYUu2QEjpw");
        
        WxMenuButton button3 = new WxMenuButton();
        button3.setType(MenuButtonType.VIEW);
        button3.setName("景区天气");
        button3.setUrl("http://tq.fjsstlyq.com:8100/gzww/index.html#/");
        
        menu.getButtons().add(button1);
        menu.getButtons().add(button2);
        menu.getButtons().add(button3);

        String menuCreate = wxMpService.getMenuService().menuCreate(menu);
        return menuCreate;
    }
    
   /* @ApiOperation(value = "获取菜单", hidden = true)
    @GetMapping("/menuError")
    @ResponseBody
    public String menuError() throws Exception {
        WxMenu menu = new WxMenu();
        WxMenuButton button1 = new WxMenuButton();
        button1.setType(MenuButtonType.VIEW);
        button1.setName("快速购票");
        button1.setUrl("http://wx.fjsfjq.com:8088/error_page.html");
        
        WxMenuButton button2 = new WxMenuButton();
        button2.setType(MenuButtonType.VIEW);
        button2.setName("购票指南");
        button2.setUrl("https://mp.weixin.qq.com/s/q7BQdX8zj0q8JYUu2QEjpw");
        
        menu.getButtons().add(button1);
        menu.getButtons().add(button2);

        String menuCreate = wxMpService.getMenuService().menuCreate(menu);
        return menuCreate;
    }
    */
   /* @ApiOperation(value = "获取菜单", hidden = true)
    @GetMapping("/menuCreate1")
    @ResponseBody
    public String menuCreate1() throws Exception {
        WxMenu menu = new WxMenu();
        WxMenuButton button1 = new WxMenuButton();
        button1.setType(MenuButtonType.VIEW);
        button1.setName("快速购票");
        button1.setUrl("http://wx.fjsfjq.com/api/wx/login1");
        
        WxMenuButton button2 = new WxMenuButton();
        button2.setType(MenuButtonType.VIEW);
        button2.setName("购票指南");
        button2.setUrl("https://mp.weixin.qq.com/s/q7BQdX8zj0q8JYUu2QEjpw");
        
        menu.getButtons().add(button1);
        menu.getButtons().add(button2);

        String menuCreate = wxMpService.getMenuService().menuCreate(menu);
        return menuCreate;
    }*/

    /*@ApiOperation(value = "获取菜单", hidden = true)
    @GetMapping("/getMenu")
    @ResponseBody
    public Object getMenu() throws Exception {
        Map<String, Object> data = new HashMap<>();
        WxMpMenu wxMenu = wxMpService.getMenuService().menuGet();
        WxMenu menu = new WxMenu();
        //List<WxButtonVo> menuvo = myOrdersService.getMenu();
        List<WxMenuButton> menuvo = new ArrayList<>();
        menuvo.forEach(m->{
			WxMenuButton button = new WxMenuButton();
			button.setType(m.getType());
			button.setName(m.getName());
			button.setUrl(m.getUrl());
			button.setKey(m.getKey());
			if(m.getList()!=null) {
				m.getList().forEach(m1->{
					WxMenuButton button2 = new WxMenuButton();
					button2.setType(m1.getType());
					button2.setName(m1.getName());
					button2.setKey(m1.getKey());
					button2.setUrl(m1.getUrl());
					button.getSubButtons().add(button2);
				});
			}
			menu.getButtons().add(button);
		});
        data.put("wxMenu", wxMenu);
        data.put("menu", menu);
        wxMpService.getMenuService().menuCreate(menu);
        return data;
    }*/
    
    


    /**
     * 微信JSAPI权限验证的参数
     *
     * @throws Exception
     */
    @ApiOperation(value = "微信JSAPI权限验证的参数", notes = "微信JSAPI权限验证的参数", hidden = false)
    @GetMapping(value = "/js")
    @ResponseBody
    public Map<String, Object> js(HttpServletRequest request, String url) throws Exception {
        WxJsapiSignature jsapiTicket = wxMpService.createJsapiSignature(url);
        String jsapiTicket2 = wxMpService.getJsapiTicket();
        Map<String, Object> data = new HashMap<>();
        data.put("appId", jsapiTicket.getAppId());
        data.put("timestamp", jsapiTicket.getTimestamp());
        data.put("nonceStr", jsapiTicket.getNonceStr());
        data.put("signature", jsapiTicket.getSignature());
        data.put("jsapiTicket", jsapiTicket2);
        return data;
    }
    
/*    @GetMapping("/222")
    @ResponseBody
    public String qqqq(){
    	 StringBuilder rssb = new StringBuilder();
         rssb.append("【订单信息】").append("/n")
         .append("姓名：XXXXXXXX").append("/n")
         .append("身份证号码：XXXXXXXXXXXXXXX（仅用于查询订单及使用情况）").append("/n")
         .append("手机号码：XXX  XXXX  XXXX").append("/n")
         .append("接收电子发票的邮箱：XXXXXXXXXXXXXXX   ").append("/n")
         .append("【增值税普通发票信息】").append("/n")
         .append("【个人】").append("/n")
         .append("发票抬头姓名：XXXXXXXX").append("/n")
         .append("【公司】").append("/n")
         .append("发票对应公司名称：XXXXXXXXXXXXXXXX ").append("/n")
         .append("发票对应公司纳税识别号：XXXXXXXXXXXXXX").append("/n")
         .append("-----------------------------------------").append("/n")
         .append("请按照上述模板将信息发送至邮箱（2046291416@qq.com）").append("/n")
         .append("或者通过短信发送到手机号：17785689143").append("/n");
         System.out.println(rssb.toString());
         log.info("rssb="+rssb.toString());
         return rssb.toString();
    }*/
    
}
