package com.xxfc.platform.universal.service;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.xxfc.platform.universal.biz.LicensePlateTypeBiz;
import com.xxfc.platform.universal.constant.RedisKey;
import com.xxfc.platform.universal.entity.LicensePlateType;
import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.vo.RentViolationDTO;
import com.xxfc.platform.universal.vo.TrafficViolations;
import com.xxfc.platform.vehicle.entity.Vehicle;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 违章查询
 * 注意:调用"北京库斯曼科技有限公司"的接口,返回参是Unicode编码
 */
@Service
public class TrafficViolationsService {

    @Autowired
    private LicensePlateTypeBiz licensePlateTypeBiz;


    @Value("${ALIYUN.CODE}")
    private String CODE;
    @Value("${RETURN.TYPE}")
    private String TYPE;

    private  ExecutorService executorService= Executors.newCachedThreadPool();
    /**
     *  下列参数,根据使用不同的公司的接口进行修改
     */
    private static final String CITY_HOST = "https://weizhang.market.alicloudapi.com";
    private static final String CITY_PATH = "/wz/province";
    private static final String CITY_METHOD = "GET";

    private static final String VIOLATIONS_HOST = "https://weizhang.market.alicloudapi.com";
    private static final String VIOLATIONS_PATH = "/wz/query";
    private static final String VIOLATIONS_METHOD = "GET";

    private static final String GET_LICENSE_PLATE_TYPE_HOST = "https://weizhang.market.alicloudapi.com";
    private static final String GET_LICENSE_PLATE_TYPE_PATH = "/wz/type";
    private static final String GET_LICENSE_PLATE_TYPE_METHOD = "GET";

    private static final String TYPE_NAME = "type";
    private static final String PLATENO_NAME="plateno";
    private static final String ENGINENO_NAME="engineno";
    private static final String FRAMENO_NAME="frameno";
    private static final String AUTHORIZATION="Authorization";

     @Autowired
     private RedisTemplate redisTemplate;


    /**
     * 支持查询的城市
     * @return
     * @throws Exception
     */
    public String getCity() throws Exception {
        Map<String, String> headers = new HashMap<
                String, String>();
        headers.put(AUTHORIZATION, "APPCODE " + CODE);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put(TYPE_NAME, TYPE);
        HttpResponse httpResponse = CertifHttpUtils.doGet(CITY_HOST, CITY_PATH, CITY_METHOD, headers, querys);
        HttpEntity entity = httpResponse.getEntity();
//        String result = EntityUtils.toString(entity);
//      ArrayList<SearchableCity> searchableCities = JSONObject.parseObject(result, ArrayList.class);
//      searchableCities.forEach(searchableCity ->searchableCity.setCreateDate(new Date()) );
//      searchableCityBiz.insertSearchableCities(searchableCities);
      return unicodeToString(EntityUtils.toString(entity));
    }


    /**s
     * 违章车辆查询
     * @param trafficViolations
     * @return
     */
    public String queryViolations(TrafficViolations trafficViolations) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(AUTHORIZATION, "APPCODE " + CODE);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put(TYPE_NAME, trafficViolations.getType());
        querys.put(PLATENO_NAME, trafficViolations.getPlateno());
        querys.put(ENGINENO_NAME, trafficViolations.getEngineno());
        querys.put(FRAMENO_NAME, trafficViolations.getFrameno());
        HttpResponse httpResponse = CertifHttpUtils.doGet(VIOLATIONS_HOST, VIOLATIONS_PATH, VIOLATIONS_METHOD, headers, querys);
        HttpEntity entity = httpResponse.getEntity();
        return unicodeToString(EntityUtils.toString(entity));
    }

    /**
     * 放入bean中
     * @throws Exception
     * @return
     */
    public ArrayList<LicensePlateType> saveLicensePlateType() throws Exception {
        String result = searchaLicensePlateType();
        if (StringUtils.isBlank(result)) {
            throw new BaseException("错误! 查询不到车辆类型");
        }
        Map<String,Object> resultMap = JSONObject.parseObject(result, Map.class);
        Integer status = (Integer) resultMap.get("status");
        Map<String,String> licensePlateTypeMap = (Map<String, String>) resultMap.get("result");
        if (status!=200||licensePlateTypeMap==null) {
            throw new BaseException("错误! 查询不到车辆类型");
        }
        ArrayList<LicensePlateType> licensePlateTypes=new ArrayList<>();
        for (Map.Entry<String, String> licensePlateTypeEntry : licensePlateTypeMap.entrySet()) {
                 licensePlateTypes.add(new LicensePlateType(licensePlateTypeEntry.getKey(),licensePlateTypeEntry.getValue()));
        }



        return licensePlateTypes;
    }


    /**
     * Unicode转汉字字符串(根据接口返回编码的类型使用)
     * @param str
     * @return
     */

    private String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {

            String group = matcher.group(2);

            ch = (char) Integer.parseInt(group, 16);

            String group1 = matcher.group(1);
            str = str.replace(group1, ch + "");
        }
        return str;

    }


    /**
     * 调用接口获取车辆车牌和代码
     * @return
     * @throws Exception
     */
    public String searchaLicensePlateType() throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(AUTHORIZATION, "APPCODE " + CODE);
        HashMap<String, String> querys = new HashMap<>();

        HttpResponse httpResponse = CertifHttpUtils.doGet(GET_LICENSE_PLATE_TYPE_HOST,
                GET_LICENSE_PLATE_TYPE_PATH,
                GET_LICENSE_PLATE_TYPE_METHOD,
                headers,
                querys
        );
        HttpEntity entity = httpResponse.getEntity();
        return unicodeToString(EntityUtils.toString(entity));
    }

    /**
     * 查询对应的车牌和车牌代码
     * @return
     * @throws Exception
     */
    public List<LicensePlateType> getLicensePlateType() throws Exception {
        List<LicensePlateType> licensePlateTypes = licensePlateTypeBiz.selectListAll();
        if (CollectionUtils.isEmpty(licensePlateTypes)) {

            licensePlateTypes = saveLicensePlateType();

            List<LicensePlateType> finalLicensePlateTypes = licensePlateTypes;



            CompletableFuture.supplyAsync(()->{
                insertLicensePlateType(finalLicensePlateTypes);
                return null;
            },executorService);

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    insertLicensePlateType(finalLicensePlateTypes);
                }
            } );

            thread.start();
        }
        return licensePlateTypes;
    }

    /**
     * 定时修改车牌类型
     * @throws SQLException
     */
//    @Scheduled(cron = "0 0 0 0/7 * ?")
    private void updateLicensePlateType() throws SQLException {
        List<LicensePlateType> licensePlateTypes = licensePlateTypeBiz.selectListAll();
        licensePlateTypeBiz.updateLicensePlateType(licensePlateTypes);
}


    private void insertLicensePlateType(List<LicensePlateType> finalLicensePlateTypes){
         licensePlateTypeBiz.insertLicensePlateType(finalLicensePlateTypes);
    }

    /**
     * 订单完成后调用接口获取车辆信息
     * @param rentViolationDTO
     * @param vehicle
     * @return
     */
    public String getRentViolation(RentViolationDTO rentViolationDTO, Vehicle vehicle) {
        String stringViolationVOS = (String) redisTemplate.opsForValue()
                .get(RedisKey.ILLEGAL_VEHICLE_ENQUIRIES+rentViolationDTO.getVehicleId());
        if (StringUtils.isBlank(stringViolationVOS)) {

        }
        return null;
    }
}
