package com.chinacreator.video.restful.service;

import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.restful.bean.AlertUrl;
import com.chinacreator.video.restful.bean.FlowBean;
import com.chinacreator.video.restful.dao.FlowAlertCpDao;
import com.chinacreator.video.util.AESUtil;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.IpValidate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;

@Service
public class FlowAlertCpService {

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private FlowAlertCpDao flowAlertCpDao;

    private static final String KEY = "ac22273abb2f4960";

    public void checkip() throws Exception{
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setChannel("flowAlertCp");
        orderInfo.setInvokeface("flowAlertCp");
        orderInfo.setCpid("flowAlertCp");
        orderInfo.setSpid("flowAlertCp");
        ipValidate.volidate(orderInfo);
    }


    public String process(FlowBean bean, HashMap<String,String> logmap) throws Exception {
        String resp = "";
        AlertUrl alertUrl = flowAlertCpDao.queryAlertUrl(bean.getCpid());
        if (alertUrl!=null){
            AlertUrl kc = flowAlertCpDao.queryAlertUrl("kc");
            String userid = DesUtil.decode(bean.getUserid(), kc.getNetpwd());
            if("1".equals(alertUrl.getMobtype())){
                userid = AESUtil.encrypt(userid, KEY);
            }
            userid = DesUtil.encode(userid,alertUrl.getNetpwd());
            String signature = MD5.MD5Encode(userid+bean.getCpid()+bean.getTimestamp()+alertUrl.getNetpwd());
            userid = URLEncoder.encode(userid,"utf-8");
            String url = alertUrl.getAlerturl() + "?userid="+userid+"&cpid="+bean.getCpid()+"&maxflow="+bean.getMaxflow()+"&flow="+bean.getFlow()+"&timestamp="+bean.getTimestamp()+"&signature="+signature;
            logmap.put("请求Url", url);
            resp = URLUtil.get(url);
        } else {
            resp =  "{\"resultcode\":\"0000\"}";
        }
        logmap.put("返回结果", resp);
        return  resp;
    }
}
