package com.chinacreator.video.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.KuaiShouHelpBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.dto.DataOutPipe;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.service.KuaiShouHelpService;
import com.chinacreator.video.service.UniMobileService;
import com.chinacreator.video.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 快手求助反馈浮层的信息收集功能
 */
@RestController
public class KuaiShouHelpController {
    //private static final Logger log = LoggerFactory.getLogger(KuaiShouHelpController.class);
    private static final  Logger log = LoggerFactory.getLogger("kuaiShouHelp");


    @Autowired
    KuaiShouHelpService kuaiShouHelpService;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private UniMobileService uniMobileService;

    @RequestMapping("/kuaiShouHelp")
    public DataOutPipe<?> hand(@RequestBody KuaiShouHelpBean bean) throws Exception{
        Map<String,Object> logmap = new HashMap<String,Object>();
        DataOutPipe outpipe = new DataOutPipe();
        log.info(bean.toString());
        String resultcode = "";
        String errorinfo = "";
        try {
            logmap.put("reqData", bean);
            //业务验证
            bean.setInvokeface("kuaiShouHelp");
            kuaiShouHelpService.checkOrder(bean);
            //验证通过，生成id
            kuaiShouHelpService.save(bean);
            resultcode = "0";
            errorinfo = "成功";
        }catch (Exception e){
            e.printStackTrace();
            resultcode = "80003";
            errorinfo = "出现异常，"+e.getMessage();
            if(e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
                throw e;
            }else {
                throw new BussinessException(resultcode, errorinfo);
            }
        }finally {
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            logmap.put("rspData", outpipe.getData());
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        return outpipe;
    }

    @RequestMapping("/saveKuaiShouHelpLog")
    public DataOutPipe<?> logHand(@RequestBody KuaiShouHelpBean bean) throws Exception{
        Map<String,Object> logmap = new HashMap<String,Object>();
        DataOutPipe outpipe = new DataOutPipe();
        //获取用户ip
        //String ipAddr = IpAddrUtil.getIpAddr(request);

        String resultcode = "";
        String errorinfo = "";
        try {
            logmap.put("reqData", bean.getIp());
           ///业务验证
            bean.setInvokeface("kuaiShouHelp");
            kuaiShouHelpService.checkOrder4Ip(bean);
            //验证完毕
            kuaiShouHelpService.savePv(bean.getIp());
            resultcode = "0";
            errorinfo = "成功";
        }catch (Exception e){
            e.printStackTrace();
            resultcode = "80003";
            errorinfo = "出现异常，"+e.getMessage();
            if(e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
                throw e;
            }else {
                throw new BussinessException(resultcode, errorinfo);
            }
        }finally {
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            logmap.put("rspData", outpipe.getData());
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        return outpipe;
    }

    @RequestMapping("/kuaiShouCount")
    public DataOutPipe<?> getCount(@RequestBody KuaiShouHelpBean bean) throws Exception{
        Map<String,Object> logmap = new HashMap<String,Object>();
        DataOutPipe outpipe = new DataOutPipe();
        log.info(bean.toString());
        String resultcode = "";
        String errorinfo = "";
        try {
            logmap.put("reqData", bean);
            //业务验证
            bean.setInvokeface("kuaiShouHelp");
            kuaiShouHelpService.checkOrderIp(bean);
            //kuaiShouHelpService.checkOrder(bean);
            //验证通过，查询数据
            //kuaiShouHelpService.save(bean);
            int count = kuaiShouHelpService.findCount();
            resultcode = "0";
            errorinfo = "成功";
            outpipe.setData(count);
        }catch (Exception e){
            e.printStackTrace();
            resultcode = "80003";
            errorinfo = "出现异常，"+e.getMessage();
            if(e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
                throw e;
            }else {
                throw new BussinessException(resultcode, errorinfo);
            }
        }finally {
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            logmap.put("rspData", outpipe.getData());
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        return outpipe;
    }
//1
    @RequestMapping("/mangoCount")
    public DataOutPipe<?> getMangoCount(@RequestBody KuaiShouHelpBean bean) throws Exception{
        Map<String,Object> logmap = new HashMap<String,Object>();
        DataOutPipe outpipe = new DataOutPipe();
        log.info(bean.toString());
        String resultcode = "";
        String errorinfo = "";
        try {
            logmap.put("reqData", bean);
            //业务验证
            bean.setInvokeface("kuaiShouHelp");
            kuaiShouHelpService.checkOrderIp(bean);
            //kuaiShouHelpService.checkOrder(bean);
            //验证通过，查询数据
            //kuaiShouHelpService.save(bean);
            int count = kuaiShouHelpService.findMangoCount();
            resultcode = "0";
            errorinfo = "成功";
            outpipe.setData(count);
        }catch (Exception e){
            e.printStackTrace();
            resultcode = "80003";
            errorinfo = "出现异常，"+e.getMessage();
            if(e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
                throw e;
            }else {
                throw new BussinessException(resultcode, errorinfo);
            }
        }finally {
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            logmap.put("rspData", outpipe.getData());
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        return outpipe;
    }

    /**
     * 快手产品查询接口
     * @param bean
     * @return
     * @throws Exception
     */
    @RequestMapping("/kuaishouOrderQuery")
    public DataOutPipe<?> orderQuery(@RequestBody KuaiShouHelpBean bean) throws Exception{
        //String url = "http://testapi.mige.tv/univideo/getinfo";//联通号判断接口 测试环境1
        String url = "http://csapi.mige.tv:809/univideo/getinfo";//联通号判断接口 生产环境
        String channel = "creators";
        String pwd = "creators20210430";
        String key = "";
        Map<String,Object> logmap = new HashMap<String,Object>();
        DataOutPipe outpipe = new DataOutPipe();
        log.info(bean.toString());
        String resultcode = "";
        String errorinfo = "";
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = IpAddrUtil.getIpAddr2(request);
        log.info("ip地址:"+ip);
        bean.setCpid("kuaishouOrderQuery");
        //bean.setIp(ip);
        try {
            logmap.put("reqData", bean);
            //业务验证
            bean.setInvokeface("kuaishouOrderQuery");
            kuaiShouHelpService.checkOrderIp(bean);
            ChannelBean channelBean = channelDao.queryChannel(bean.getChannel());
            key = channelBean.getPassword();
            String userid = DesUtil.decode(bean.getUserid(),key);
            log.info(userid+"业务验证通过");
            //验证通过，查询是否联通号码
//            String queryUserid = DesUtil.encode(userid,pwd); // 用户手机伪码，采用(DES(手机号，密码))加密
//            String timestamp = (System.currentTimeMillis()) / 1000 + "";
//            String signature = MD5.MD5Encode(queryUserid + channel + timestamp + pwd);
//            JSONObject data = new JSONObject();
//            data.put("userid", queryUserid);
//            data.put("channel", channel);
//            data.put("timestamp", timestamp);
//            data.put("signature", signature);
//            String params = data.toJSONString();
//            String s = HttpRequestTest.postJsonRequest(url, params);
//            JSONObject jsonObject = JSON.parseObject(s);
//            String resultCode = (String) jsonObject.get("resultCode");
            Map<String,String> map = uniMobileService.getMobileInfo(userid);
            String resultInfo=map.get("resultInfo");
            log.info("联通号码判断接口响应："+map);
            if(!(resultInfo != null && !resultInfo.equals("")&&resultInfo.equals("联通"))){
                //非联通号码无资格
                resultcode = "1";
                errorinfo = "成功";
                outpipe.setResultcode(resultcode);
                outpipe.setErrorinfo(errorinfo);
                logmap.put("rspData", outpipe.getData());
                logmap.put("resultcode", resultcode);
                logmap.put("errorinfo", errorinfo);
                log.info(JSON.toJSONString(logmap)); //写日志文件
                return outpipe;
            }
            log.info(bean.getUserid()+"为联通号码");
            //联通号码，产品表内的产品是否有订购关系
            bean.setUserid(userid);
            int count = kuaiShouHelpService.queryOrderRelation(bean.getUserid());
            if(count == 0){
                //无订生效购关系有订购资格
                resultcode = "0";
                errorinfo = "成功";
                outpipe.setResultcode(resultcode);
                outpipe.setErrorinfo(errorinfo);
                logmap.put("rspData", outpipe.getData());
                logmap.put("resultcode", resultcode);
                logmap.put("errorinfo", errorinfo);
                log.info(JSON.toJSONString(logmap)); //写日志文件
            }else {
                //有订生效购关系无订购资格
                resultcode = "1";
                errorinfo = "成功";
                outpipe.setResultcode(resultcode);
                outpipe.setErrorinfo(errorinfo);
                logmap.put("rspData", outpipe.getData());
                logmap.put("resultcode", resultcode);
                logmap.put("errorinfo", errorinfo);
                log.info(JSON.toJSONString(logmap)); //写日志文件
            }
        }catch (Exception e){
            e.printStackTrace();
            resultcode = "80003";
            errorinfo = "出现异常，"+e.getMessage();
            if(e instanceof BussinessException) {
                resultcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
                throw e;
            }else {
                throw new BussinessException(resultcode, errorinfo);
            }
        }finally {
            outpipe.setResultcode(resultcode);
            outpipe.setErrorinfo(errorinfo);
            logmap.put("rspData", outpipe.getData());
            logmap.put("resultcode", resultcode);
            logmap.put("errorinfo", errorinfo);
            log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        return outpipe;
    }
}
