package com.ruoyi.web.controller.parkLot;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;

import com.ruoyi.common.utils.StringUtils;

import com.ruoyi.system.domain.vo.TempCarInRecordVo;
import org.joda.time.DateTime;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Date;

import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.constant.CacheConstants.LEFT_PLACE;

/**
 * 参数配置 信息操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/parkLot")
public class ParkLotController extends BaseController {
    @Autowired
    private RedisCache redisCache;

    /**
     * 提供给皖事通剩余地面车位数量
     */
    @PostMapping("/parkLotNum")
    public String parkLotNum() {
        //先去查redis
        String leftPlaceRedis = redisCache.getCacheObject(LEFT_PLACE);
        if (StringUtils.isEmpty(leftPlaceRedis)) {
            leftPlaceRedis = "0";
            String result = GetCameraPreviewURL.GetCameraPreviewURL();
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");
            if ("0".equals(code)) {
                JSONArray data = jsonObject.getJSONArray("data");
                leftPlaceRedis = data.getJSONObject(0).getString("leftPlace");
                System.out.println(leftPlaceRedis);
            } else {
                System.out.println(jsonObject.getString("msg"));
            }
            redisCache.setCacheObject(LEFT_PLACE, leftPlaceRedis, 1, TimeUnit.MINUTES);
        }
        return leftPlaceRedis;
    }

    /**
     * 获取实时地面停车场场内车数据
     *
     * @return
     */
    @PostMapping("/tempCarInRecords")
    public TableDataInfo tempCarInRecords(TempCarInRecordVo tempCarInRecordVo) {
        //所有固定车车牌
        ArrayList chargeList = chargeList(tempCarInRecordVo.getPlateNo());
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        String startTime = tempCarInRecordVo.getStartTime();
        String endTime = tempCarInRecordVo.getEndTime();
        if (StringUtils.isNotBlank(startTime)){
            DateTime parseStartTime = DateTime.parse(startTime, formatter);
            startTime = parseStartTime.toString("yyyy-MM-dd'T'HH:mm:ss") + "+08:00";
        }
        if (StringUtils.isNotBlank(endTime)){
            DateTime parseEndTime = DateTime.parse(endTime, formatter);
            endTime = parseEndTime.toString("yyyy-MM-dd'T'HH:mm:ss") + "+08:00";
        }
        //获取所有在场车辆
        String result = GetCameraPreviewURL.GetTempCarInRecordsURL(tempCarInRecordVo.getPlateNo(), startTime, endTime, tempCarInRecordVo.getPageNo(), tempCarInRecordVo.getPageSize());
        /**
         * {
         *     "code": "0",
         *     "msg": "success",
         *     "data": {
         *         "total": 1,
         *         "pageNo": 1,
         *         "pageSize": 15,
         *         "list": [
         *             {
         *                 "inRecordSyscode": "h45h45h45ghhn45tg245g45r",
         *                 "vehiclePicUri": "/pic?=d7ei703i10cd*73a-d5108a--22c6592ai2b4*=3d4id=",
         *                 "cardNo": "613453453",
         *                 "inTime": "2018-07-26T15:00:00+08:00",
         *                 "parkTime": "1天1小时1分钟",
         *                 "parkSyscode": "hju56jyt54h4h245g2345g345fg",
         *                 "parkName": "停车库1",
         *                 "plateNoPicUri": "/pic?=d7ei703i10cd*73a-d5108a--22c592ai2b4*=3",
         *                 "aswSyscode": "g45ghertg34fh4hy245tgy234tg5",
         *                 "plateNo": "浙A12345"
         *             }
         *         ]
         *     }
         * }
         */
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        //定义返回值
        ArrayList tempCarInRecordList = new ArrayList<>();
        if ("0".equals(code)) {
            String data = jsonObject.getString("data");
            JSONObject jsonObjectData = JSONObject.parseObject(data);
            JSONArray list = jsonObjectData.getJSONArray("list");
            if (list != null && list.size() > 0){
                for (int i = 0; i < list.size(); i++) {
                    JSONObject jsonObjectTempCarInRecord = list.getJSONObject(i);
                    String plateNoTempCarInRecord = jsonObjectTempCarInRecord.getString("plateNo");
                    boolean contains = chargeList.contains(plateNoTempCarInRecord);
                    if (contains){
                        TempCarInRecordVo tempCarInRecord = new TempCarInRecordVo();
                        tempCarInRecord.setPlateNo(plateNoTempCarInRecord);
                        tempCarInRecord.setParkTime(jsonObjectTempCarInRecord.getString("parkTime"));
                        tempCarInRecord.setInTime(zDate(jsonObjectTempCarInRecord.getString("inTime")));
                        tempCarInRecordList.add(tempCarInRecord);
                    }
                }
            }
        }
        return getDataTable(tempCarInRecordList);
    }

    /**
     * 所有固定车车牌
     *
     * @return
     */
    public ArrayList chargeList(String plateNo) {
        DateTime dt = new DateTime();
        String timestamp = dt.toString("yyyy-MM-dd'T'HH:mm:ss") + "+08:00";
        /**
         * {
         *     "code": "0",
         *     "msg": "success",
         *     "data": {
         *         "total": 1,
         *         "pageNo": 1,
         *         "pageSize": 15,
         *         "list": [
         *             {
         *                 "regionIndexCode": "s7f0wef9-weuf0we0f",
         *                 "vehicleId": "as78da790sd99u29u9129uddav90s",
         *                 "plateNo": "浙A12345",
         *                 "cardNo": "6518959562033",
         *                 "personId": "as9du12d9219d1-2ud012d22d",
         *                 "personName": "Jack",
         *                 "categoryCode": "0ff8231a93604c4d849dad519451fb03",
         *                 "categoryName": "VIP车辆"
         *                 "validity": [
         *                     {
         *                         "parkSyscode": "gqwerg354g345g35g",
         *                         "parkName": "停车库1",
         *                         "functionTime": [
         *                             {
         *                                 "startTime": "2018-07-26",
         *                                 "endTime": "2018-07-27"
         *                             }
         *                         ]
         *                     }
         *                 ]
         *             }
         *         ]
         *     }
         * }
         */
        //固定车车牌集合
        ArrayList plateNoList = new ArrayList();
        boolean totalCharge = true;
        int pageNoCharge = 0;
        while (totalCharge) {
            totalCharge = false;
            pageNoCharge = 1 + pageNoCharge;
            //查询出所有未过期的固定车
            String resultCharge = GetCameraPreviewURL.GetChargeURL(plateNo, "2018-07-26T15:00:00+08:00", timestamp, String.valueOf(pageNoCharge), "1000");
            JSONObject jsonObjectCharge = JSONObject.parseObject(resultCharge);
            String codeCharge = jsonObjectCharge.getString("code");
            if ("0".equals(codeCharge)) {
                String dataCharge = jsonObjectCharge.getString("data");
                JSONObject jsonObjectDataCharge = JSONObject.parseObject(dataCharge);
                JSONArray listCharge = jsonObjectDataCharge.getJSONArray("list");
                if (listCharge != null && listCharge.size() > 0) {
                    for (int i = 0; i < listCharge.size(); i++) {
                        JSONObject jsonObjectList = listCharge.getJSONObject(i);
                        //固定车车牌
                        String plateNoCharge = jsonObjectList.getString("plateNo");
                        plateNoList.add(plateNoCharge);
                    }
                    if (listCharge.size() == 1000) {
                        totalCharge = true;
                    }
                }
            }
        }
        return plateNoList;
    }

    /**
     * ISO8601转data
     *
     * @param tDate
     * @return
     */
    public static String zDate(String tDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date date2 = null;
        try {
            date2 = format.parse(tDate);
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date2);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
