package com.weiqi.mis.impl;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.weiqi.mis.DateUtil;
import com.weiqi.mis.ReturnValue;
import com.weiqi.mis.domain.*;
import com.weiqi.mis.mapper.WxXrPemsOrderMapper;
import com.weiqi.mis.mapper.WxXrPemsOrderPushLogMapper;
import com.weiqi.vo.OrderInfoVo;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.weiqi.mis.*;

@Service
public class MsgServiceImpl implements MsgService {

    public static Cache<String, Integer> brandIdCache =
            Caffeine.newBuilder().expireAfterWrite(12, TimeUnit.HOURS).build();
    public static Cache<String, JSONObject> seriesIdCache =
            Caffeine.newBuilder().expireAfterWrite(12, TimeUnit.HOURS).build();

    private Logger logger = LoggerFactory.getLogger(getClass());


    // 记录上次处理时间
    Map<String, Long> currTimeMap = new ConcurrentHashMap<>();

    @Autowired
    private WxXrPemsOrderMapper wxXrPemsOrderMapper;
    @Autowired
    private WxXrPemsOrderPushLogMapper wxXrPemsOrderPushLogMapper;

    @Resource(name = "threadPool")
    Executor executor;

    public Object getinfo() {

        return "";
    }


    /**
     * 查询所有appid
     *
     * @return
     */
    public ReturnValue getAppId() {


        return ReturnValue.buildSuccessdata(null, 1);

    }

    /**
     * 查询所有sp
     *
     * @return
     */
    public ReturnValue getsp() {

        return ReturnValue.buildSuccessdata(null, 1);

    }

    @Override
    public Object usableGetsp() {

        return ReturnValue.buildSuccessdata(null, 1);
    }


    @Override
    public Object getOrderinfo(OrderInfoVo records) {

        WxXrPemsOrderExample example1 = new WxXrPemsOrderExample();
        WxXrPemsOrderExample.Criteria cri1 = example1.createCriteria();


        int offset = 0;
        int pagesize = records.getLimit();
        int pageNumber = records.getPage();

        if (records.getStatus() != null && !records.getStatus().equals("null")
                && records.getStatus().toString().length() > 0) {
            cri1.andStatusEqualTo(records.getStatus());
        }

        if (records.getPlatenumber() != null && !records.getPlatenumber().equals("null")
                && records.getPlatenumber().toString().length() > 0) {
            cri1.andPlatenumberLike("%" + records.getPlatenumber() + "%");
        }
        offset = (pageNumber - 1) * pagesize;
        example1.setOrderByClause(" create_time desc   limit " + offset + " ," + pagesize);

        if (records.getEndTime().length() > 0 && records.getBeginTime().length() > 0) {
            cri1.andCreateTimeBetween(DateUtil.string2Date(records.getBeginTime(), "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.string2Date(records.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        } else {
            cri1.andCreateTimeBetween(DateUtil.getDayBegin(), DateUtil.getDayEnd());

        }
        int num = wxXrPemsOrderMapper.countByExample(example1);
        List<WxXrPemsOrder> wxXrPemsOrders = wxXrPemsOrderMapper.selectByExample(example1);

        return ReturnValue.buildSuccessdata(wxXrPemsOrders, num);
    }

    @Override
    public Object getOrderinfoLog(OrderInfoVo records) {

        WxXrPemsOrderPushLogExample example1 = new WxXrPemsOrderPushLogExample();
        WxXrPemsOrderPushLogExample.Criteria cri1 = example1.createCriteria();


        int offset = 0;
        int pagesize = records.getLimit();
        int pageNumber = records.getPage();

        if (records.getStatus() != null && !records.getStatus().equals("null")
                && records.getStatus().toString().length() > 0) {
            cri1.andStatusEqualTo(records.getStatus());
        }


        offset = (pageNumber - 1) * pagesize;
        example1.setOrderByClause(" create_time desc   limit " + offset + " ," + pagesize);

        if (records.getEndTime().length() > 0 && records.getBeginTime().length() > 0) {
            cri1.andCreateTimeBetween(DateUtil.string2Date(records.getBeginTime(), "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.string2Date(records.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        } else {
            cri1.andCreateTimeBetween(DateUtil.getDayBegin(), DateUtil.getDayEnd());

        }

        int num = wxXrPemsOrderPushLogMapper.countByExample(example1);
        List<WxXrPemsOrderPushLog> wxXrPemsOrders = wxXrPemsOrderPushLogMapper.selectByExample(example1);

        return ReturnValue.buildSuccessdata(wxXrPemsOrders, num);
    }

    @Override
    public Object addinfo() {

        getbrandInfo();

        return null;
    }

    @Override
    public Object setorderInfo() {

        WxXrPemsOrderExample example1 = new WxXrPemsOrderExample();
        WxXrPemsOrderExample.Criteria cri1 = example1.createCriteria();
        cri1.andSeriesidIsNull();

        List<WxXrPemsOrder> wxXrPemsOrders = wxXrPemsOrderMapper.selectByExample(example1);
        for (WxXrPemsOrder wxXrPemsOrder : wxXrPemsOrders) {
            Integer brandId = brandIdCache.getIfPresent(wxXrPemsOrder.getBrandname());
            JSONObject jsonObject = seriesIdCache.getIfPresent(wxXrPemsOrder.getSeriesname());
            Integer id = jsonObject.getInteger("id");
            String img = jsonObject.getString("img");
            wxXrPemsOrder.setBrandid(brandId);
            wxXrPemsOrder.setSeriesid(id);
            wxXrPemsOrder.setVehiclesrc(img);
            int i = wxXrPemsOrderMapper.updateByPrimaryKeySelective(wxXrPemsOrder);
            logger.info("更新结果为：{}", i);
        }

        return null;
    }

    /**
     * 获取品牌ID
     *
     * @return
     */
    public Map<String, Integer> getbrandInfo() {

        JSONObject js = new JSONObject();
        Map<String, Integer> retmap = new HashMap();
        try {
            String url = "https://api.mycar369.com/api//app/getbrands/v1?appid=LANBBXCXtest&os=android-11-M2011K2C&version=1.1.2&timestamp=1725702019&udid=a97c068f-0ba3-3f3b-a25e-172087d538e2&noncestr=WySsMg&usid=36&_sign=C404D844CC87716925DC40E65F6E4FF9";
            String body = HttpUtil.sendGetRequest(url);
            js = JSONObject.parseObject(body);
            JSONArray objects = js.getJSONObject("result").getJSONArray("brand");
            for (int i = 0; i < objects.size(); i++) {
                retmap.put(objects.getJSONObject(i).getString("brandname"), objects.getJSONObject(i).getInteger("brandid"));
                brandIdCache.put(objects.getJSONObject(i).getString("brandname"), objects.getJSONObject(i).getInteger("brandid"));
                getseries(objects.getJSONObject(i).getInteger("brandid") + "");
            }
        } catch (Exception e) {
            logger.error("{}", e);
        }
        return retmap;
    }


    public JSONObject getseries(String brandId) {
        JSONObject js = new JSONObject();
        try {
            String url = "https://api.mycar369.com/api/app/getseries/v1?brandid=" + brandId + "&appid=LANBBXCXtest&os=android-11-M2011K2C&version=1.1.2&timestamp=1725705334&udid=a97c068f-0ba3-3f3b-a25e-172087d538e2&noncestr=B7aIVh&usid=36&_sign=AF5BBEE40C3C6C7205550B73A3B531E8";
            String body = HttpUtil.sendGetRequest(url);
            js = JSONObject.parseObject(body);
            if (js.getInteger("returncode") == 2000) {
                JSONArray objects = js.getJSONArray("result");
                for (int i = 0; i < objects.size(); i++) {
                    JSONObject jsonObject = objects.getJSONObject(i);
                    seriesIdCache.put(jsonObject.getString("name"), jsonObject);
                }
            }
        } catch (Exception e) {
            js.put("returncode", -1);
            js.put("message", "请求数据报错");
        }

        return js;
    }

}
