package com.zhongshu.card.server.core.service.openAPI.device;

import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.client.model.base.IDParam;
import com.zhongshu.card.client.model.devices.DeviceUseRecordModel;
import com.zhongshu.card.client.model.devices.DeviceUseRecordSearch;
import com.zhongshu.card.client.openApi.model.device.DeviceUseRecordOpenApiSearch;
import com.zhongshu.card.server.core.dao.devices.DeviceUseRecordDao;
import com.zhongshu.card.server.core.domain.devices.DeviceUseRecords;
import com.zhongshu.card.server.core.service.base.CommonService;
import com.zhongshu.card.server.core.service.devices.DeviceUseRecordService;
import com.zhongshu.card.server.core.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * 设备使用记录的 openAPI
 * @author TRX
 * @date 2025/3/10
 */
@Slf4j
@Service
public class DeviceUseRecordOpenApiService {

    @Autowired
    private DeviceUseRecordDao deviceUseRecordDao;

    @Autowired
    private DeviceUseRecordService deviceUseRecordService;

    @Autowired
    private CommonService commonService;

    /**
     * 设备使用记录分页
     * @param param
     * @return
     */
    public ResultContent<Page<DeviceUseRecordModel>> page(DeviceUseRecordOpenApiSearch param) {
        if (ObjectUtils.isEmpty(param.getUserId())) {
            return ResultContent.buildFail("userId不能为空");
        }
        ResultContent<String> resultContent = commonService.checkProjectCanUserByCode(param.getProjectCode());
        if (resultContent.isFailed()) {
            return ResultContent.buildFail(resultContent.getMsg());
        }
        String projectOid = resultContent.getContent();
        DeviceUseRecordSearch search = new DeviceUseRecordSearch();
        BeanUtils.copyProperties(param, search);
        search.setProjectOid(projectOid);

        Pageable pageable = PageRequest.of(param.getNumber(), param.getSize());
        Page<DeviceUseRecords> page = deviceUseRecordDao.page(pageable, search);

        return ResultContent.buildSuccess(PageEntityUtil.concurrent2PageModel(page, deviceUseRecordService::toModel));
    }

    public ResultContent<DeviceUseRecordModel> detailById(IDParam param) {
        DeviceUseRecords entity = deviceUseRecordDao.findTopById(param.getId());
        if (ObjectUtils.isEmpty(entity)) {
            return ResultContent.buildFail(String.format("数据不存在"));
        }
        return ResultContent.buildSuccess(deviceUseRecordService.toModel(entity));
    }

}
