package com.template.services.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.template.common.utils.CommonUtil;
import com.template.common.utils.RequestUtils;
import com.template.config.ParkConfig;
import com.template.config.ScheduleConfig;
import com.template.model.pojo.SmartCarAccess;
import com.template.mapper.SmartCarAccessMapper;
import com.template.services.SmartCarAccessService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ceshi
 * @since 2024-02-23
 */
@Service
public class SmartCarAccessServiceImpl extends ServiceImpl<SmartCarAccessMapper, SmartCarAccess> implements SmartCarAccessService {
    @Autowired
    ParkConfig parkConfig;

    @Resource
    private ScheduleConfig scheduleConfig;

    private Integer page = 0;
    private Integer size = 20;

    @Scheduled(cron = "0 0/45 * * * ? ")
    @Async
    public void car() {
        if(scheduleConfig.getIsOpen().equals("1")) {
            try {
                getEnterCar(page, size);
                getOutCar(page, size);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


    /**
     * 入场车辆
     *
     * @param pageindex
     * @param pagesize
     * @throws Exception
     */
    public void getEnterCar(Integer pageindex, Integer pagesize) throws Exception {

        String url = parkConfig.getUrl() + "Inquire/GetEnterCar";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid", parkConfig.getAppId());
        jsonObject.put("parkKey", parkConfig.getParkKey());
        String rand = String.valueOf(Math.random());
        jsonObject.put("rand", rand);
        jsonObject.put("version", "v1.1");

//        时间
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime stateTime = now.withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endTime = now.withHour(23).withMinute(59).withSecond(59);
        String startData = stateTime.format(dateTimeFormatter1);
        String endData = endTime.format(dateTimeFormatter1);
//        开始时间
        jsonObject.put("startTime", startData);
//        jsonObject.put("startTime", "2024-01-10 00:00:00");
//        结束时间
        jsonObject.put("endTime", endData);
//        jsonObject.put("endTime", "2024-01-10 23:59:59");

        jsonObject.put("size", "20");
        jsonObject.put("indexId", "0");
        jsonObject.put("carNo", "");


        String md5Str = "appid=" + parkConfig.getAppId() + "&endTime=" + endData + "&indexId=" + pageindex + "&parkKey=" + parkConfig.getParkKey() + "&rand=" + rand + "&size=" + pagesize + "&startTime=" + startData + "&version=v1.1" + "&" + parkConfig.getAppSecret();
//        String md5Str = "appid=" + parkConfig.getAppId() + "&endTime=" + "2024-01-10 23:59:59" + "&indexId=" + pageindex + "&parkKey=" + parkConfig.getParkKey() + "&rand=" + rand + "&size=" + pagesize + "&startTime=" + "2024-01-10 00:00:00" + "&version=v1.1" + "&" + parkConfig.getAppSecret();
        String sign = CommonUtil.MD5(md5Str);
        //sign签名
        jsonObject.put("sign", sign);

        String s = RequestUtils.httpPost(url, jsonObject.toJSONString());
        JSONObject jsonObject1 = JSONObject.parseObject(s);

        JSONArray dataArray = jsonObject1.getJSONArray("data");

        if (ObjectUtils.isNotEmpty(dataArray) && dataArray.size() > 0) {

            for (int i = 0; i < dataArray.size(); i++) {

                JSONObject data = dataArray.getJSONObject(i);

                if (ObjectUtils.isNotEmpty(data)) {
                    SmartCarAccess smartCarAccess = new SmartCarAccess();

//            索引ID
                    String indexId = data.getString("indexId");
//          车牌号码
                    String carNo = data.getString("carNo");
//            入场时间
                    String enterTime = data.getString("enterTime");
//             入口车道名称
                    String enterGateName = data.getString("enterGateName");

                    smartCarAccess.setIndexId(indexId);
                    smartCarAccess.setType("1");
                    smartCarAccess.setCarNo(carNo);
                    smartCarAccess.setEnterTime(enterTime);
                    smartCarAccess.setEnterGateName(enterGateName);

                    //                    判断是否已经添加
                    LambdaQueryWrapper<SmartCarAccess> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SmartCarAccess::getType, 1)
                            .eq(SmartCarAccess::getIndexId, indexId);
                    List<SmartCarAccess> list = this.list(wrapper);

                    if (ObjectUtils.isEmpty(list) && list.size() <= 0) {
                        this.save(smartCarAccess);
                    }
                }
            }

            page=page+1;
        } else {
            if (page>0) {
                page=page-1;
            }else {
                page=0;
            }
        }
    }


    /**
     * 出场车辆
     *
     * @param pageindex
     * @param pagesize
     * @throws Exception
     */
    public void getOutCar(Integer pageindex, Integer pagesize) throws Exception {

        String url = parkConfig.getUrl() + "Inquire/GetOutCar";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid", parkConfig.getAppId());
        jsonObject.put("parkKey", parkConfig.getParkKey());
        String rand = String.valueOf(Math.random());
        jsonObject.put("rand", rand);
        jsonObject.put("version", "v1.1");

//        时间
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime stateTime = now.withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endTime = now.withHour(23).withMinute(59).withSecond(59);
        String startData = stateTime.format(dateTimeFormatter1);
        String endData = endTime.format(dateTimeFormatter1);
//        开始时间
        jsonObject.put("startTime", startData);
//        data.put("startTime", "2024-01-22 00:00:00");
//        结束时间
        jsonObject.put("endTime", endData);
//        data.put("endTime", "2024-01-22 23:59:59");

        jsonObject.put("size", "20");
        jsonObject.put("indexId", "0");
        jsonObject.put("carNo", "");


        String md5Str = "appid=" + parkConfig.getAppId() + "&endTime=" + endData + "&indexId=" + pageindex + "&parkKey=" + parkConfig.getParkKey() + "&rand=" + rand + "&size=" + pagesize + "&startTime=" + startData + "&version=v1.1" + "&" + parkConfig.getAppSecret();
        String sign = CommonUtil.MD5(md5Str);
        //sign签名
        jsonObject.put("sign", sign);

        String s = RequestUtils.httpPost(url, jsonObject.toJSONString());
        JSONObject jsonObject1 = JSONObject.parseObject(s);

        JSONArray dataArray = jsonObject1.getJSONArray("data");

        if (ObjectUtils.isNotEmpty(dataArray) && dataArray.size() > 0) {

            for (int i = 0; i < dataArray.size(); i++) {

                JSONObject data = dataArray.getJSONObject(i);

                if (ObjectUtils.isNotEmpty(data)) {
                    SmartCarAccess smartCarAccess = new SmartCarAccess();

//            索引ID
                    String indexId = data.getString("indexId");
//          车牌号码
                    String carNo = data.getString("carNo");
//            入场时间
                    String enterTime = data.getString("enterTime");
//             入口车道名称
                    String enterGateName = data.getString("enterGateName");

                    smartCarAccess.setIndexId(indexId);
                    smartCarAccess.setType("2");
                    smartCarAccess.setCarNo(carNo);
                    smartCarAccess.setEnterTime(enterTime);
                    smartCarAccess.setEnterGateName(enterGateName);

                    //                    判断是否已经添加
                    LambdaQueryWrapper<SmartCarAccess> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SmartCarAccess::getType, 2)
                            .eq(SmartCarAccess::getIndexId, indexId);
                    List<SmartCarAccess> list = this.list(wrapper);

                    if (ObjectUtils.isEmpty(list) && list.size() <= 0) {
                        this.save(smartCarAccess);
                    }
                }
            }

            page=page+1;
        } else {
            if (page>0) {
                page=page-1;
            }else {
                page=0;
            }
        }
    }

}
