package com.zt.plat.module.qms.resource.device.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceUseRecordDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.qms.resource.device.dal.mapper.DeviceUseRecordMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.pojo.CommonResult.success;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DEVICE_USE_RECORD_NOT_EXISTS;

/**
 * 设备-使用记录 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
public class DeviceUseRecordServiceImpl implements DeviceUseRecordService {

    @Resource private DeviceInfomationService deviceInfomationService;
    @Resource private DeviceProductService deviceProductService;
    @Resource private DeviceUseRecordMapper deviceUseRecordMapper;
    @Resource private DeviceUseRecordDetailService deviceUseRecordDetailService;

    @Override
    public PageResult<DeviceInfomationUseRecordVO> queryPageListWithCount(DeviceUseRecordPageReqVO reqVO) {
        Long productId = reqVO.getProductId();
        if(productId != null){
            List<Long> productIds = deviceProductService.getIdListByIdPath(productId);
            List<Long> deviceIds = deviceInfomationService.getIdListByProductIdList(productIds);
            if(!deviceIds.isEmpty()){
                reqVO.setProductId(null);
                reqVO.setDeviceIdList(deviceIds);
            }
        }
        Page<DeviceInfomationUseRecordVO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
        IPage<DeviceInfomationUseRecordVO> pageList = deviceUseRecordMapper.queryPageListWithCount(page, reqVO);
        return new PageResult<>(pageList.getRecords(), pageList.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<DeviceUseRecordRespVO> createDeviceUseRecord(DeviceUseRecordSaveReqVO reqVO) {
        Long deviceId = reqVO.getDeviceId();
        if(ObjectUtils.isEmpty(reqVO.getUserName())){
            //当前登录人
            LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
            //当前登录用户昵称
            String nickName = SecurityFrameworkUtils.getLoginUserNickname();
            reqVO.setUserName(nickName);
            reqVO.setUserId(loginUser.getId());
        }
        DeviceUseRecordDO deviceUseRecord = BeanUtils.toBean(reqVO, DeviceUseRecordDO.class);
        deviceUseRecordMapper.insert(deviceUseRecord);
        if(reqVO.getUseTimeEnd() == null)
            deviceInfomationService.updateDeviceInUseFlag(deviceId, 1);
        else
            deviceInfomationService.updateDeviceInUseFlag(deviceId, 0);
        deviceUseRecordDetailService.saveList(deviceUseRecord.getId(), reqVO.getDetailList());
        // 返回
        DeviceUseRecordRespVO respVO = BeanUtils.toBean(deviceUseRecord, DeviceUseRecordRespVO.class);
        return success(respVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceUseRecord(DeviceUseRecordSaveReqVO reqVO) {
        // 校验存在
        validateDeviceUseRecordExists(reqVO.getId());
        Long deviceId = reqVO.getDeviceId();
        if(reqVO.getUseTimeEnd() == null)
            deviceInfomationService.updateDeviceInUseFlag(deviceId, 1);
        else
            deviceInfomationService.updateDeviceInUseFlag(deviceId, 0);
        deviceUseRecordDetailService.saveList(reqVO.getId(), reqVO.getDetailList());
        // 更新
        DeviceUseRecordDO updateObj = BeanUtils.toBean(reqVO, DeviceUseRecordDO.class);
        deviceUseRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceUseRecord(Long id) {
        // 校验存在
        validateDeviceUseRecordExists(id);
        // 删除
        deviceUseRecordMapper.deleteById(id);
    }

    @Override
        public void deleteDeviceUseRecordListByIds(List<Long> ids) {
        // 校验存在
        validateDeviceUseRecordExists(ids);
        // 删除
        deviceUseRecordMapper.deleteByIds(ids);
        }

    private void validateDeviceUseRecordExists(List<Long> ids) {
        List<DeviceUseRecordDO> list = deviceUseRecordMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_USE_RECORD_NOT_EXISTS);
        }
    }

    private void validateDeviceUseRecordExists(Long id) {
        if (deviceUseRecordMapper.selectById(id) == null) {
            throw exception(DEVICE_USE_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public DeviceUseRecordDO getDeviceUseRecord(Long id) {
        return deviceUseRecordMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceUseRecordDO> getDeviceUseRecordPage(DeviceUseRecordPageReqVO pageReqVO) {
        return deviceUseRecordMapper.selectPage(pageReqVO);
    }

}