package com.fs.app.controller;

import com.alibaba.fastjson.JSON;
import com.fs.app.service.QwDataCallbackService;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.DateUtils;
import com.fs.company.service.ICompanyConfigService;
import com.fs.qw.domain.*;
import com.fs.qw.mapper.QwCompanyMapper;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.param.QwAutoRulesTagsParams;
import com.fs.qw.service.*;
import com.fs.qwApi.Result.QwGroupChatDetailsResult;
import com.fs.qwApi.Result.QwOpenidResult;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.param.QwEditUserTagParam;
import com.fs.qwApi.param.QwOpenidByUserParams;
import com.fs.qwApi.service.QwApiService;
import com.fs.qwApi.util.AesException;
import com.fs.qwApi.util.WXBizMsgCrypt;
import com.fs.qwApi.util.XMLParse;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class QwController {
    org.slf4j.Logger logger= LoggerFactory.getLogger(getClass());





    @Autowired
    private QwCompanyMapper qwCompanyMapper;

    @Autowired
    private QwDataCallbackService qwDataCallbackService;
    @GetMapping("/qw/test/{corpId}")
    public String test(@PathVariable String corpId )throws Exception {
        System.out.println("11111111111111");
       // 尝试读取一个不存在的文件
       // FileInputStream fileInputStream = new FileInputStream("non_existent_file.txt");
        return "ok";
    }
    /**
     * 功能描述:
     * 应用详情 --> 回调配置中 --> 数据回调URL
     */
    @GetMapping("/qw/data/{corpId}")
    public String data(@PathVariable String corpId,
                       @RequestParam("msg_signature") String msg_signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("echostr") String echostr) {
//        logger.info("数据回调URL-微信调用dataGet请求");
        return getVerify(msg_signature, timestamp, nonce, echostr,corpId);
    }

    @PostMapping("/qw/data/{corpId}")
    public String data(@PathVariable String corpId,
                        @RequestBody String requestBody,
                        @RequestParam("msg_signature") String msg_signature,
                        @RequestParam("timestamp") String timestamp,
                        @RequestParam(value = "corpid", required = false) String corpid,
                        @RequestParam("nonce") String nonce) {
        return dataCallback(msg_signature,timestamp,nonce,requestBody,corpId);
    }

    public String getVerify(String sVerifyMsgSig,String sVerifyTimeStamp,
                            String sVerifyNonce,String sVerifyEchoStr,String corpId){
       QwCompany qwCompany= qwCompanyMapper.selectQwCompanyByCorpId(corpId);
        String token = qwCompany.getToken();
        String encodingAESKey = qwCompany.getEncodingAesKey();

        WXBizMsgCrypt wxcpt = null;
        try {
            wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);
        }catch (AesException E){
            return "error";
        }
        String sEchoStr; //需要返回的明文
        try {
            sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,
                    sVerifyNonce, sVerifyEchoStr);
//            logger.info("企业微信验证事件："+corpId);
        } catch (Exception e) {
            logger.info("企业微信验证失败："+corpId);
            //验证URL失败，错误原因请查看异常
            return "error";
        }
        return  sEchoStr;
    }




    public String dataCallback(String sVerifyMsgSig,String sVerifyTimeStamp,String sVerifyNonce,String sData,String corpId){
        QwCompany qwCompany= qwCompanyMapper.selectQwCompanyByCorpId(corpId);
        String token = qwCompany.getToken();
        String encodingAESKey = qwCompany.getEncodingAesKey();
//        logger.info("企业微信回调事件companyId："+corpId);
        String result = "error";
        WXBizMsgCrypt wxcpt = null;
        try {
            Object[] encrypt = XMLParse.extract(sData);
            String sSuiteid = (String) encrypt[2];
            wxcpt = new WXBizMsgCrypt(token, encodingAESKey, sSuiteid);
        }catch (AesException E){
            return result;
        }
        try{
            String sMsg = wxcpt.DecryptMsg(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sData);
            logger.info("企业微信回调事件："+sMsg);
            // 加密成功
            // TODO: 解析出明文xml标签的内容进行处理
            // For example:
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(sMsg);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);
            qwDataCallbackService.dataCallback(document,corpId,qwCompany);

        }
        catch(Exception e)
        {
            e.printStackTrace();
            // 加密失败
            logger.error("加密失败:"+result);
            return result;
        }
        result = "success";
        return  result;
    }
}
