package com.chinacreator.video.restful.service;

import com.alibaba.fastjson.JSONArray;
import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.mapper.SmsCheckDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.*;
import com.google.gson.JsonObject;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Or;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 视频审核管理中台搭建服务类
 *
 * @author zhengrong.yan
 * @date 20210628
 */
@Component
public class SmsCheckService {

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private SignValidate signValidate;

    @Autowired
    private ParamValidate paramValidate;

    @Autowired
    private CommConfDao commConfDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SmsCheckDao smsCheckDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private ChannelDao channelDao;

    private static Logger logger = Logger.getLogger(SmsCheckService.class);

    private static Logger log = Logger.getLogger("smscheck");
    private static Logger log_img = Logger.getLogger("imgcheck");
    private static Logger log_audio = Logger.getLogger("audiocheck");
    private static Logger log_video = Logger.getLogger("videocheck");
    private static Logger log_callback = Logger.getLogger("callback");

    public void busiCheck(OrderInfo orderInfo, int type) throws Exception {
        System.out.println("invokeface====>" + orderInfo.getInvokeface());
        String invokeface = orderInfo.getInvokeface();
        if(!invokeface.equals("health")) {//除health接口，其他均需要进行时间戳验证
            //timetamp验证
            timetampValidate.validate(orderInfo.getTimestamp());
        }
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
//        //设置cpid
        if("audiocheck".equals(invokeface)){
            orderInfo.setCpid("audiocheck");
        }else if ("videocheck".equals(invokeface)){
            orderInfo.setCpid("videocheck");
        }else if("imgcheck".equals(invokeface)){
            orderInfo.setCpid("imgcheck");
        }else if("smscheck".equals(invokeface)){
            orderInfo.setCpid("smscheck");
        }else if("health".equals(invokeface)){
            orderInfo.setCpid("health");
        }
        ipValidate.volidate(orderInfo);
        //签名验证
        signValidate(orderInfo);
        if (type == 0 && orderInfo.getUserid()!=null && !"".equals(orderInfo.getUserid())) {
            //手机号码验证
            mobValidate(orderInfo);
        }
        //20220408 去掉并发控制，通创方需求
//        //并发访问控制
//        if(!invokeface.equals("health")) {//除health接口，其他均需要进行并发控制
//            //timetamp验证
//            vistVali(orderInfo);
//        }

    }


    /**
     * 手机号码验证
     *
     * @param
     * @throws Exception
     */
    private void mobValidate(OrderInfo orderInfo) throws Exception {
        String userid = orderInfo.getUserid();
        if (StringUtils.isEmpty(userid)) {
            throw new BussinessException("10007", "手机号不能为空");
        }
        ChannelBean channelBean = channelDao.queryChannel(orderInfo.getChannel());
        try {
            userid = DesUtil.decode(userid, channelBean.getPassword());//解密
            if (isValid(userid) && userid.length() == 11) {
                orderInfo.setUserid(userid);//重新设置手机号码为源码
            } else {
                throw new BussinessException("10009", "手机号错误");
            }
        } catch (Exception e) {
            if (e instanceof BussinessException) {
                throw e;
            } else {
                throw new BussinessException("10008", "手机号加密错误");
            }
        }
    }

    private boolean isValid(String usermob) {
        if (usermob == null) {
            return false;
        }
        usermob = usermob.replaceAll("[\\s-]", "");

        return usermob.matches(".*(1\\d{10}).*");
    }


    /**
     * 拼接签名信息 orderid+channel+timestamp
     *
     * @param
     * @return
     */
    public String getSign(OrderInfo orderInfo) throws Exception {
        StringBuilder strb = new StringBuilder();
        String userid = orderInfo.getUserid() == null ? "" : orderInfo.getUserid();
        if("smscheck".equals(orderInfo.getInvokeface())) {
            strb.append(userid);
        }
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }

    /**
     * 签名验证
     *
     * @param
     * @throws Exception
     */
    public void signValidate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        String channel = orderInfo.getChannel();
        lcalsign += channelDao.queryChannel(channel).getPassword();
        System.out.println("local-->" + lcalsign);
        lcalsign = MD5.MD5Encode(lcalsign);
        System.out.println("orderinfo==>" + orderInfo.getSignature());
        System.out.println("lcalsign===>" + lcalsign);
        if (!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }

    /**
     * 业务处理
     *
     * @param orderInfo
     */
    public JSONObject busiOper_sms(OrderInfo orderInfo) throws Exception {
        String resultcode = "0";
        String resultinfo = "";
        String jsonParams = "";
        String isviolate = "0";
        String requestid = "";
        String result = "";
        JSONObject resjson = null;
        HashMap map = new HashMap();
        try {
            String smsdata = orderInfo.getSmsdata() == null ? "" : orderInfo.getSmsdata();
            String url = dictionaryDao.getValue("tencentCheckUrl");
            String userid = orderInfo.getUserid();
            String channel = orderInfo.getChannel()==null?"":orderInfo.getChannel();

            HashMap paramMap = new HashMap();
            paramMap.put("channel",channel);
            paramMap.put("subchannel",orderInfo.getSubchannel());

            /*新增业务id配置 20210825*/
            int bussinesid = 1;
            if(!"".equals(channel)){
                /*新增业务id通过表查询*/
                log.info("-----业务id开始查询(优先查表）----");
                bussinesid = queryBussinessidByConfig(paramMap);
                if(bussinesid==1){
                    log.info("-----业务id开始通过接口查询----");
                    bussinesid = queryBussinesdid(paramMap,log);
                    if(bussinesid==1){
                        log.info("-----业务id开始新增----");
                        Boolean res = addBussinesid(paramMap,log);
                        if(res){
                            bussinesid = queryBussinesdid(paramMap,log);//再查一次获得新id
                        }
                        log.info("-----业务id结束新增----");
                    }
                }
                log.info("-----业务id结束查询----");
            }

            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("Action", "TextModeration");
            json.put("Content", smsdata == null ? "" : smsdata.getBytes());

            json.put("BusinessId", bussinesid);
            jsonParams = json.toJSONString();
            log.info(jsonParams);

            /*添加到表*/
            map.put("id", smsCheckDao.getNo());
            map.put("userid", userid);
            map.put("resdata", smsdata);
            map.put("request", jsonParams);
            map.put("channel", orderInfo.getChannel());
            map.put("invokeface", "smscheck");
            smsCheckDao.addRec(map);
            /**end**/

            /*调接口*/
            result = URLUtil.postJson(url, jsonParams);
            log.info(url);
            log.info(jsonParams);
            log.info(result);
            if (!"".equals(result) && result != null) {
                resjson = JSONObject.fromObject(result);
                JSONObject jsonObject = resjson.getJSONObject("Response");
                requestid = jsonObject.getString("RequestId");
                if (jsonObject.getJSONObject("Data") != null) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("Data");
                    String evilflag = jsonObject2.getString("EvilFlag");
                    isviolate = evilflag;
                    log.info("是否恶意===>evilflag==>" + evilflag);
                    resultinfo = jsonObject2.toString();
                } else if (jsonObject.getJSONObject("Error") != null) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("Data");
                    resultcode = jsonObject2.getString("Code");
                    resultinfo = jsonObject2.getString("Message");
                    throw new BussinessException(resultcode, resultinfo);
                } else {
                    throw new BussinessException("8001", "json解析错误，result不为空");
                }
            } else {
                throw new BussinessException("8000", "result为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                resultinfo = ((BussinessException) e).getMessage();
            } else {
                resultcode = "8000";
                resultinfo = "出现异常，" + e.toString();
            }
            throw e;
        } finally {
            //更新表
            map.put("requestid", requestid);
            map.put("isviolate", isviolate);
            map.put("resultinfo", resultinfo.length() > 4000 ? resultinfo.substring(0, 2000) : resultinfo);
            smsCheckDao.upRec(map);
            return resjson;
        }
    }


    /**
     * 验证访问限制，1分钟内同一业务只能办理一次
     *
     * @param orderInfo
     * @throws Exception
     */
    private void vistVali(OrderInfo orderInfo) throws Exception {
        String[] params = new String[3];
        params[0] = orderInfo.getChannel();
        params[1] = orderInfo.getUserid();
        if (commonService.vistVali2(params, orderInfo.getInvokeface())) {
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }

    /*
     * 设置到bean里
     *
     * */
    public OrderInfo setBean(com.alibaba.fastjson.JSONObject inputObj, int type) {
        OrderInfo orderInfo = new OrderInfo();
        if (type == 0) {
            orderInfo.setUserid(inputObj.getString("userid") == null ? "" : inputObj.getString("userid"));
        }
        orderInfo.setTimestamp(inputObj.getString("timestamp"));
        orderInfo.setChannel(inputObj.getString("channel"));
        orderInfo.setSignature(inputObj.getString("signature"));
        orderInfo.setInvokeface(inputObj.getString("invokeface"));
        return orderInfo;
    }

    /**
     * 业务处理
     *
     * @param orderInfo
     */
    public JSONObject busiOper_img(OrderInfo orderInfo) throws Exception {
        String resultcode = "0";
        String resultinfo = "";
        String jsonParams = "";
        String isviolate = "0";
        String result = "";
        JSONObject resjson = null;
        HashMap map = new HashMap();
        String requestid = "";
        try {
            String imgdata = orderInfo.getImgdata() == null ? "" : orderInfo.getImgdata();
            String url = dictionaryDao.getValue("tencentCheckUrl");
            String channel = orderInfo.getChannel()==null?"":orderInfo.getChannel();

            HashMap paramMap = new HashMap();
            paramMap.put("channel",channel);
            paramMap.put("subchannel",orderInfo.getSubchannel());

            /*新增业务id配置 20210825*/
            int bussinesid = 1;
            if(!"".equals(channel)){
                /*新增业务id通过表查询*/
                log.info("-----业务id开始查询(优先查表）----");
                bussinesid = queryBussinessidByConfig(paramMap);
                if(bussinesid==1) {
                    log_img.info("-----业务id开始接口查询----");
                    bussinesid = queryBussinesdid(paramMap, log_img);
                    if (bussinesid == 1) {
                        log_img.info("-----业务id开始新增----");
                        Boolean res = addBussinesid(paramMap, log_img);
                        if (res) {
                            bussinesid = queryBussinesdid(paramMap, log_img);//再查一次获得新id
                        }
                        log_img.info("-----业务id结束新增----");
                    }
                }
                log_img.info("-----业务id结束查询----");
            }

            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("Action", "ImageModeration");
            json.put("FileContent", imgdata == null ? "" : imgdata);

            json.put("BusinessId", bussinesid);
            jsonParams = json.toJSONString();
            log_img.info(jsonParams);

            /*添加到表*/
            map.put("id", smsCheckDao.getNo());
            map.put("resdata", imgdata);
            map.put("request", jsonParams);
            map.put("channel", orderInfo.getChannel());
            map.put("invokeface", "imgcheck");
            smsCheckDao.addRec(map);
            /**end**/

            /*调接口*/
            result = URLUtil.postJson(url, jsonParams);
            log_img.info(url);
            log_img.info(jsonParams);
            log_img.info(result);
            if (!"".equals(result) && result != null) {
                resjson = JSONObject.fromObject(result);
                JSONObject jsonObject = resjson.getJSONObject("Response");
                requestid = jsonObject.getString("RequestId");
                if (jsonObject.getJSONObject("Data") != null) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("Data");
                    String evilflag = jsonObject2.getString("EvilFlag");
                    isviolate = evilflag;
                    log_img.info("是否恶意===>evilflag==>" + evilflag);
                    resultinfo = jsonObject2.toString();
                } else if (jsonObject.getJSONObject("Error") != null) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("Data");
                    resultcode = jsonObject2.getString("Code");
                    resultinfo = jsonObject2.getString("Message");
                    throw new BussinessException(resultcode, resultinfo);
                } else {
                    throw new BussinessException("8001", "json解析错误，result不为空");
                }
            } else {
                throw new BussinessException("8000", "result为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                resultinfo = ((BussinessException) e).getMessage();
            } else {
                resultcode = "8000";
                resultinfo = "出现异常，" + e.toString();
            }
            throw e;
        } finally {
            //更新表
            map.put("requestid", requestid);
            map.put("isviolate", isviolate);
            map.put("resultinfo", resultinfo.length() > 4000 ? resultinfo.substring(0, 2000) : resultinfo);
            smsCheckDao.upRec(map);
            return resjson;
        }
    }

    /**
     * 业务处理
     *
     * @param inputObj
     */
    public JSONObject busiOper_audio(com.alibaba.fastjson.JSONObject inputObj) throws Exception {
        String resultcode = "0";
        String resultinfo = "";
        String jsonParams = "";
        String isviolate = "0";
        String result = "";
        JSONObject resjson = null;
        HashMap map = new HashMap();
        String requestid = "";//回调时需要用此id进行过滤
        try {
            String callbackURL = inputObj.get("callbackURL") == null ? "" : inputObj.getString("callbackURL");
            String channel = inputObj.get("channel") == null ? "" : inputObj.getString("channel");
            Boolean live = inputObj.get("live") == null ? false : inputObj.getBoolean("live");
            JSONArray audioTasks = inputObj.get("audioTasks") == null ? null : inputObj.getJSONArray("audioTasks");
            String url = dictionaryDao.getValue("tencentCheckUrl");
            String kc_callbackurl = dictionaryDao.getValue("tencentCallback") + "audioCallback";

            HashMap paramMap = new HashMap();
            paramMap.put("channel",channel);
            paramMap.put("subchannel",inputObj.get("subchannel"));

            /*新增业务id配置 20210825*/
            int bussinesid = 1;
            if(!"".equals(channel)){
                log.info("-----业务id开始查询(优先查表）----");
                bussinesid = queryBussinessidByConfig(paramMap);
                if(bussinesid==1) {
                    log_audio.info("-----业务id开始接口查询----");
                    bussinesid = queryBussinesdid(paramMap, log_audio);
                    if (bussinesid == 1) {
                        log_audio.info("-----业务id开始新增----");
                        Boolean res = addBussinesid(paramMap, log_audio);
                        if (res) {
                            bussinesid = queryBussinesdid(paramMap, log_audio);//再查一次获得新id
                        }
                        log_audio.info("-----业务id结束新增----");
                    }
                }
                log_audio.info("-----业务id结束查询----");
            }

            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("Action", "AudioModeration");
            json.put("CallbackURL", kc_callbackurl);
            json.put("Live", live);
            json.put("AudioTasks", audioTasks);

            json.put("BusinessId", bussinesid);
            jsonParams = json.toJSONString();
            log_audio.info(jsonParams);

            /*添加到表*/
            map.put("id", smsCheckDao.getNo());
            map.put("resdata", audioTasks == null ? "" : audioTasks.toString());
            map.put("request", jsonParams);
            map.put("channel", channel);
            map.put("invokeface", "audiocheck");
            map.put("callbackurl", callbackURL);
            smsCheckDao.addRec(map);
            /**end**/

            /*调接口*/
            result = URLUtil.postJson(url, jsonParams);
            log_audio.info(url);
            log_audio.info(jsonParams);
            log_audio.info(result);
            resultinfo = result;
            if (!"".equals(result) && result != null) {
                resjson = JSONObject.fromObject(result);
                JSONObject jsonObject = resjson.getJSONObject("Response");
                if (jsonObject.getString("RequestId") != null) {
                    requestid = jsonObject.getString("RequestId");
                } else {
                    throw new BussinessException("8001", "json解析错误，result不为空");
                }
            } else {
                throw new BussinessException("8000", "result为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                resultinfo = ((BussinessException) e).getMessage();
            } else {
                resultcode = "8000";
                resultinfo = "出现异常，" + e.toString();
            }
            throw e;
        } finally {
            //更新表
            map.put("requestid", requestid);
            map.put("resultinfo", resultinfo.length() > 4000 ? resultinfo.substring(0, 2000) : resultinfo);
            smsCheckDao.upRec2(map);
            return resjson;
        }
    }

    /**
     * 业务处理
     *
     * @param inputObj
     */
    public JSONObject busiOper_video(com.alibaba.fastjson.JSONObject inputObj) throws Exception {
        String resultcode = "0";
        String resultinfo = "";
        String jsonParams = "";
        String isviolate = "0";
        String result = "";
        HashMap map = new HashMap();
        String requestid = "";
        JSONObject resjson = null;
        try {
            String callbackURL = inputObj.get("callbackURL") == null ? "" : inputObj.getString("callbackURL");
            String channel = inputObj.get("channel") == null ? "" : inputObj.getString("channel");
            Boolean live = inputObj.get("live") == null ? false : inputObj.getBoolean("live");
            JSONArray videotasks = inputObj.get("videoTasks") == null ? null : inputObj.getJSONArray("videoTasks");
            String url = dictionaryDao.getValue("tencentCheckUrl");
            String kc_callbackurl = dictionaryDao.getValue("tencentCallback") + "videoCallback";

            HashMap paramMap = new HashMap();
            paramMap.put("channel",channel);
            paramMap.put("subchannel",inputObj.get("subchannel"));

            /*新增业务id配置 20210825*/
            int bussinesid = 1;
            if(!"".equals(channel)){
                log.info("-----业务id开始查询(优先查表）----");
                bussinesid = queryBussinessidByConfig(paramMap);
                if(bussinesid==1) {
                    log_video.info("-----业务id开始接口查询----");
                    bussinesid = queryBussinesdid(paramMap, log_video);
                    if (bussinesid == 1) {
                        log_video.info("-----业务id开始新增----");
                        Boolean res = addBussinesid(paramMap, log_video);
                        if (res) {
                            bussinesid = queryBussinesdid(paramMap, log_video);//再查一次获得新id
                        }
                        log_video.info("-----业务id结束新增----");
                    }
                }
                log_video.info("-----业务id结束查询----");
            }

            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("Action", "VideoModeration");
            json.put("CallbackURL", kc_callbackurl);
            json.put("Live", live);
            json.put("VideoTasks", videotasks);

            json.put("BusinessId", bussinesid);
            jsonParams = json.toJSONString();
            log_video.info(jsonParams);

            /*添加到表*/
            map.put("id", smsCheckDao.getNo());
            map.put("resdata", videotasks == null ? "" : videotasks.toString());
            map.put("request", jsonParams);
            map.put("channel", channel);
            map.put("invokeface", "videocheck");
            map.put("callbackurl", callbackURL);
            smsCheckDao.addRec(map);
            /**end**/

            /*调接口*/
            result = URLUtil.postJson(url, jsonParams);
            log_video.info(url);
            log_video.info(jsonParams);
            log_video.info(result);
            resultinfo = result;
            if (!"".equals(result) && result != null) {
                resjson = JSONObject.fromObject(result);
                JSONObject jsonObject = resjson.getJSONObject("Response");
                if (jsonObject.getString("RequestId") != null) {
                    requestid = jsonObject.getString("RequestId");
                } else {
                    throw new BussinessException("8001", "json解析错误，result不为空");
                }
            } else {
                throw new BussinessException("8000", "result为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                resultinfo = ((BussinessException) e).getMessage();
            } else {
                resultcode = "8000";
                resultinfo = "出现异常，" + e.toString();
            }
            throw e;
        } finally {
            //更新表
            map.put("requestid", requestid);
            map.put("resultinfo", resultinfo.length() > 4000 ? resultinfo.substring(0, 2000) : resultinfo);
            smsCheckDao.upRec2(map);
            return resjson;
        }
    }

    /**
     * 回调业务处理
     *
     * @param inputObj
     */
    public void busiOper_callback(com.alibaba.fastjson.JSONObject inputObj, int type) throws Exception {
        String resultcode = "0";
        String resultinfo = "";
        String isviolate = "0";
        HashMap map = new HashMap();
        try {
            String requestid = inputObj.get("RequestId") == null ? "" : inputObj.getString("RequestId");

            String invokeface = "audiocheck";
            if (type==1) {
                invokeface = "videocheck";
            }
            String[] eviltype_audio = {"PornDetect", "PolityDetect", "CurseDetect", "MoanDetect"};
            String[] eviltype_video = {"HotDetect", "IllegalDetect", "PolityDetect", "PornDetect", "Similar", "TerrorDetect", "AdvertiseDetect", "CurseDetect"};
            log_callback.info("----接口---" + invokeface);
            log_callback.info("----requestid---" + requestid);
            log_callback.info(inputObj.toJSONString());

            //20220408修改 对于汇总包，直接忽略，不进行处理
            boolean flag = false;
            if(inputObj.getInteger("Finished")==null){
                flag = true;
            }else if(inputObj.getInteger("Finished")!=1){
                flag = true;
            }


            if (inputObj.getJSONObject("Data") != null && flag) {
                com.alibaba.fastjson.JSONObject jsonObject2 = inputObj.getJSONObject("Data");
                String detecttype = inputObj.getString("DetectType");
                if ("Audio".equals(detecttype)) {
                    for (String s : eviltype_audio) {
                        String res = "0";
                        com.alibaba.fastjson.JSONObject jsonObject = jsonObject2.getJSONObject(s);
                        if (jsonObject != null) {
                            res = jsonObject.getString("HitFlag");
                            log_callback.info("audio是否违规>>>" + res);
                            if ("1".equals(res)) {
                                isviolate = res;
                                break;
                            }
                        }
                    }
                } else {
                    for (String s : eviltype_video) {
                        String res = "0";
                        com.alibaba.fastjson.JSONObject jsonObject = jsonObject2.getJSONObject(s);
                        if (s != null) {
                            res = jsonObject.getString("HitFlag");
                            log_callback.info("video是否违规>>>" + res);
                            if ("1".equals(res)) {
                                isviolate = res;
                                break;
                            }
                        }
                    }
                }
            }

            /*更新到表*/
            map.put("requestid", requestid);
            String callbackresult = "";
            if(inputObj.toString()!=null && inputObj.toString().length()>4000) {
                callbackresult = inputObj.toString().substring(0, 2000);
            }else {
                callbackresult = inputObj.toString();
            }
            map.put("callbackresult", callbackresult);
            map.put("invokeface", invokeface);//过滤条件 invokeface+requestid
            map.put("isviolate", isviolate);
//            smsCheckDao.upCallbackRec(map); 由于一个请求会有多条回调，故采用新表TD_TENCENTCHECK_CALLBACK记录回调数据 20220310
            HashMap resmap = smsCheckDao.getCallbackUrl(map);
            String callbackurl = "";
            String channel = "";
            if (resmap != null) {
                callbackurl = resmap.get("CALLBACKURL") == null ? "" : resmap.get("CALLBACKURL").toString();
                channel = resmap.get("CHANNEL") == null ? "" : resmap.get("CHANNEL").toString();
                map.put("callbackurl",callbackurl);
                map.put("channel",channel);
            }
            String id = smsCheckDao.getNo();
            map.put("id",id);
            smsCheckDao.addCallbackRec(map);//将数据插入到新表

            //获取callbackurl 开始调接口
            //HashMap resmap = smsCheckDao.getCallbackUrl(map);
//            if (resmap != null) {
//                callbackurl = resmap.get("CALLBACKURL") == null ? "" : resmap.get("CALLBACKURL").toString();
//                channel = resmap.get("CHANNEL") == null ? "" : resmap.get("CHANNEL").toString();
//            }
            if (!"".equals(callbackurl) && !"".equals(channel)) {
                /*调接口*/
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("requestid", requestid);
                jsonObject.put("result", inputObj);
                jsonObject.put("invokeface", invokeface);
                jsonObject.put("channel", channel);
                String jsonParams = jsonObject.toString();
                String result = URLUtil.postJson(callbackurl, jsonParams);
                log_callback.info("-----------调合作方接口通知----------");
                log_callback.info(callbackurl);
                log_callback.info(jsonParams);
                log_callback.info(result);
                if (!"".equals(result) && result != null) {
                    resultinfo = result;
                    map.put("notifyresult",resultinfo.length() > 4000 ? resultinfo.substring(0, 2000) : resultinfo);
//                    smsCheckDao.upNotifyRec(map);
                    smsCheckDao.upCallbackRec(map);
                }
                log_callback.info("-----------调合作方接口通知end----------");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                resultinfo = ((BussinessException) e).getMessage();
            } else {
                resultcode = "8000";
                resultinfo = "出现异常，" + e.toString();
            }
            throw e;
        }
    }


    /*
    * 业务接口 新增
    * */
    public Boolean addBussinesid(HashMap paramMap,Logger log) throws BussinessException {
        String jsonParams = "";
        String result = "";
        //优先取子渠道，如果子渠道空，则取父渠道
        String name = "";
        if(paramMap.get("subchannel")==null || "".equals(paramMap.get("subchannel"))){
            String channel = paramMap.get("channel").toString();
            name = smsCheckDao.getChannelName(channel);
        }else{
            name = paramMap.get("subchannel").toString();
        }
        Boolean flag = false;
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("Module", "MG");
        json.put("Action", "PreAddBusiness");
        json.put("Name", name);
        jsonParams = json.toJSONString();

        /*调接口*/
        String url = dictionaryDao.getValue("tencentBusid");
        try {
            result = URLUtil.postJson(url, jsonParams);
            log.info(url);
            log.info(jsonParams);
            log.info(result);
            com.alibaba.fastjson.JSONObject inputObj = new com.alibaba.fastjson.JSONObject().parseObject(result);
            if (inputObj.get("RetCode") != null) {
                if("0".equals(inputObj.getString("RetCode"))){
                    flag = true;
                }
            }
        }catch (Exception e){
            throw new BussinessException("9000", "新增腾讯业务id失败");
        }

        return  flag;
    }


    /*
    * 业务接口 查询
    * */
    public int queryBussinesdid(HashMap paramMap,Logger log) throws BussinessException {
        String jsonParams = "";
        String result = "";
        //优先取子渠道，如果子渠道空，则取父渠道
        String name = paramMap.get("channel").toString();
        if(paramMap.get("subchannel")!=null && !"".equals(paramMap.get("subchannel"))){
            name = paramMap.get("subchannel").toString();
        }else{
            //subchannel为空时，name从表里拿
            name = smsCheckDao.getChannelName(name);
        }
        int id = 1;
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("Module", "MG");
        json.put("Action", "PreListBusiness");
        json.put("BusinessName", name);
        jsonParams = json.toJSONString();

        /*调接口*/
        String url = dictionaryDao.getValue("tencentBusid");
        try {
            result = URLUtil.postJson(url, jsonParams);
            log.info(url);
            log.info(jsonParams);
            log.info(result);
            com.alibaba.fastjson.JSONObject inputObj = new com.alibaba.fastjson.JSONObject().parseObject(result);
            if (inputObj.get("RetCode") != null) {
                if("0".equals(inputObj.getString("RetCode"))){
                    com.alibaba.fastjson.JSONObject jsonObject2 = inputObj.getJSONObject("Response");
                    com.alibaba.fastjson.JSONArray jsonArray = jsonObject2.getJSONArray("Result");
                    if(jsonArray.size()>0) {
                        for(int i=0;i<jsonArray.size();i++){
                            String tencentName =  jsonArray.getJSONObject(i) == null?"":jsonArray.getJSONObject(i).getString("Name");
                            if(name.equals(tencentName)){
                                id = jsonArray.getJSONObject(i) == null ? 1 : jsonArray.getJSONObject(i).getInteger("Id");
                                break;
                            }
                        }
                        if(id!=1){
                            //添加到表
                            paramMap.put("bussinessid",id);
                            smsCheckDao.saveBussinesid(paramMap);
                        }
                    }
                }
            }
        }catch (Exception e){
            throw new BussinessException("9000", "查询腾讯业务id失败");
        }

        return  id;
    }

    /*
     * 业务接口 查询
     * */
    public int queryBussinessidByConfig(HashMap paramMap) throws BussinessException {
        int id = 1;
        try {
            HashMap map = new HashMap();
            map.put("channel",paramMap.get("channel"));
            map.put("subchannel",paramMap.get("subchannel"));
            System.out.println(smsCheckDao.getBussinesid(map));
            String s = smsCheckDao.getBussinesid(map);
            if(s!=null && !"".equals(s)){
                id = Integer.parseInt(s);
            }
        }catch (Exception e){
            throw new BussinessException("9001", "查询腾讯业务id失败(查表）");
        }
        return  id;
    }
}
