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.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.model.result.PageUtils;
import com.template.model.vo.SmartAccessVo;
import com.template.model.vo.SmartCarAccessVo;
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;

    @Autowired
    SmartCarAccessMapper smartCarAccessMapper;

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

    @Scheduled(cron = "0 40 * * * ? ")
    @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-06-26 00:00:00");
//        结束时间
        jsonObject.put("endTime", endData);
//        jsonObject.put("endTime", "2024-01-10 23:59:59");

        jsonObject.put("size", pagesize+"");
        jsonObject.put("indexId", pageindex+"");
//        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");
//              图片
                    String enterImgPath = data.getString("enterImgPath");

                    smartCarAccess.setIndexId(indexId);
                    smartCarAccess.setType("1");
                    smartCarAccess.setCarNo(carNo);
                    smartCarAccess.setDataTime(enterTime);
                    smartCarAccess.setCarGateName(enterGateName);
                    smartCarAccess.setImage(enterImgPath);

                    //                    判断是否已经添加
                    LambdaQueryWrapper<SmartCarAccess> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SmartCarAccess::getCarNo,carNo)
                            .eq(SmartCarAccess::getDataTime, enterTime);
                    List<SmartCarAccess> list = this.list(wrapper);

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

//        判断是否还有第二页
        if (dataArray.size()>=pagesize) {
            getEnterCar(pageindex+1, pagesize);
        }


    }


    /**
     * 出场车辆
     *
     * @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);
//        jsonObject.put("startTime", "2024-06-26 00:00:00");
//        结束时间
        jsonObject.put("endTime", endData);
//        data.put("endTime", "2024-01-22 23:59:59");

        jsonObject.put("size", pagesize+"");
        jsonObject.put("indexId",pageindex+"");
//        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 outTime = data.getString("outTime");

//             入口车道名称
                    String enterGateName = data.getString("enterGateName");
//              	出口车道名称
                    String outOperatorName = data.getString("outGateName");

                    //图片
                    String outImgPath = data.getString("outImgPath");



                    smartCarAccess.setIndexId(indexId);
                    smartCarAccess.setType("2");
                    smartCarAccess.setCarNo(carNo);
                    smartCarAccess.setDataTime(outTime);
                    smartCarAccess.setCarGateName(outOperatorName);
                    smartCarAccess.setImage(outImgPath);

                    //                    判断是否已经添加
                    LambdaQueryWrapper<SmartCarAccess> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SmartCarAccess::getCarNo,carNo)
                            .eq(SmartCarAccess::getDataTime,outTime);
                    List<SmartCarAccess> list = this.list(wrapper);

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

                    SmartCarAccess enterCar = new SmartCarAccess();
                    enterCar.setIndexId(indexId);
                    enterCar.setType("1");
                    enterCar.setCarNo(carNo);
                    enterCar.setDataTime(enterTime);
                    enterCar.setCarGateName(enterGateName);


                    //                    判断是否已经添加
                    LambdaQueryWrapper<SmartCarAccess> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(SmartCarAccess::getCarNo,carNo)
                            .eq(SmartCarAccess::getDataTime,enterTime);
                    List<SmartCarAccess> list2 = this.list(wrapper2);

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

                }
            }

        }

        //        判断是否还有第二页
        if (dataArray.size()>=pagesize) {
            getOutCar(pageindex+1, pagesize);
        }

    }


    @Override
    public PageUtils<SmartCarAccessVo> getPage(Integer currentPage, Integer pageCount, String keyWord, String type, String startTime, String endTime) {
        Page<SmartCarAccessVo> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageCount);
        IPage<SmartCarAccessVo> datas = smartCarAccessMapper.getPage(page,keyWord,type,startTime,endTime);
        return new PageUtils(datas);
    }
}
