package com.usky.eg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.datascope.context.DataScopeContextHolder;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.eg.domain.EgDevice;
import com.usky.eg.domain.EgRecord;
import com.usky.eg.mapper.EgDeviceMapper;
import com.usky.eg.mapper.EgRecordMapper;
import com.usky.eg.service.EgDeviceService;
import com.usky.eg.service.EgRecordService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.eg.service.vo.EgRecordRequestVO;
import net.bytebuddy.dynamic.scaffold.MethodRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 门禁_通行记录表 服务实现类
 * </p>
 *
 * @author zyj
 * @since 2024-11-27
 */
@Service
public class EgRecordServiceImpl extends AbstractCrudService<EgRecordMapper, EgRecord> implements EgRecordService {
    @Autowired
    private EgDeviceService egDeviceService;
    @Autowired
    private EgDeviceMapper egDeviceMapper;

    @Override
    public void add(EgRecord egRecord){
        Integer tenantId;
        
        // 通过deviceUuid查询设备获取tenantId
        LambdaQueryWrapper<EgDevice> queryWrapper = Wrappers.lambdaQuery();
        if(StringUtils.isBlank(egRecord.getDeviceUuid())){
            throw new BusinessException("设备Uuid不能为空");
        }
        queryWrapper.select(EgDevice::getId, EgDevice::getTenantId)
                .eq(EgDevice::getDeviceUuid,egRecord.getDeviceUuid());
        EgDevice one = egDeviceService.getOne(queryWrapper);
        if(one == null){
            throw new BusinessException("设备未注册，请先注册");
        }
        tenantId = one.getTenantId();
        egRecord.setEgDeviceId(one.getId());
        LocalDateTime now = LocalDateTime.now();
        egRecord.setPassTime(now);
        egRecord.setCreateTime(now);
        egRecord.setTenantId(tenantId);
        
        // 安全获取部门ID
        Integer deptId = null;
        if(SecurityUtils.getLoginUser() != null 
                && SecurityUtils.getLoginUser().getSysUser() != null 
                && SecurityUtils.getLoginUser().getSysUser().getDeptId() != null){
            deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId().intValue();
        }
        egRecord.setDeptId(deptId);

        this.save(egRecord);
    }

    @Override
    @DataScope
    public CommonPage<EgRecord> page(EgRecordRequestVO requestVO){
        IPage<EgRecord> page = new Page<>(requestVO.getCurrent(),requestVO.getSize());
        String deviceName = requestVO.getDeviceName();

        List<Integer> egDeviceIdList = new ArrayList<>();
        List<EgDevice> egDeviceList ;
        LambdaQueryWrapper<EgDevice> egDeviceQuery = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank(deviceName)){
            egDeviceQuery.like(EgDevice::getDeviceName,deviceName).eq(EgDevice::getTenantId, SecurityUtils.getTenantId());
            egDeviceList = egDeviceMapper.selectList(egDeviceQuery);
            if(egDeviceList.size() > 0){
                for (int i = 0; i < egDeviceList.size(); i++) {
                    egDeviceIdList.add(egDeviceList.get(i).getId());
                }
            }
        }else{
            egDeviceQuery.eq(EgDevice::getTenantId, SecurityUtils.getTenantId());
            egDeviceList = egDeviceMapper.selectList(egDeviceQuery);
        }

        String dataScopeSql = DataScopeContextHolder.getDataScopeSql();

        LambdaQueryWrapper<EgRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(requestVO.getUserName()),EgRecord::getUserName,requestVO.getUserName())
                .eq(null != requestVO.getPassType(),EgRecord::getPassType,requestVO.getPassType())
                .in(CollectionUtils.isNotEmpty(egDeviceIdList),EgRecord::getEgDeviceId,egDeviceIdList)
                .between(StringUtils.isNotBlank(requestVO.getStartTime())&&StringUtils.isNotBlank(requestVO.getEndTime()),EgRecord::getPassTime,requestVO.getStartTime(),requestVO.getEndTime())
                .apply(Objects.nonNull(dataScopeSql), dataScopeSql)
                .orderByDesc(EgRecord::getId);
        page = this.page(page,queryWrapper);
        if((page.getRecords().size() > 0) && (egDeviceList.size() > 0)){
            for (int i = 0; i < page.getRecords().size(); i++) {
                if(Objects.nonNull(page.getRecords().get(i).getEgDeviceId())){
                    Integer egDeviceId = page.getRecords().get(i).getEgDeviceId();
                    for (int j = 0; j < egDeviceList.size(); j++) {
                        if(egDeviceId.equals(egDeviceList.get(j).getId())){
                            page.getRecords().get(i).setEgDevice(egDeviceList.get(j));
                            break;
                        }
                    }
                }
            }
        }

        return new CommonPage<>(page.getRecords(),page.getTotal(),requestVO.getSize(),requestVO.getCurrent());
    }
}
