package com.kiisoo.ic.wx.controller;


import com.kiisoo.ic.common.BaseController;
import com.kiisoo.ic.common.utils.SignUtils;
import com.kiisoo.ic.common.utils.WeixinApi;
import com.kiisoo.ic.employee.entity.QrCodeDO;
import com.kiisoo.ic.employee.entity.QrCodeVO;
//import com.kiisoo.ic.employee.service.QrCodeService;
import com.kiisoo.ic.employee.service.QrCodeService;
import com.kiisoo.ic.wx.entity.ContactWayDTO;
import com.kiisoo.ic.wx.service.WxAccessService;
import com.kiisoo.ic.wx.service.WxLoginService;
import com.kiisoo.ic.wx.service.WxResponseService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业微信认证登录
 *
 * @author yechenhao
 * @date 2020/03/11 15:32
 */
@Slf4j
@Controller
@RequestMapping("/qy")
public class WxAccessController extends BaseController {

    @Autowired
    private WxAccessService wxAccessService;

    @Autowired
    private WxLoginService loginService;



    @Autowired
    private WxResponseService wxResponseService;

    @Autowired
    private QrCodeService qrCodeService;

    private String loginPageUrl = "http://localhost:8311/kiisoo-ic-ui";
    private String baseUrl = "http://jdxdev.vipgz4.idcfengye.com/ic";

    /**
     * 获取微信权限验证
     *
     * @param url 页面路径
     * @return 微信认证的url和ticket
     * @author dexiang.jiang
     * @date 2020/03/11 15:44
     */
    @RequestMapping(value = "/wechat/oauth", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getWxSign(@RequestParam("url") String url) {
        try {
            WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
            String ticket = config.getJsapiTicket();
            Map<String, Object> map = SignUtils.sign(ticket, url);
            return data(map);
        } catch (Exception e) {
            log.error("by get wxSign qy weixin oauth error ", e);
            return fail();
        }

    }

    /**
     * 通过微信接口获取codeID并跳转接口
     *
     * @param response 响应
     */
    @RequestMapping(value = "/wechat/register", method = RequestMethod.GET)
    @ResponseBody
    public void registerSmall(HttpServletResponse response) {
        try {
            WxCpService wxCpService = new WxCpServiceImpl();
            String url = wxCpService.getOauth2Service().buildAuthorizationUrl(baseUrl + "/qy/qywx/oauth", "111999");
            response.sendRedirect(url);
        } catch (Exception e) {
            log.error("Exception", e);
        }
    }

    /**
     * 通过codeID从微信接口获取openID，手机绑定
     */
    @RequestMapping(value = "/qywx/oauth", method = RequestMethod.GET)
    @ResponseBody
    public void wechat(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        // 先获取OPENID
        try {
            WxCpService wxCpService = new WxCpServiceImpl();
            //TODO 企业微信认证登录url（订单详情项目）
            WxCpOauth2UserInfo res =  wxCpService.getOauth2Service().getUserInfo(code);
            String userId = res.getUserId();
            //根据企业微信id找到相关账号密码
            Map<String, String> loginInfo = loginService.getLoginInfoByQywxUserId(userId);
            String redirectUri;
            if (loginInfo == null || StringUtils.isBlank(loginInfo.get("login")) || StringUtils.isBlank(loginInfo.get("password"))) {
                redirectUri = loginPageUrl + "/login?relition=false&qywxUserId=" + userId;
            } else {
                String login = loginInfo.get("login");
                String password = loginInfo.get("password");
                redirectUri = loginPageUrl + "/login?relition=true&login=" + login + "&password=" + password + "&qywxUserId=" + userId;
            }
            response.sendRedirect(redirectUri);
        } catch (Exception e) {
            log.error("微信验证失败", e);
        }
    }

    /**
     * 登录账号
     *
     * @param login    用户名
     * @param password 密码
     * @return 成功/失败
     */
    @RequestMapping(value = "/account", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> loginAccount(@RequestParam("login") String login, @RequestParam("password") String password,
                                            @RequestParam(value = "isMD5", required = false, defaultValue = "false") Boolean isMD5) {
        try {
            Map<String, Object> resultMap = new HashMap<>();
//            LoginBean loginBean = loginService.login(login, password, isMD5);
//            resultMap.put("code", loginBean.getLoginInfo().get("code"));
//            resultMap.put("results", loginBean);
//            resultMap.put("success", Boolean.TRUE);
            return resultMap;
        } catch (Exception e) {
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 登录账号
     *
     * @param login      用户名
     * @param password   密码
     * @param qywxUserId 企业微信账号
     * @return 成功/失败
     */
    @RequestMapping(value = "/account/bind", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> loginAccountBind(@RequestParam("login") String login, @RequestParam("password") String password,
                                                @RequestParam("qywxUserId") String qywxUserId) {
        try {
            Map<String, Object> resultMap = new HashMap<>();
//            LoginBean loginBean = loginService.login(login, password, false);
//            resultMap.put("code", loginBean.getLoginInfo().get("code"));
//            if (LoginEnum.LOGIN_SUCCEED.getCode().equals(loginBean.getLoginInfo().get("code"))) {
//                loginService.bindQywxUserIdByUserId(loginBean.getUserId(), qywxUserId);
//            }
//            resultMap.put("results", loginBean);
//            resultMap.put("success", Boolean.TRUE);
            return resultMap;
        } catch (Exception e) {
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 解析企业微信返回的数据
     *
     * @param request   回调的请求
     * @param signature 消息体签名
     * @param timestamp 时间戳
     * @param nonce     随机数字串
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/contact/handle", produces = {"application/xml;charset=UTF-8"})
    @ResponseBody
    public Object handlerMessage(HttpServletRequest request, @RequestParam(name = "msg_signature") String signature,
                                 String timestamp, String nonce) throws Exception {
        try {
            //将数据输入转为String
            request.setCharacterEncoding("UTF-8");
            StringBuilder builder = new StringBuilder();
            ServletInputStream input = request.getInputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while (-1 != (len = input.read(buffer))) {
                builder.append(new String(buffer, 0, len, "UTF-8"));
            }
            //解析并获取返回
            String response = wxResponseService.contactHandleParse(signature, timestamp, nonce, builder.toString());
            return response;
        } catch (Exception e) {
            log.error("企业微信微信回调数据解析失败", e);
            return null;
        }
    }

    /**
     * 企业微信外部联系人变更回调事件
     *
     * @param request   回调的请求
     * @param signature 消息体签名
     * @param timestamp 时间戳
     * @param nonce     随机数字串
     * @return 返回响应
     * @author dexiang.jiang
     * @date 2020/03/11 15:44
     */
    @RequestMapping(value = "/customer/handle", produces = {"application/xml;charset=UTF-8"})
    @ResponseBody
    public String customerHandle(HttpServletRequest request, @RequestParam(name = "msg_signature") String signature,
                                 String timestamp, String nonce) {

        try {
            //将数据输入转为String
            request.setCharacterEncoding("UTF-8");
            StringBuilder builder = new StringBuilder();
            ServletInputStream input = request.getInputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while (-1 != (len = input.read(buffer))) {
                builder.append(new String(buffer, 0, len, "UTF-8"));
            }
            //解析并获取返回
            String sEchoStr = wxResponseService.customerParse(signature, timestamp, nonce, builder.toString());
            // 验证URL成功，将sEchoStr返回
            System.out.println(sEchoStr);
            return sEchoStr;
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 获取微信权限验证(认证服务器时放开此controller)
     *
     * @param sVerifyMsgSig msg_signature参数
     * @param sVerifyTimeStamp timestamp参数
     * @param sVerifyNonce nonce参数
     * @param sVerifyEchoStr echostr参数
     * @return 微信认证的url和ticket
     * @author dexiang.jiang
     * @date 2020/03/11 15:44
     */
//    @RequestMapping(value = "/customer/handle", method = RequestMethod.GET)
//    @ResponseBody
//    public String verify(@RequestParam("msg_signature") String sVerifyMsgSig,
//                                      @RequestParam("timestamp") String sVerifyTimeStamp,
//                                      @RequestParam("nonce") String sVerifyNonce,
//                                      @RequestParam("echostr") String sVerifyEchoStr) {
//
//        try {
//            String sEchoStr = wxResponseService.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,
//                    sVerifyNonce, sVerifyEchoStr);
//            // 验证URL成功，将sEchoStr返回
//            System.out.println(sEchoStr);
//            return sEchoStr;
//        } catch (Exception e) {
//            //验证URL失败，错误原因请查看异常
//            e.printStackTrace();
//        }
//        return null;
//    }



    /**
     * 企业微信-客户列表
     *
     * @param userid 企业内部客户ID
     * @return 列表集合
     * @author dexiang.jiang
     * @date 2020/03/19 15:44
     */
    @RequestMapping(value = "/externalcontact/list", method = RequestMethod.GET)
    @ResponseBody
    public String externalContact(@RequestParam("userid") String userid) {
        try {
            String res = WeixinApi.getExternalContact(userid);
            return res;
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 企业微信-客户列表
     *
     * @param configId 配置ID
     * @return 列表集合
     * @author dexiang.jiang
     * @date 2020/03/19 15:44
     */
    @RequestMapping(value = "/externalcontact/contactway", method = RequestMethod.GET)
    @ResponseBody
    public String contactway(@RequestParam("configId") String configId) {
        try {
            String res = WeixinApi.getContactWay(configId);
            return res;
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 企业微信-添加联系方式
     *
     * @return 列表集合
     * @author dexiang.jiang
     * @date 2020/03/19 15:44
     */
    @RequestMapping(value = "/externalcontact/add/contactway", method = RequestMethod.GET)
    @ResponseBody
    public QrCodeVO addContactway() {
        try {
            QrCodeDO contactWayDTO = new QrCodeDO();
            contactWayDTO.setType(1);
            contactWayDTO.setScene(2);
            contactWayDTO.setScene(2);
            String[] data = new String[1];
            data[0] = ("JiangDeXiang");
            contactWayDTO.setUser(data);
//            contactWayDTO.setState("D1");
            contactWayDTO.setState("D2");

           QrCodeVO res = qrCodeService.getQrCode(contactWayDTO);
            System.out.println(res);
            return null;
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析企业微信返回的数据
     * @param request 回调的请求
     * @param signature 消息体签名
     * @param timestamp 时间戳
     * @param nonce 随机数字串
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/res",produces = {"application/xml;charset=UTF-8"})
    @ResponseBody
    public Object handlerMessageTo(HttpServletRequest  request, @RequestParam(name = "msg_signature") String signature,
                                 String timestamp, String nonce) throws Exception {
        try {
            //将数据输入转为String
            request.setCharacterEncoding("UTF-8");
            StringBuilder builder = new StringBuilder();
            ServletInputStream input = request.getInputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while(-1!=(len=input.read(buffer)))
            {
                builder.append(new String(buffer,0,len,"UTF-8"));
            }
            //解析并获取返回
            String response = wxResponseService.parse(signature, timestamp, nonce, builder.toString());

            return response;
        }catch (Exception e){
            log.error("企业微信微信回调数据解析失败",e);
            return null;
        }
    }

}
