package com.chinacreator.video.restful.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.util.DesUtil;
import com.chinacreator.video.util.IpAddrUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.BusiValidate;
import org.apache.commons.lang.StringUtils;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@Component
public class FeeInfoService {

    @Autowired
    private BusiValidate busiVali;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private CommConfDao commConfDao;

    public org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("testredis");

    private static Logger log = Logger.getLogger("feeinfo");


    public void busiCheck(JSONObject inputObj, String invokename) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setChannel(inputObj.getString("channel"));
        orderInfo.setUserid(inputObj.getString("userid"));
        orderInfo.setTimestamp(inputObj.getString("timestamp"));
        orderInfo.setSignature(inputObj.getString("signature"));
        orderInfo.setInvokeface(invokename);
        //ip验证
        busiVali.valiIp(orderInfo);;
        //参数验证
        paramValidate(inputObj,invokename);
        //时间戳验证
        busiVali.valiTime(orderInfo);
        //签名验证
        signValidate(inputObj,invokename);
        //手机号码验证
        mobValidate(inputObj);
    }

    private void paramValidate(JSONObject inputObj, String invokename) throws Exception{
        if(!StringUtils.isNotEmpty(inputObj.getString("userid"))
                || !StringUtils.isNotEmpty(inputObj.getString("channel"))
                || !StringUtils.isNotEmpty(inputObj.getString("signature"))
                || !StringUtils.isNotEmpty(inputObj.getString("timestamp"))
        ){
            throw new BussinessException("80015", "参数异常，");
        }
    }

    /**
     * 签名验证
     * @param
     * @throws Exception
     */
    public void signValidate(JSONObject inputObj, String invokename) throws Exception{
        String lcalsign = getSign(inputObj,invokename);
        lcalsign += channelDao.queryChannel(inputObj.getString("channel")).getPassword();
        lcalsign = MD5.MD5Encode(lcalsign);
        if(!lcalsign.equals(inputObj.getString("signature"))) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }

    /**
     * 拼接签名信息 channel+userid+timestamp
     * @param
     * @return
     */
    public String getSign(JSONObject inputObj, String invokename){
        StringBuilder strb = new StringBuilder();
        strb.append(inputObj.getString("channel"));
        strb.append(inputObj.getString("userid"));
        strb.append(inputObj.getString("timestamp"));
        return strb.toString();
    }

    /**
     * 手机号码验证
     * @param
     * @throws Exception
     */
    private void mobValidate(JSONObject inputObj)throws Exception{
        boolean res = false;
        String usermob = inputObj.getString("userid");
        String pwd = channelDao.queryChannel(inputObj.getString("channel")).getPassword();
        //解密手机号码
        usermob = DesUtil.decode(usermob, pwd);
        if (usermob != null && usermob.length() == 11) {
            usermob = usermob.replaceAll("[\\s-]", "");
            if(usermob.matches(".*(1\\d{10}).*")){
                inputObj.put("usermob", usermob);
                res = true;
            }
        }
        if(res == false){
            throw new BussinessException("9022","手机号码不合法");
        }
    }

    /**
     * 调能力平台查询话费余额
     * @param inputObj
     * @throws Exception
     */
    public String qryFeeInfo(JSONObject inputObj) throws Exception{
        JSONArray data = null;
        String result = "";
        String invokeUrl = ""; //接口地址
        String params = ""; //调接口参数
        String userid = inputObj.getString("usermob"); //（手机号码）
        HashMap<String,String> map = new HashMap<>();
        try {
            invokeUrl =  dictionaryDao.getValue("shareselectfeeinfoUrl");
            params = invokeUrl+"?userid="+userid;
            result = URLUtil.get(params, 30000);
            data = JSON.parseObject(result).getJSONArray("data");
            log.info("data>>>String: "+JSON.parseObject(result).getString("data"));
            log.info("data>>>arr: "+JSON.parseObject(result).getJSONArray("data"));
        } catch (Exception e) {
            e.printStackTrace();
            result = "查询话费余额出现异常，"+e.getMessage();
            log.error(result,e);
            if( e != null && e.getMessage().indexOf("http") != -1){
                throw new Exception("调下游查询接口出现错误");
            }else{
                throw e;
            }
        } finally {
            inputObj.put("data", data);
            log.info(userid+"，接口地址=>"+invokeUrl+"，执行结果=>"+result);
        }

        return result;
    }
}
