package com.chinacreator.process.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.EverySmsDao;
import com.chinacreator.process.exception.BusinessException;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.URLUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhengrong.yan
 * @date 2021/2/1 9:45
 */
public class EverySmsJob {
    private Logger log = Logger.getLogger("everysms");

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private EverySmsDao everySmsDao;

    public void doProcess() throws Exception {
        log.info("每日流量超量短信下发定时任务开始");
        System.out.println("每日流量超量短信下发定时任务开始");
        long beginTime = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = c.getTime();//这是昨天
        String date = sdf.format(yesterday);
        //统计数据到数据库
        List<HashMap> list = everySmsDao.getData(date);
        if (list != null && list.size() > 0) {
            log.info("数据库有效需要处理的数：" + list.size());
            for (HashMap busimap : list) {
                if (busimap.get("COUNT") == 0) {
                    log.info(date + "数据异常,统计数据为0");
                } else {
                    deal(busimap);
                }
            }
        }
        log.info(Thread.currentThread().getName() + "定时任务完成，耗时：" + (System.currentTimeMillis() - beginTime) / 1000 + " 秒");
    }

    /*
     * 处理数据
     * */
    public void deal(Map busimap) {
        Map logMap = new HashMap();
        logMap.put("data", busimap);
        String resultCode = "-1";
        String resultInfo = "";
        String id = String.valueOf(busimap.get("ID"));
        try {
            //提交工单给合作方
            String result = invoke(busimap);
            JSONObject jsonObject = JSON.parseObject(result);
            resultCode = jsonObject.getString("code");
            resultInfo = jsonObject.getString("message");
            //重试三次
            if (!"0".equals(resultCode)) {
                int flag = 1;
                while (flag > 3 || "0".equals(resultCode)) {
                    result = invoke(busimap);
                    JSONObject object = JSON.parseObject(result);
                    resultCode = object.getString("code");
                    resultInfo = object.getString("message");
                    flag++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BusinessException) {
                resultInfo = ((BusinessException) e).getMessage();
                resultCode = ((BusinessException) e).getCode();
            } else {
                resultCode = "8000";
                resultInfo = "系统错误，" + e.getMessage();
            }
        } finally {
            try {
                if (resultInfo != null && resultInfo.length() > 250) {
                    resultInfo = resultInfo.substring(0, 250);
                }
                everySmsDao.upResult(id, resultCode, resultInfo);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("更新数据出现异常，" + id + ", resultCode:" + resultCode + ", resultInfo:" + resultInfo);
            }
            logMap.put("reusltCode", resultCode);
            logMap.put("resultInfo", resultInfo);
            log.info(JsonUtil.objectToJson(logMap));
        }
    }


    /**
     * 调合作方接口
     *
     * @param
     * @return
     * @throws Exception
     */
    private String invoke(Map params) throws Exception {
        String result = "";
        String url = dictionaryDao.getValue("everysmsUrl");
        String jsonParams = "";
        String id = String.valueOf(params.get("ID"));
        JSONObject json = new JSONObject();
        json.put("date", params.get("DATETM"));
        json.put("sendnumber", params.get("COUNT"));
        jsonParams = json.toJSONString();
        log.info("url: " + url);
        log.info(jsonParams);
        result = URLUtil.postJson(url, jsonParams);
        log.info("调合作方接口结果=> id: " + id + " , result: " + result);
        return result;
    }


    /**
     * 解析数据
     *
     * @param body orderId TD_POINTS_ORDER_REC表ID字段，我方生成的订单流水号
     *             orderNo 积分商城订单号
     *             requestId 返回给客户的请求ID
     * @return
     */
    public Map transBean(Map<String, Object> body) {
        String jsonStr = JsonUtil.objectToJson(body);
        return (Map) JsonUtil.jsonToBean(jsonStr, Map.class);
    }


    /**
     * 获取请求属性性
     *
     * @return
     */
    private static Map getProperty() {
        Map reqProperty = new HashMap();
        reqProperty.put("Content-type", "application/json;charset=UTF-8");
        return reqProperty;
    }
}
