package com.mortals.xhx.module.hik.event.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.common.Rest;
import com.mortals.framework.util.DataUtil;
import com.mortals.xhx.common.code.HikAbilityEnum;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.module.hik.AbstractHikService;
import com.mortals.xhx.module.hik.HikApiRest;
import com.mortals.xhx.module.hik.event.model.req.callback.*;
import com.mortals.xhx.module.hik.event.model.req.sub.EventSubReq;
import com.mortals.xhx.module.hik.event.model.rsp.EventInfo;
import com.mortals.xhx.module.hik.event.service.IHikEventService;
import com.mortals.xhx.module.person.service.PersonService;
import com.mortals.xhx.module.realtime.service.RealtimeDataflowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 海康人员接口类
 *
 * @author: zxfei
 * @date: 2023/4/12 17:51
 */
@Service("hikEventService")
@Slf4j
public class HikEventServiceImpl extends AbstractHikService implements IHikEventService {

    @Autowired
    private RealtimeDataflowService dataflowService;
    @Autowired
    private PersonService personService;

    @Override
    public Rest<String> subEvent(EventSubReq eventSubReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/eventService/v1/eventSubscriptionByEventTypes";
        path.put(protocol, getCamsApi);
        try {
            log.info("event sub req=>{}", JSON.toJSONString(eventSubReq));
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(eventSubReq), null, null, "application/json");
            log.info("event sub resp=>{}", respJson);
            HikApiRest<String> rest = JSON.parseObject(respJson, new TypeReference<HikApiRest<String>>() {
            });
            if ("0".equals(rest.getCode())) {
                return Rest.ok();
            } else {
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("event sub error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<List<EventInfo>> getEvents() {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/eventService/v1/eventSubscriptionView";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, "{}", null, null, "application/json");
            Rest<List<EventInfo>> rest = JSON.parseObject(respJson, new TypeReference<Rest<List<EventInfo>>>() {
            });
            if (rest.getCode() == 0) {
                return Rest.ok(rest.getData());
            } else {
                log.info("sub event list error resp=>", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("event list error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<String> cancelEvent(EventSubReq eventSubReq) {
        ArtemisConfig config = getArtemisConfig();
        String getCamsApi = ARTEMIS_PATH + "/api/eventService/v1/eventUnSubscriptionByEventTypes";
        path.put(protocol, getCamsApi);
        try {
            String respJson = ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSONString(eventSubReq), null, null, "application/json");
            Rest<String> rest = JSON.parseObject(respJson, new TypeReference<Rest<String>>() {
            });
            if (rest.getCode() == 0) {
                return Rest.ok();
            } else {
                log.info("event cancel error resp=>", respJson);
                return Rest.fail(rest.getMsg());
            }
        } catch (Exception e) {
            log.error("event cancel error异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<String> handleEvent(EventReq req) {
        //处理识别业务 todo
        Double similarity = DataUtil.converStr2Double(GlobalSysInfo.getParamValue(ParamKey.PARAM_FACE_SIMILARITY, "0.8"), 0);
        //String similarity = GlobalSysInfo.getParamValue(ParamKey.PARAM_FACE_SIMILARITY, "0.8");
        Params params = req.getParams();
        if (HikAbilityEnum.人脸识别事件.getValue().equals(params.getAbility())) {
            for (EventsItem event : params.getEvents()) {
                EventTypeAbstract eventTypeAbstract = EventTypeAbstract.newType(event.getEventType());
                eventTypeAbstract.saveEventData(event);

               // assessmentAbstract.initBidData(projectEntity, entity, supplierEntities);

             /*   EventData eventData = event.getData();
                //识别结果
                FaceRecognitionResult faceRecognitionResult = eventData.getFaceRecognitionResult();
                //抓拍信息
                Snap snap = faceRecognitionResult.getSnap();
                if (HikEventTypeEnum.重点人员识别事件.getValue() == event.getEventType()) {
                    //处理重点人员事件
                    //匹配的结果
                    List<FaceMatchItem> faceMatchs = faceRecognitionResult.getFaceMatch();
                    for (FaceMatchItem faceMatch : faceMatchs) {
                        //根据匹配结果 保存业务数据 todo
                        if (faceMatch.getSimilarity() > similarity) {
                            //保存当前识别结果到记录表中
                        }
                    }
                } else if (HikEventTypeEnum.陌生人员识别事件.getValue() == event.getEventType()) {
                    //不论识别结果 保存流量数据
                    RealtimeDataflowEntity realtimeDataflowEntity = new RealtimeDataflowEntity();
                    realtimeDataflowEntity.setDetectTime(event.getHappenTime());
                    String resIndexCodes = eventData.getResInfo().stream().map(i -> i.getIndexCode()).collect(Collectors.joining(","));
                    realtimeDataflowEntity.setDevice(resIndexCodes);
                    realtimeDataflowEntity.setPicUri(eventData.getFaceRecognitionResult().getSnap().getFaceUrl());
                    realtimeDataflowEntity.setEventId(event.getEventId());
                    realtimeDataflowEntity.setEventType(HikEventTypeEnum.陌生人员识别事件.getValue().longValue());
                    realtimeDataflowEntity.setCreateUserId(1L);
                    realtimeDataflowEntity.setCreateTime(new Date());
                    realtimeDataflowEntity.setCreateUserName("system");
                    realtimeDataflowEntity.initAttrValue();

                    dataflowService.save(realtimeDataflowEntity);
                }*/
            }
        }

        return Rest.ok("处理成功！");
    }
}
