package com.xjrsoft.module.hikvision.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
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.utils.WeChatUtil;
import com.xjrsoft.config.HikvisionConfig;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.service.IBaseClassService;
import com.xjrsoft.module.concat.service.IXjrUserService;
import com.xjrsoft.module.hikvision.util.ApiUtil;
import com.xjrsoft.module.hikvision.util.OutInRecordUtil;
import com.xjrsoft.module.organization.dto.WeChatSendMessageDto;
import com.xjrsoft.module.organization.entity.UserStudent;
import com.xjrsoft.module.organization.service.IWeChatService;
import com.xjrsoft.module.student.entity.BaseStudentSchoolRoll;
import com.xjrsoft.module.teacher.entity.XjrUser;
import com.xjrsoft.module.teacher.mapper.FaceImportMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/event")
@Api(value = "/event", tags = "订阅事件接收")
@AllArgsConstructor
@Slf4j
public class EventController {
    private final OutInRecordUtil outInRecordUtil = new OutInRecordUtil();

    private final FaceImportMapper faceImportMapper;
    private final HikvisionConfig hikvisionConfig;
    private final IBaseClassService classService;
    private final IWeChatService weChatService;
    private final IXjrUserService xjrUserService;
    private final WeChatUtil weChatUtil;

    @PostMapping("/receiveCar")
    @ApiOperation(value = "接收车辆事件")
    public ResponseEntity<Void> receiveCarEvent(@RequestBody(required = false) String eventData) {
        log.info("Received event data: {}", eventData);
        new Thread(() -> {
            try {
                outInRecordUtil.GetVehicleRecordTest(faceImportMapper, eventData);
                outInRecordUtil.UpdatePicVehicleRecordTest(eventData);
                outInRecordUtil.UpdateReleaseVehicleRecordTest(eventData);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }).start();

        // 立即返回HTTP 200 OK响应
        return ResponseEntity.ok().build();
    }

    @PostMapping("/receivePeople")
    @ApiOperation(value = "接收人员事件")
    public ResponseEntity<Void> receivePeopleEvent(@RequestBody(required = false) String eventData) {
        log.info("Received event data: {}", eventData);
        new Thread(() -> {
            try {
                JsonObject data = new JsonParser().parse(eventData).getAsJsonObject();
                outInRecordUtil.GetTeacherAndStudentRecordsTest(faceImportMapper, data);

                JsonObject paramsObject = data.getAsJsonObject("params");
                JsonArray eventsArray = paramsObject.getAsJsonArray("events");
                for (JsonElement eventElement : eventsArray) {
                    JsonObject eventObject = eventElement.getAsJsonObject();
                    JsonObject dataObject = eventObject.getAsJsonObject("data");

                    String idNum = null;
                    if (dataObject.has("ExtEventPersonNo")) {
                        idNum = dataObject.get("ExtEventPersonNo").getAsString();
                    }
                    String happenTime = eventObject.get("happenTime").getAsString();
                    String recordTimeStr = outInRecordUtil.ChangeTime(happenTime);
                    int status = eventObject.get("status").getAsInt();
                    if (idNum == null) continue;
                    if (!Objects.equals(faceImportMapper.IsStudentTypeByPersonId(Long.valueOf(idNum)), "学生")) {
                        continue;
                    }

                    List<XjrUser> userList = xjrUserService.list(
                        new MPJLambdaWrapper<XjrUser>()
                                .select(XjrUser::getId)
                        .leftJoin(UserStudent.class, UserStudent::getUserId, XjrUser::getId)
                        .eq(UserStudent::getStudentId, idNum)
                    );

                    for (XjrUser member : userList) {
                        XjrUser student = xjrUserService.getById(idNum);
                        BaseClass baseClass = classService.getOne(
                            new MPJLambdaWrapper<BaseClass>()
                            .leftJoin(BaseStudentSchoolRoll.class, BaseStudentSchoolRoll::getClassId, BaseClass::getId)
                            .eq(BaseStudentSchoolRoll::getUserId, student.getId())
                        );

                        WeChatSendMessageDto weChatSendMessageDto = new WeChatSendMessageDto();
                        weChatSendMessageDto.setUserId(member.getOpenId());
                        weChatSendMessageDto.setTemplateId(weChatUtil.getOutInTemplate());
                        weChatSendMessageDto.setMsgId(IdUtil.getSnowflakeNextId() + "");
                        JSONObject paramJson = new JSONObject();

                        JSONObject thing1 = new JSONObject();
                        thing1.put("value", student.getName());
                        paramJson.put("thing1", thing1);

                        JSONObject time3 = new JSONObject();
                        time3.put("value", recordTimeStr);
                        paramJson.put("time3", time3);

                        JSONObject thing2 = new JSONObject();
                        thing2.put("value", baseClass.getName());
                        paramJson.put("thing2", thing2);

                        JSONObject const4 = new JSONObject();
                        if(status == 1){
                            const4.put("value", "进校");
                        }else{
                            const4.put("value", "出校");
                        }

                        paramJson.put("const4", const4);

                        weChatSendMessageDto.setContent(paramJson);
                        weChatService.sendTemplateMessage(weChatSendMessageDto);
                    }
                }
            } catch (ParseException e) {
                log.error("Error processing event data", e);
            }
        }).start();

        return ResponseEntity.ok().build();
    }

    @PostMapping("/visit")
    @ApiOperation(value = "接收访客事件")
    public ResponseEntity<Void> receiveVisitEvent(@RequestBody(required = false) String eventData) {
        log.info("Received event data: {}", eventData);
        new Thread(() -> {
            try {
                outInRecordUtil.GetVisitRecordsTest(faceImportMapper, eventData);
            } catch (ParseException e) {
                log.error("Error processing event data", e);
            }
        }).start();

        // 立即返回HTTP 200 OK响应
        return ResponseEntity.ok().build();
    }

    @PostMapping("/subscribe")
    @ApiOperation(value = "订阅事件")
    public RT<Boolean> subscribeEvent() {
        ApiUtil apiUtil = new ApiUtil();
        JsonArray eventList = new JsonArray();
        String apiPath = "/api/eventService/v1/eventSubscriptionByEventTypes";
        JsonObject paramJson = new JsonObject();
//*******手动更改****************************************************
//        eventList.add(196893); //人脸匹配成功
//        eventList.add(197151); //人脸匹配失败
//        eventList.add(771760130); //车辆入场压线事件
//        eventList.add(771760133); //车辆出场压线事件
        eventList.add(1392513025); //访客登记
        eventList.add(1392513026); //访客签离
        paramJson.addProperty("eventDest", hikvisionConfig.getVisitUrl()); //要修改第二个参数
//******************************************************************
        paramJson.add("eventTypes", eventList);

        String response = apiUtil.doPost(apiPath, paramJson.toString(), null);
        log.info("Subscribe response: {}", response);
        return RT.ok(true);
    }

    @PostMapping("/query")
    @ApiOperation(value = "查询已订阅事件")
    public String queryEvent() {
        ApiUtil apiUtil = new ApiUtil();
        String apiPath = "/api/eventService/v1/eventSubscriptionView";
        String response = apiUtil.doPost(apiPath, null, null);
        System.out.println("output: " + response);
//        Gson gson = new GsonBuilder().setPrettyPrinting().create();
//
//        JsonElement jsonElement = JsonParser.parseString(response);
//
//        String prettyJson = gson.toJson(jsonElement);

        return response;
    }

    @PostMapping("/cancel")
    @ApiOperation(value = "取消已订阅事件")
    public String cancelEvent() {
        ApiUtil apiUtil = new ApiUtil();
        JsonArray eventList = new JsonArray();
//*******手动更改****************************************************
        eventList.add(196893);
//        eventList.add(197151);
        eventList.add(1392513025); //访客登记
        eventList.add(1392513026); //访客签离
//        eventList.add(771760130);
//        eventList.add(771760133);
//******************************************************************
        JsonObject paramJson = new JsonObject();
        paramJson.add("eventTypes", eventList);
        String apiPath = "/api/eventService/v1/eventUnSubscriptionByEventTypes";
        String response = apiUtil.doPost(apiPath, paramJson.toString(), null);
        System.out.println("output: " + response);

        return response;
    }
}
