package com.jeeplus.modules.wexinpackage.access.web;


import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.entity.Company;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.wexinpackage.access.service.WeChatCallbackService;
import com.jeeplus.modules.wexinpackage.access.util.access.WeChatParamsUtil;
import com.jeeplus.modules.wexinpackage.access.util.encryption.WXBizMsgCrypt;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.PrintWriter;

@Controller
@RequestMapping(value = "${adminPath}/weChatCallBack/weChatController")
public class WeChatCallbackController extends BaseController {
    @Autowired
    private WeChatCallbackService weChatCallbackService;

    @RequestMapping(value = "callBack")
    public void getCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String method = request.getMethod();
        if ("GET".equals(method)){
            doGet(request,response);
        }else {
            doPost(request,response);
        }
    }
    private void doGet(HttpServletRequest request, HttpServletResponse response){
        // 微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echoStr = request.getParameter("echostr");
        //回调key值
        String sEchoStr = null;
        WXBizMsgCrypt wxcpt;
            try {
            PrintWriter writer = response.getWriter();
            wxcpt = new WXBizMsgCrypt(WeChatParamsUtil.contacts_token,WeChatParamsUtil.encodingAESKey,WeChatParamsUtil.corpId);
            sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echoStr);
            if (StringUtils.isBlank(sEchoStr)){
                logger.error("url验证失败");
            }
            writer.write(sEchoStr);
            writer.close();
        }catch (Exception e){
            logger.error("企业微信回调验证错误",e);
        }
    }
    private  void  doPost(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String sReqMsgSig = request.getParameter("msg_signature");
        String sReqTimeStamp = request.getParameter("timestamp");
        String sReqNonce = request.getParameter("nonce");
//        try {
            BufferedReader reader = request.getReader();
            char[] buf = new char[512];
            int len = 0;
            StringBuffer stringBuffer = new StringBuffer();
            while ((len = (int) reader.read(buf))!= -1){
                stringBuffer =  stringBuffer.append(buf, 0, len);
            }
            String content = stringBuffer.toString();
            if (content == null){
                content = "";
            }
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WeChatParamsUtil.contacts_token,WeChatParamsUtil.encodingAESKey,WeChatParamsUtil.corpId);
            String sMsg = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, content);
            weChatCallbackService.getMapOperation(sMsg,request);
            // 循环所有子元素
//        } catch (Exception e) {
//            // TODO
//            // 解密失败，失败原因请查看异常
//            e.printStackTrace();
//        }
    }

//    public void getSaveUser(List children,HttpServletRequest request){
//        String userId= "";
//        String ChangeType = "";
//        if (children != null && children.size() > 0) {
//            for (int i = 0; i < children.size(); i++) {
//                Element child = (Element) children.get(i);
//                //xml转Map
//                System.out.println(child.getName()+"======"+child.getTextTrim());
//                if (child.getName().equals("ChangeType")){
//                    ChangeType = child.getTextTrim();
//                }
//                if (child.getName().equals("UserID")){
//                    userId = child.getTextTrim();
//                    break;
//                }
//            }
//        }
//        if (ChangeType.contains("update")){
//            WeChatUser weChatUser1 = new WeChatUser();
//            String s = UserUrl.getUser("", userId);
//            JSONObject jsonObject = JSONObject.parseObject(s);
//            Map<String,Object> map = JSONObject.toJavaObject(jsonObject,Map.class);
//            weChatUser1.setUserid((String) map.get("userid"));
//            weChatUser1.setName((String) map.get("name"));
//            weChatUser1.setGender((String)map.get("gender"));//性别
//            weChatUser1.setTelephone((String)map.get("telephone"));//座机
//            weChatUser1.setMobile((String) map.get("mobile"));
//            weChatUser1.setMobile((String)map.get("alias"));//别名
//            weChatUser1.setEmail((String) map.get("email"));
//            weChatUser1.setAddress((String)map.get("address"));//地址
////            WorkStaffBasicInfo  workStaffBasicInfo = new WorkStaffBasicInfo();
//            WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
//            User user = new User();
//            Office office = new Office();
//            office.setName("财务部");
//            office.setId("379981dac65a4b26a59f2f6d373da091");
//            user.setOffice(office);
//            workStaffBasicInfo.setOffice(office);
//            Office office1 = new Office();
//            office1.setName("兴光项目");
//            office1.setId("ffe5af5b557e46f28b000c94716e228a");
//            user.setCompany(office1);
//            workStaffBasicInfo.setCompany(office1);
//            user.setComId("ffe5af5b557e46f28b000c94716e228a");
//            user.setLoginName(weChatUser1.getUserid());//登录名
//            workStaffBasicInfo.setNo(weChatUser1.getUserid());
//            user.setName(weChatUser1.getName());
//            workStaffBasicInfo.setName(weChatUser1.getName());
//            workStaffBasicInfo.setNo(weChatUser1.getUserid());
////            workStaffBasicInfo.setNo(weChatUser.getMobile());
//            workStaffBasicInfo.setGender(weChatUser1.getGender());
//            workStaffBasicInfo.setNation("01");
//            workStaffBasicInfo.setAge(24);
//            workStaffBasicInfo.setStatus("正式");
//            workStaffBasicInfo.setBranchOffice(office1);
//            user.setEmail(weChatUser1.getEmail());
//            workStaffBasicInfo.setEmail(weChatUser1.getEmail());
//            user.setMobile(weChatUser1.getMobile());
//            workStaffBasicInfo.setMobile(weChatUser1.getMobile());
//            workStaffBasicInfo.setPhone(weChatUser1.getMobile());
//            user.setLoginFlag("1");
//            workStaffBasicInfo.setDelFlag("0");
//            workStaffBasicInfo.setRoleId("df7e52bdc2934e18b4739e6c98b93385");
//            user.setNewPassword("123456");
//            user.setDelFlag("0");
////            workStaffBasicInfo.setName(weChatUser1.getName());
////            workStaffBasicInfo.setGender(weChatUser1.getGender());
////            workStaffBasicInfo.setEmail(weChatUser1.getEmail());
////            workStaffBasicInfo.setPhone(weChatUser1.getMobile());
////            workStaffBasicInfo.setMobile(weChatUser1.getMobile());
//            WorkStaffBasicInfo no = workStaffBasicInfoService.findNo(userId);
//            WorkStaffBasicInfo t = workStaffBasicInfoService.get(no.getId());//从数据库取出记录的值
//            try {
//                MyBeanUtils.copyBeanNotNull2Bean(workStaffBasicInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
////                workStaffBasicInfoService.save(t,request);//保存
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        if (ChangeType.equals("delete_user")){
//            WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.findNo(userId);
//            if (null!=workStaffBasicInfo){
//                workStaffBasicInfoService.delete(workStaffBasicInfo);
//            }
//        }
//        if (ChangeType.contains("create")){
//            if (!"".equals(userId)){
//                WeChatUser weChatUser = new WeChatUser();
//                String s = UserUrl.getUser("", userId);
//                JSONObject jsonObject = JSONObject.parseObject(s);
//                Map<String,Object> map = JSONObject.toJavaObject(jsonObject,Map.class);
//                weChatUser.setUserid((String) map.get("userid"));
//                weChatUser.setName((String) map.get("name"));
//                weChatUser.setGender((String)map.get("gender"));//性别
//                weChatUser.setTelephone((String)map.get("telephone"));//座机
//                weChatUser.setMobile((String) map.get("mobile"));
//                weChatUser.setMobile((String)map.get("alias"));//别名
//                weChatUser.setEmail((String) map.get("email"));
//                weChatUser.setAddress((String)map.get("address"));//地址
//                System.out.println(s);
//                WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
//                User user = new User();
//                Office office = new Office();
//                office.setName("财务部");
//                office.setId("379981dac65a4b26a59f2f6d373da091");
//                user.setOffice(office);
//                workStaffBasicInfo.setOffice(office);
//                Office office1 = new Office();
//                office1.setName("兴光项目");
//                office1.setId("ffe5af5b557e46f28b000c94716e228a");
//                user.setCompany(office1);
//                workStaffBasicInfo.setCompany(office1);
//                user.setComId("ffe5af5b557e46f28b000c94716e228a");
//                user.setLoginName(weChatUser.getUserid());//登录名
//                workStaffBasicInfo.setNo(weChatUser.getUserid());
//                user.setName(weChatUser.getName());
//                workStaffBasicInfo.setName(weChatUser.getName());
//                workStaffBasicInfo.setNo(weChatUser.getUserid());
////            workStaffBasicInfo.setNo(weChatUser.getMobile());
//                workStaffBasicInfo.setGender(weChatUser.getGender());
//                workStaffBasicInfo.setNation("01");
//                workStaffBasicInfo.setAge(24);
//                workStaffBasicInfo.setStatus("正式");
//                workStaffBasicInfo.setBranchOffice(office1);
//                user.setEmail(weChatUser.getEmail());
//                workStaffBasicInfo.setEmail(weChatUser.getEmail());
//                user.setMobile(weChatUser.getMobile());
//                workStaffBasicInfo.setMobile(weChatUser.getMobile());
//                workStaffBasicInfo.setPhone(weChatUser.getMobile());
//                user.setLoginFlag("1");
//                workStaffBasicInfo.setDelFlag("0");
//                workStaffBasicInfo.setRoleId("df7e52bdc2934e18b4739e6c98b93385");
//                user.setNewPassword("123456");
//                user.setDelFlag("0");
//                String redisUser = JedisUtils.get("WXUSERID");
//                if (null != redisUser){
//                    if (!redisUser.equals(weChatUser.getUserid())){
//                        try {
//                            JedisUtils.set("WXUSERID",weChatUser.getUserid(),0);
//                            boolean b = userService.save(user,request,null);
//                            if (b){
//                                workStaffBasicInfoService.save(workStaffBasicInfo,request);//保存
//                            }
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                    }
//                }else {
//                    try {
//                        JedisUtils.set("WXUSERID",weChatUser.getUserid(),0);
//                        boolean b = userService.save(user,request,null);
//                        if (b){
//                            workStaffBasicInfoService.save(workStaffBasicInfo,request);//保存
//                        }
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//
//    }
}