package com.salesforce.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import com.alibaba.fastjson.JSONObject;
import com.salesforce.SurveyConfigService;
import com.salesforce.httpclient.HttpClient;
import com.salesforce.httpclient.exception.SalesForceApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartframework.common.GlobalConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class SurveyConfigServiceImpl implements SurveyConfigService {
    /**
     * 加入并发锁控制
     */

    private Lock lock = new ReentrantLock();
    /**
     * 加入并发锁控制
     */

    private final Logger logger = LoggerFactory.getLogger(SurveyConfigServiceImpl.class);


    private HttpClient httpClient = new HttpClient().setHost(GlobalConfig.getConfigValue("salesforce.config.hostSurvey"));


    /**
     * 查询salesforce数据结果
     *
     * @param api
     * @param cmd
     * @return JSON
     */
    @Override
    public  JSONObject querySfResult(String api, String cmd, Map<String, Object> dataMap) throws Exception {
        lock.lock();
        JSONObject postResponse=null;
        try{
            Map<String, Object> resultMap = new HashMap<>();
            int opCount = 0;
            resultMap.put("opCount", opCount);

            String sidCount = "1";
            String token = GlobalConfig.getConfigValue("salesforce.config.token");
            if (token == null || "".equals(token)) {
                return null;
            }
            String appid = GlobalConfig.getConfigValue("salesforce.config.appid", "301");
            String timestamp = (System.currentTimeMillis() / 1000) + "";
            String nonce = String.valueOf(getRandomInteger(100000, 999999));
            String timeString = getTimeString();
            String sid = appid + timeString + fillZero(sidCount, 5);
        /*header*/
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("appid", appid);
            headerMap.put("echostr", genRandomString(6));
            headerMap.put("nonce", nonce);
            headerMap.put("sid", sid);
            String[] signatureParam = {token, timestamp, nonce};
            Arrays.sort(signatureParam);
            headerMap.put("signature", SHA1(signatureParam[0] + signatureParam[1] + signatureParam[2]));
            headerMap.put("timestamp", timestamp);
        /*cmd*/
            Map<String, String> cmdMap = new HashMap<>();
            cmdMap.put("name", cmd);
            //查询传递的参数 queryMap
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("header", headerMap);
            queryMap.put("cmd", cmdMap);
            queryMap.put("data", dataMap);
            postResponse = httpClient.post(api, queryMap);
        }catch (Exception ex){
            ex.printStackTrace();
            lock.unlock();
            throw ex;
        }finally {
            lock.unlock();
        }
        return postResponse!=null?postResponse:null;
    }

    /**
     * 生成随机字符串
     *
     * @param length 要生成长度为多少的字符串
     * @return
     */
    private static String genRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int num = random.nextInt(62);
            buf.append(str.charAt(num));
        }
        return buf.toString();
    }

    /**
     * 生成随机整数
     *
     * @param min 最小
     * @param max 最大
     * @return 按规定的随机整数
     */
    private static int getRandomInteger(int min, int max) {

        Random random = new Random();

        int randomInt = random.nextInt(max) % (max - min + 1) + min;
        return randomInt;
    }

    /**
     * SHA1加密
     *
     * @param decript 要加密的文本
     * @return
     */
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String getTimeString() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);

        String yearstr = String.valueOf(year).substring(2, 4);
        String monthstr = fillZero(String.valueOf(month), 2);

        String daystr = fillZero(String.valueOf(day), 2);
        String hourstr = fillZero(String.valueOf(hour), 2);
        String minutestr = fillZero(String.valueOf(minute), 2);
        String secondstr = fillZero(String.valueOf(second), 2);

        return yearstr + monthstr + daystr + hourstr + minutestr + secondstr;


    }

    /**
     * 左补零
     *
     * @param target 目标字符串
     * @param length 输出字符串长度
     * @return 输出字符串
     */
    private static String fillZero(String target, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < (length - target.length()); i++) {
            sb.append("0");
        }
        sb.append(target);
        return sb.toString();
    }


    public static void main(String[] args) {
        DateFormat dFormat = new SimpleDateFormat("yyyy/MM/dd");
//     2.	管家楼宇收缴率 t_CollectionRate
//      注入服务SurveyConfigService
    	System.out.println("loss");
            SurveyConfigServiceImpl service=new SurveyConfigServiceImpl();
            Map<String, Object> dataMap = new HashMap<>();
//           参数
            dataMap.put("employeeNumber", "2015082909");
//            dataMap.put("phone", "");
        try {
            JSONObject jsonStr = service.querySfResult("apexrest/api/", "t_CollectionRate", dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String im=dFormat.format(new Date());
             String [] imu=im.split("/");
            System.out.println(imu[0]);
            if (Integer.parseInt(imu[1])-1==1){
                  System.out.println(12);
            }
            System.out.println(Integer.parseInt(imu[1])-1);
    }

	@Override
	public Result collectionRate(String employeeNumber) {
//	     2.	管家楼宇收缴率 t_CollectionRate
//      注入服务SurveyConfigService
            SurveyConfigServiceImpl service=new SurveyConfigServiceImpl();
            Map<String, Object> dataMap = new HashMap<>();
//           参数
            dataMap.put("employeeNumber", "000643");
//            dataMap.put("phone", "");
        JSONObject jsonStr = null;
        try {
            jsonStr = service.querySfResult("apexrest/api/", "t_CollectionRate", dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(jsonStr);
            return Response.response(jsonStr);
	}
    /**
     * 查询salesforce数据结果
     *
     * @param api
     * @param cmd
     * @return JSON
     */
    @Override
    public  JSONObject querySfResultUtf8(String api, String cmd, Map<String, Object> dataMap) throws Exception {
        lock.lock();
        JSONObject postResponse=null;
        try{
            Map<String, Object> resultMap = new HashMap<>();
            int opCount = 0;
            resultMap.put("opCount", opCount);

            String sidCount = "1";
            String token = GlobalConfig.getConfigValue("salesforce.config.token");
            if (token == null || "".equals(token)) {
                return null;
            }
            String appid = GlobalConfig.getConfigValue("salesforce.config.appid", "301");
            String timestamp = (System.currentTimeMillis() / 1000) + "";
            String nonce = String.valueOf(getRandomInteger(100000, 999999));
            String timeString = getTimeString();
            String sid = appid + timeString + fillZero(sidCount, 5);
            /*header*/
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("appid", appid);
            headerMap.put("echostr", genRandomString(6));
            headerMap.put("nonce", nonce);
            headerMap.put("sid", sid);
            String[] signatureParam = {token, timestamp, nonce};
            Arrays.sort(signatureParam);
            headerMap.put("signature", SHA1(signatureParam[0] + signatureParam[1] + signatureParam[2]));
            headerMap.put("timestamp", timestamp);
            /*cmd*/
            Map<String, String> cmdMap = new HashMap<>();
            cmdMap.put("name", cmd);
            //查询传递的参数 queryMap
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("header", headerMap);
            queryMap.put("cmd", cmdMap);
            queryMap.put("data", dataMap);
            postResponse = httpClient.postUtf8(api, queryMap);
        }catch (Exception ex){
            ex.printStackTrace();
            lock.unlock();
            throw ex;
        }finally {
            lock.unlock();
        }
        return postResponse!=null?postResponse:null;
    }

}
