package com.xjrsoft.module.hikvision.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.module.hikvision.dto.HikvisionCarOutinPageDto;
import com.xjrsoft.module.hikvision.dto.HikvisionOutinPageDto;
import com.xjrsoft.module.hikvision.service.IHikvisionDataService;
import com.xjrsoft.module.hikvision.util.ApiUtil;
import com.xjrsoft.module.hikvision.vo.HikvisionCarListVo;
import com.xjrsoft.module.hikvision.vo.HikvisionCarOutinPageVo;
import com.xjrsoft.module.hikvision.vo.HikvisionOutinPageVo;
import com.xjrsoft.module.personnel.entity.CarMessageApply;
import com.xjrsoft.module.personnel.service.ICarMessageApplyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/hikvision/outin")
@Api(value = "/hikvision/outin", tags = "海康出入记录")
@AllArgsConstructor
@Slf4j
public class OutInController {

    private final IHikvisionDataService hkvisionDataService;
    private final ICarMessageApplyService carApplyService;

    @GetMapping("/page")
    @ApiOperation(value="海康记录查询(分页)")
    @SaCheckPermission("outin:detail")
    public RT<PageOutput<HikvisionOutinPageVo>> page(@Valid HikvisionOutinPageDto dto){
        ApiUtil apiUtil = new ApiUtil();
        String apiPath = "/api/acs/v2/door/events";

        JsonObject paramJson = new JsonObject();
        JsonArray eventList = new JsonArray();
        eventList.add(196893); // 只获取人脸通过的
        paramJson.addProperty("pageNo", dto.getLimit());
        paramJson.addProperty("pageSize", dto.getSize());
        paramJson.add("eventTypes", eventList);
        String hikvisionId = hkvisionDataService.getHikvisionIdBySourceId(dto.getUserId().toString());

        JsonArray personIds = new JsonArray();
        personIds.add(hikvisionId);
        paramJson.add("personIds", personIds);
        paramJson.addProperty("sort", "eventTime");
        paramJson.addProperty("order", "desc");

        String doPost = apiUtil.doPost(apiPath, paramJson.toString(), null);
        JsonParser parser = new JsonParser();
        JsonObject data = parser.parse(doPost).getAsJsonObject().get("data").getAsJsonObject();
        JsonArray list = data.get("list").getAsJsonArray();
        List<HikvisionOutinPageVo> result = new ArrayList<>();
        Gson gson = new Gson();
        for (JsonElement jsonElement : list) {
            result.add(gson.fromJson(jsonElement.getAsJsonObject(), HikvisionOutinPageVo.class));
        }

        PageOutput<HikvisionOutinPageVo> output = new PageOutput<>();
        output.setCurrentPage(dto.getLimit());
        output.setPageSize(dto.getSize());
        output.setTotalPage(data.get("totalPage").getAsInt());
        output.setTotal(data.get("total").getAsInt());
        output.setList(result);

        return RT.ok(output);
    }

    @GetMapping("/car-list")
    @ApiOperation(value="根据用户id查询车牌号")
    @SaCheckPermission("outin:detail")
    public RT<List<HikvisionCarListVo>> carList(@Valid HikvisionCarOutinPageDto dto){
        if(dto.getUserId() == null){
            dto.setUserId(StpUtil.getLoginIdAsLong());
        }
        List<CarMessageApply> list = carApplyService.list(new QueryWrapper<CarMessageApply>().lambda().eq(CarMessageApply::getUserId, dto.getUserId()));
        List<HikvisionCarListVo> result = new ArrayList<>();
        for (CarMessageApply el : list) {
            result.add(
                    new HikvisionCarListVo(){{
                        setPlateNo(el.getCarNumber());
                    }}
            );
        }
        return RT.ok(result);
    }


    @GetMapping("/car-page")
    @ApiOperation(value="海康车辆出入记录查询(分页)")
    @SaCheckPermission("outin:detail")
    public RT<PageOutput<HikvisionCarOutinPageVo>> carPage(@Valid HikvisionCarOutinPageDto dto){
        ApiUtil apiUtil = new ApiUtil();
        String apiPath = "/api/pms/v1/crossRecords/page";

        JsonObject paramJson = new JsonObject();
        paramJson.addProperty("pageNo", dto.getLimit());
        paramJson.addProperty("pageSize", dto.getSize());
        paramJson.addProperty("sort", "crossTime");
        paramJson.addProperty("order", "desc");
        paramJson.addProperty("plateNo", dto.getPlateNo());

        String doPost = apiUtil.doPost(apiPath, paramJson.toString(), null);
        JsonParser parser = new JsonParser();
        JsonObject data = parser.parse(doPost).getAsJsonObject().get("data").getAsJsonObject();
        JsonArray list = data.get("list").getAsJsonArray();
        List<HikvisionCarOutinPageVo> result = new ArrayList<>();
        Gson gson = new Gson();
        for (JsonElement jsonElement : list) {
            result.add(gson.fromJson(jsonElement.getAsJsonObject(), HikvisionCarOutinPageVo.class));
        }

        PageOutput<HikvisionCarOutinPageVo> output = new PageOutput<>();
        output.setCurrentPage(dto.getLimit());
        output.setPageSize(dto.getSize());
//        output.setTotalPage(data.get("totalPage").getAsInt());
        output.setTotal(data.get("total").getAsInt());
        output.setList(result);

        return RT.ok(output);
    }
}
