package com.chinacreator.process.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.process.bean.BoYuanBean;
import com.chinacreator.process.bean.BoYuanLogBean;
import com.chinacreator.process.bean.BoYuanPushBean;
import com.chinacreator.process.dao.BoYuanSyncDao;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.util.HttpBoYuanInvoke;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.fakeid.MD5;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

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


/**
 * 后向送会员异步处理
 * @author xu.zhou
 * @date 20200818
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BoYuanSyncJob {

    private static Logger logger = Logger.getLogger("boyuan");

    @Autowired
    private BoYuanSyncDao boYuanSyncDao;

    @Autowired
    private DictionaryDao dictionaryDao;


    public void doProcess() throws Exception {
        logger.info("铂源数据推送定时任务开始========");
        long beginTime = System.currentTimeMillis();
//        BoYuanSyncDao boYuanSyncDao = new BoYuanSyncDao();
        List<BoYuanBean> list = boYuanSyncDao.findSyncData();
        if(list != null && list.size()>0){
            //将list封装成要发送的list数据
            List<BoYuanPushBean> pushList = convertData(list);
            String jsonParams = JsonUtil.objectToJson(pushList);
//            String jsonParams= jsonParams1.length()>1000?jsonParams1.substring(0,1000):jsonParams1;
            //批量推送
            String result = syncBoYuanBatch(pushList);
            if(result!= null && !result.equals("")){
                //解析json
                JSONObject jo = JSON.parseObject(result);
                String  code = jo.getString("code");//获取code的值
                //{"code":10000,"message":"操作成功","data":"订购成功"}
                //0:已同步 1:未同步  2:正在同步中  3:同步失败
                String status = "3";
                String synctime = getDateStr(new Date());
                logger.info(synctime+"=====发送报文:【"+jsonParams+"】响应报文：【"+result+"】");
                if(code!= null && code.equals("10000")) //成功
                    status = "0";
                for(BoYuanBean bean: list){
                    bean.setStatus(status);
                    bean.setSynctime(synctime);
                    bean.setInputparams(synctime);
                    bean.setOutparams(result);

                    BoYuanLogBean logBean = new BoYuanLogBean();
                    logBean.setSyncid(bean.getId());
                    logBean.setUserid(bean.getUserid());
                    logBean.setSpid(bean.getSpid());
                    logBean.setCpid(bean.getCpid());
                    logBean.setType(bean.getType());
                    logBean.setSynctime(synctime);
                    logBean.setInputtime(getDateStr(new Date()));
                    logBean.setInputparams(jsonParams);
                    logBean.setOutparams(result);
                    logBean.setInputparamsback(synctime);
                    //1修改主表数据
                    boYuanSyncDao.updateBoYuan(bean);
                    //2插入日志表数据
                    boYuanSyncDao.insertBoYuanLogBean(logBean);
                }
            }
        }
        logger.info("铂源数据推送定时任务完成，耗时："+(System.currentTimeMillis()-beginTime)/1000+" 秒");
        logger.info("铂源数据推送定时任务结束！");
    }


    //获取系统时间
    public String getDateStr(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(date);
        return dateString;
    }

    //将金额转换成2位小数
    public String getPrice(String param){
        String price = "0.00";
        if(param!= null && !param.equals("")) {
            BigDecimal b = new BigDecimal(param);
            price = b.setScale(2,BigDecimal.ROUND_HALF_UP).toString();
        }
        return price;
    }


    //将数据进行封装
    public List<BoYuanPushBean> convertData(List<BoYuanBean> list){
        List<BoYuanPushBean> pushList = new ArrayList<BoYuanPushBean>();
        String timestamp = System.currentTimeMillis() / 1000 + "";
        String channel = "af1af29d8821db08342578755f8c30a6";
        String secretkey = "f589b0116f63d840483833a0ef094645";
        for (BoYuanBean bean:list ) {
            BoYuanPushBean pushBean = new BoYuanPushBean();
            pushBean.setSpid(bean.getSpid());
            pushBean.setMoney(getPrice(bean.getPrice()));
            pushBean.setOrderid(bean.getId());
            pushBean.setPhone(bean.getUserid());
            pushBean.setChannel(channel);
            pushBean.setType(bean.getType());
            pushBean.setTimestamp(timestamp);
            pushBean.setSign(MD5.MD5Encode(pushBean.getSpid() + pushBean.getChannel()
                    + pushBean.getOrderid() + pushBean.getPhone() + pushBean.getType() + pushBean.getTimestamp() + secretkey));
            pushList.add(pushBean);
        }
        return pushList;
    }


//
//
//	/**
//	 *伯源订购关系同步推送
//	 */
//	public  void syncBoYuan1(String phone,String spid,String channel,String type,String orderid,String money) {
//		try {
//			String secretkey = "f589b0116f63d840483833a0ef094645";
//			String timestamp = System.currentTimeMillis() / 1000 + "";
//			String sign = MD5.MD5Encode(spid + channel + orderid + phone + type + timestamp + secretkey);
//			Map<String, String> params = new HashMap<String, String>();
//			params.put("spid", spid);
//			params.put("money", money);
//			params.put("channel", channel);
//			params.put("type", type);
//			params.put("timestamp", timestamp);
//			params.put("phone", phone);
//			params.put("sign", sign);
//			params.put("orderid", orderid);
//			List<Map<String,String>> list=new ArrayList<Map<String, String>>();
//			list.add(params);
//    jsonParams = "[{\"sign\":\"81ce9f00ba1237db32ff08d31b93f59d\",\"timestamp\":\"1622172065\",\"phone\":\"18673197465\",\"spid\":\"1211\",\"money\":\"1.00\",\"orderid\":\"1\",\"type\":\"0\",\"channel\":\"af1af29d8821db08342578755f8c30a6\"}" +
//                    ",{\"sign\":\"81ce9f00ba1237db32ff08d31b93f59d\",\"timestamp\":\"1622172065\",\"phone\":\"18673197465\",\"spid\":\"1211\",\"money\":\"1.00\",\"orderid\":\"1\",\"type\":\"0\",\"channel\":\"af1af29d8821db08342578755f8c30a6\"}]";
////			System.out.println("------"+JSONObject.toJSONString(list));
//			String jsonParams = JsonUtil.objectToJson(list);
//			System.out.println("------"+jsonParams);
////			cbReqParams = JsonUtil.objectToJson(orderOutObj);
//			//String resp = URLUtil.postJson("https://face.mige.tv/cartoontest/insetApi/priorOrder", JSONObject.toJSONString(params));
//			Map reqProperty = new HashMap();
//			reqProperty.put("Content-type", "application/json;charset=UTF-8");
////			reqProperty.put("Content-Type", "application/json; charset=UTF-8");
////			reqProperty.put("Accept", "application/json");
//			String  url="https://face.mige.tv/cartoontest/insetApi/priorOrder";
//			String resp = HttpInvoke.sendhttpsReq("POST", url, jsonParams, getProperty());
////			String resp= HttpInvoke.sendhttpsReq("POST","https://face.mige.tv/cartoontest/insetApi/priorOrder",JsonUtil.objectToJson(list),reqProperty,0);
////			String resp= HttpInvoke.sendHttpByPost("POST", "https://face.mige.tv/cartoontest/insetApi/priorOrder", JSONObject.toJSONString(list), reqProperty);
// resp="{\"code\":10000,\"message\":\"操作成功\",\"data\":\"订购成功\"}";
// System.out.println(resp);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}


    /**
     * 批量数据推送且接收返回信息
     * @param list
     */
    public  String syncBoYuanBatch(List<BoYuanPushBean> list) {
        String resp = "";
        try {
            String jsonParams = JsonUtil.objectToJson(list);
            Map reqProperty = new HashMap();
            reqProperty.put("Content-type", "application/json;charset=UTF-8");
//            DictionaryDao dictionaryDao = new DictionaryDao();
            String url = dictionaryDao.getValue("boyuanDataPushUrl");//调用数据推送接口
            resp = HttpBoYuanInvoke.sendhttpsReq("POST", url, jsonParams, getProperty());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }


    /**
     * 单条数据推送
     * @param phone
     * @param spid
     * @param channel
     * @param type
     * @param orderid
     * @param money
     */
    public  void syncBoYuan(String phone,String spid,String channel,String type,String orderid,String money) {
        try {
            String secretkey = "f589b0116f63d840483833a0ef094645";
            String timestamp = System.currentTimeMillis() / 1000 + "";
            String sign = MD5.MD5Encode(spid + channel + orderid + phone + type + timestamp + secretkey);
            Map<String, String> params = new HashMap<String, String>();
            params.put("spid", spid);
            params.put("money", money);
            params.put("channel", channel);
            params.put("type", type);
            params.put("timestamp", timestamp);
            params.put("phone", phone);
            params.put("sign", sign);
            params.put("orderid", orderid);
            List<Map<String,String>> list=new ArrayList<Map<String, String>>();
            list.add(params);
            String jsonParams = JsonUtil.objectToJson(list);

            System.out.println("------"+jsonParams);
            Map reqProperty = new HashMap();
            reqProperty.put("Content-type", "application/json;charset=UTF-8");
            String  url="https://face.mige.tv/cartoontest/insetApi/priorOrder";
            String resp = HttpBoYuanInvoke.sendhttpsReq("POST", url, jsonParams, getProperty());
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Map getProperty(){
        Map reqProperty = new HashMap();
        reqProperty.put("Content-type", "application/json;charset=UTF-8");
        return reqProperty;
    }

//	syncBoYuan("18673197465","1211","af1af29d8821db08342578755f8c30a6","0","2021051345","2.00");
//	public static void main(String[] args)throws Exception {
    // 订购接口
//		new BoYuanSyncJob().doProcess();
//	}
}
