package com.chinacreator.process.job;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.PushTwDao;
import com.chinacreator.process.util.DesUtil;
import com.chinacreator.process.util.HttpInvoke;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前向产品订购失败推送拓维后向发短信-黄一鹰
 * @author shuchuan.jin
 * @date 20191212
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class PushTwMQJob {

    private Logger logger = Logger.getLogger(PushTwMQJob.class);

    private Logger log = Logger.getLogger("twhx");

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private PushTwDao pushTwDao;

    @Autowired
    private MessageService messageService;

    public void doProcess() throws Exception {
        logger.info("接收前向产品订购失败推送拓维后向发短信队列JOB启动");
        if (dictionaryDao.getValue("recivemq").equals("0")) {
            long beginTime = System.currentTimeMillis();
            List<MessagePipe> list = messageService.reciveBatchMessage("twhx", 500);
            logger.info("接收前向产品订购失败推送拓维后向发短信队列花费时间：" + (System.currentTimeMillis() - beginTime));
            List<Map> dataList = new ArrayList<Map>();
            for (MessagePipe messagePipe : list) {
                Map reqBean = transBean(messagePipe.getBody());
                dataList.add(reqBean);
            }
            if(dataList != null && dataList.size()>0){
                for (Map reqBean  : dataList) {
                    this.handleOrder(reqBean);
                }
            }
        } else {
            logger.info("停止接收前向产品订购失败推送拓维后向发短信队列消息");
        }
    }

    /**
     * 业务处理
     * @param reqBean
     */
    public void handleOrder(Map reqBean){
        Map logMap = new HashMap();
        logMap.put("data", reqBean);
        String resultCode = "-1";
        String resultInfo = "";
        try {

            Map<String, String> reMap = pushTw(reqBean);

            if(!"0".equals(reMap.get("resultcode"))){//推送未成功
                resultCode = reMap.get("resultcode");
                resultInfo = reMap.get("resultinfo");
            }else{
                resultCode = "0";
                resultInfo = "成功";
            }
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                resultInfo = ((BusinessException) e).getMessage();
                resultCode = ((BusinessException) e).getCode();
            }else{
                e.printStackTrace();
                resultCode = "8000";
                resultInfo = "系统错误，"+e.getMessage();
            }
        } finally{

            //写日志
            logMap.put("reusltCode", resultCode);
            logMap.put("resultInfo", resultInfo);
            log.info(JsonUtil.objectToJson(logMap));
        }
    }




    public Map<String,String> pushTw(Map reqBean){
        Map<String, String> reMap = new HashMap<String,String>();
        String resultcode = "-1"; //失败
        String resultinfo = ""; //失败
        try {
            JSONObject obj = new JSONObject(true);
            //测试地址：https://twtest.wo186.tv/backward-activity/api/hx/sendSMSUrl.json
            //正式地址：https://bpmanagement.wo186.tv/backward-activity/api/hx/sendSMSUrl.json
            String pushUrl = this.dictionaryDao.getValue("pushTwhxUrl");
            System.out.println("pushUrl:"+pushUrl);
            String pwd = "szCQ8PeQ";
            String userid = (String)reqBean.get("userid");
            String kcSpid = (String)reqBean.get("kcSpid");
            String kcCpid = (String)reqBean.get("kcCpid");

            kcSpid = pushTwDao.qryRelaFtoH(kcCpid,kcSpid);

            obj.put("userid", DesUtil.encode(userid,pwd));
            obj.put("kcSpid",kcSpid);
            obj.put("kcCpid",kcCpid);

            String encodeStr = DesUtil.encode(obj.toJSONString(),pwd);

            Map<String,String> param = new HashMap<String, String>();
            param.put("params", URLEncoder.encode(encodeStr,"utf-8"));

   /*         HttpRequest request = new HttpRequest(pushU.
   rl,"POST")
                    .contentType("application/x-www-form-urlencoded").form(param);*/
           // String result = new String(request.bytes(), Charset.forName("UTF-8"));
            String result = HttpInvoke.http("https://backward.mige.tv/backward-activity/api/hx/sendSMSUrl.json", param);;
            log.info("推送拓维后向发短信结果=> userid: " +userid+" , result: "+result);
            JSONObject robj = JSON.parseObject(result);

            resultcode = robj.getString("code");
            resultinfo = robj.getString("message");


        } catch (Exception e) {
            e.printStackTrace();
            log.error("userid: "+reqBean.get("userid")+"推送拓维后向订购失败，"+e);
            resultcode = "8000";
            resultinfo = e.getMessage();
        }

        reMap.put("resultcode",resultcode);
        reMap.put("resultinfo",resultinfo);
        return reMap;

    }




    /**
     * 解析数据
     * @param body
     *
     * @return
     */
    public Map transBean(Map<String, Object> body) {
        String jsonStr = JsonUtil.objectToJson(body);
        return (Map) JsonUtil.jsonToBean(jsonStr, Map.class);
    }




    public static void main(String agrs[]) throws SQLException {
        PushTwMQJob p = new PushTwMQJob();


        Map map = new HashMap();
        map.put("userid","18673687435");
        map.put("kcCpid","youtu");
        map.put("kcSpid","1167");
        System.out.println(p.pushTw(map));


    }




}
