package com.zhongshu.card.server.core.service.permissVerify;

import com.github.microservice.models.gateDoor.use.DeviceUseParam;
import com.github.microservice.net.ResultContent;
import com.github.microservice.types.user.DevicePermissFromType;
import com.zhongshu.card.client.model.devices.permiss.Device2UseUsableSearch;
import com.zhongshu.card.server.core.dao.devices.Device2UseUsableDao;
import com.zhongshu.card.server.core.dao.visitor.VisitorSettingDeviceDao;
import com.zhongshu.card.server.core.domain.devices.permiss.Device2UseUsable;
import com.zhongshu.card.server.core.domain.visitor.VisitorMain;
import com.zhongshu.card.server.core.domain.visitor.VisitorSettingDevice;
import com.zhongshu.card.server.core.service.visitor.VisitorMainService;
import com.zhongshu.card.server.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TRX
 * @date 2025/2/11
 */
@Slf4j
@Service
public class Device2UseUsableService {

    @Autowired
    private Device2UseUsableDao device2UseUsableDao;

    @Autowired
    private VisitorSettingDeviceDao visitorSettingDeviceDao;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 更加访客申请信息 写入对应的设备 临时权限
     *
     * @param visitorMain
     * @return
     */
    public ResultContent addByVisitorData(VisitorMain visitorMain, boolean isDayLastTime) {
        if (ObjectUtils.isEmpty(visitorMain)) {
            return ResultContent.buildFail("访客数据为空");
        }
        String fromDataId = visitorMain.getId();
        Device2UseUsable entity = device2UseUsableDao.findToByFromDataId(fromDataId);
        if (ObjectUtils.isEmpty(entity)) {
            entity = new Device2UseUsable();
            entity.setFromDataId(visitorMain.getId());
            entity.setServiceBeanName(CommonUtil.getCollectionName(VisitorMainService.class));
            entity.setTempType(DevicePermissFromType.Visitor);

            List<String> useDataIds = new ArrayList<>();
            useDataIds.add(visitorMain.getTempUserId());
            if (StringUtils.isNotEmpty(visitorMain.getApplyUserId())) {
                useDataIds.add(visitorMain.getApplyUserId());
            }

            entity.setUseDataIds(useDataIds);
            entity.setStartTime(visitorMain.getPerStartTime());

            List<String> deviceIds = visitorMain.getDeviceIds();
            if (ObjectUtils.isEmpty(deviceIds)) {
                // 查询访客组件上配置的所有的设备
                List<VisitorSettingDevice> list = visitorSettingDeviceDao.findBySceneComponentId(visitorMain.getSceneComponentId());
                if (ObjectUtils.isNotEmpty(list)) {
                    deviceIds = list.stream().map(VisitorSettingDevice::getDeviceId).collect(Collectors.toList());
                }
            }
            entity.setDeviceIds(deviceIds);
            entity.setProjectOid(visitorMain.getProjectOid());
            entity.setOid(visitorMain.getOid());
        }
        Long endTime = visitorMain.getEndTime();
        if (isDayLastTime) {
            endTime = visitorMain.getPerEndTime();
        }
        entity.setEndTime(endTime);
        entity.setTtl(new Date(endTime));
        device2UseUsableDao.save(entity);
        return ResultContent.buildSuccess();
    }

    /**
     * 验证失败 临时权限
     *
     * @param userId   用户id或临时用户id
     * @param deviceId 设备id
     * @return
     */
    public ResultContent<String> verifyDevice(String userId, String deviceId, String projectOid, DeviceUseParam deviceUserParam) {
        String msg = "失败";

        Device2UseUsableSearch param = new Device2UseUsableSearch();
        param.setUseDataIds(List.of(userId));
        param.setProjectOid(projectOid);
        param.setDeviceIds(List.of(deviceId));
        param.setCurrentTime(System.currentTimeMillis());
        Pageable pageable = PageRequest.of(0, 1);
        Page<Device2UseUsable> page = device2UseUsableDao.page(pageable, param);
        List<Device2UseUsable> list = page.getContent();

        if (ObjectUtils.isNotEmpty(list)) {
            msg = "成功";
            for (Device2UseUsable device2UseUsable : list) {
                String serviceBeanName = device2UseUsable.getServiceBeanName();
                deviceUserParam.setServiceBeanName(serviceBeanName);
                if (StringUtils.isEmpty(serviceBeanName)) {
                    log.error("serviceBeanName is null {}", device2UseUsable.getTempType());
                    continue;
                }
                Object object = applicationContext.getBean(device2UseUsable.getServiceBeanName());
                if (ObjectUtils.isEmpty(object)) {
                    log.error("serviceBeanName is not found {}", serviceBeanName);
                    continue;
                }
                SuperPermissService service = (SuperPermissService) object;
                service.markUse(device2UseUsable.getFromDataId(), deviceUserParam);
            }
            return ResultContent.buildSuccess(msg);
        }
        return ResultContent.buildFail(msg);
    }

}
