package com.jpsoft.shinestar.modules.mq.listener;

import com.alibaba.fastjson.JSONObject;
import com.jpsoft.shinestar.modules.base.entity.DeviceInfo;
import com.jpsoft.shinestar.modules.base.service.DeviceInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.pacs.dto.PacsResult;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import com.jpsoft.shinestar.modules.sys.entity.SysLog;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 动态创建队列后订阅事件
 */
@Slf4j
@Component
public class DeviceMessageListener {
    @Autowired
    private IGuardService guardService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private SysLogService sysLogService;

//    @Autowired
//    Semaphore downloadSemaphore;

    public void handleMessage(JSONObject jsonObject){
        Long personId = jsonObject.getLong("personId");
        String deviceId = jsonObject.getString("deviceId");

        log.warn("照片同步:" + personId + "->" + deviceId);

        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());

        try {
            sysLog.setPointcut("同步照片到单个设备");
            sysLog.setUserId(String.valueOf(personId));
            sysLog.setData(deviceId);

            DeviceInfo deviceInfo = deviceInfoService.get(deviceId);

            if (deviceInfo==null){
                throw new Exception(deviceId + "设备不存在!");
            }

            PacsResult msgResult = guardService.addPersonToDevice(personId, deviceId);

            StringBuilder sb = new StringBuilder();

            boolean success = msgResult.isSuccess();

            if (success) {
                sb.append(deviceInfo.getAliasName() + "同步人脸信息成功!");
            } else {
                sb.append(deviceInfo.getAliasName() + "同步人脸信息失败!" + msgResult.getMsg());
            }

            sysLog.setRemark(sb.toString());
        }
        catch (Exception ex){
            log.error(ex.getMessage());
            sysLog.setRemark("同步失败!" + ex.getMessage());
        }

        try {
//            downloadSemaphore.release();
            sysLogService.insert(sysLog);
        }
        catch (Exception ex){
            log.error(ex.getMessage());
        }
    }
}
