package com.fuyuanshen.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import com.fuyuanshen.app.domain.AppDeviceShare;
import com.fuyuanshen.app.domain.AppPersonnelInfoRecords;
import com.fuyuanshen.app.mapper.AppDeviceBindRecordMapper;
import com.fuyuanshen.app.mapper.AppDeviceShareMapper;
import com.fuyuanshen.app.mapper.AppPersonnelInfoRecordsMapper;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceAlarm;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.domain.DeviceLog;
import com.fuyuanshen.equipment.domain.vo.DeviceAlarmVo;
import com.fuyuanshen.equipment.domain.vo.WebDeviceVo;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.mapper.DeviceAlarmMapper;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.web.service.WEBDeviceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Author: WY
 * @Date: 2025/5/16
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class WEBDeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements WEBDeviceService {

    private final DeviceAssignmentsMapper deviceAssignmentsMapper;

    private final AppDeviceBindRecordMapper appDeviceBindRecordMapper;
    private final AppPersonnelInfoRecordsMapper infoRecordsMapper;
    private final DeviceLogMapper deviceLogMapper;
    private final DeviceAlarmMapper deviceAlarmMapper;

    private final DeviceMapper deviceMapper;
    private final AppDeviceShareMapper appDeviceShareMapper;


    /**
     * WEB端解绑设备
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int webUnBindDevice(Long id, Long userId) {
        // 设备端解绑 0:设备端解绑 1:web端解绑
        int type = 1;
        if (userId == null) {
            DeviceAssignments deviceAssignments = deviceAssignmentsMapper.selectById(id);
            if (deviceAssignments == null) {
                throw new RuntimeException("请先将设备入库！！！");
            }
            id = deviceAssignments.getDeviceId();
            type = 0;
        }

        QueryWrapper<AppDeviceBindRecord> deviceId = new QueryWrapper<AppDeviceBindRecord>().eq("device_id", id);

        // appDeviceService.unBindDevice(id, userId, type);
        UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
        deviceUpdateWrapper.eq("id", id)
                .set("binding_user_id", null)
                .set("binding_status", BindingStatusEnum.UNBOUND.getCode())
                .set("binding_time", null);
        deviceMapper.update(null, deviceUpdateWrapper);

        return appDeviceBindRecordMapper.delete(deviceId);
    }


    /**
     * WEB端设备详情
     *
     * @param id
     * @return
     */
    @Override
    public WebDeviceVo getDevice(Long id) {
        Device device = deviceMapper.selectById(id);
        if (device != null) {
            WebDeviceVo webDeviceVo = new WebDeviceVo();
            BeanUtil.copyProperties(device, webDeviceVo);
            // 查询分享用户数
            Long count = appDeviceShareMapper.selectCount(new QueryWrapper<AppDeviceShare>().eq("device_id", id));
            webDeviceVo.setShareUsersNumber(Math.toIntExact(count));
            return webDeviceVo;
        }
        return null;
    }


    /**
     * 设备用户详情
     *
     * @param id
     * @return
     */
    @Override
    public List<AppPersonnelInfoRecords> getDeviceUser(Long id) {
        List<AppPersonnelInfoRecords> appPersonnelInfoRecords = infoRecordsMapper.selectList(
                new QueryWrapper<AppPersonnelInfoRecords>().eq("device_id", id)
                        .orderByDesc("create_time"));
        return appPersonnelInfoRecords;
    }


    /**
     * 设备操作记录
     *
     * @param deviceId
     * @return
     */
    @Override
    public TableDataInfo<DeviceLog> getOperationRecord(Long deviceId, String startTime, String endTime, PageQuery pageQuery) {
        Page<DeviceLog> page = pageQuery.build();
        QueryWrapper<DeviceLog> queryWrapper = new QueryWrapper<DeviceLog>().eq("device_id", deviceId);

        if (StrUtil.isNotEmpty(startTime)) {
            queryWrapper.ge("create_time", startTime);
        }
        if (StrUtil.isNotEmpty(endTime)) {
            queryWrapper.le("create_time", endTime);
        }
        queryWrapper.orderByDesc("create_time");
        IPage<DeviceLog> logList = deviceLogMapper.selectPage(page, queryWrapper);
        return TableDataInfo.build(logList);
    }


    /**
     * 设备告警记录
     *
     * @param deviceId
     * @return
     */
    @Override
    public TableDataInfo getAlarmRecord(Long deviceId, String startTime, String endTime, PageQuery pageQuery) {
        Page<DeviceAlarm> page = pageQuery.build();
        QueryWrapper<DeviceAlarm> queryWrapper = new QueryWrapper<DeviceAlarm>().eq("device_id", deviceId);

        if (StrUtil.isNotEmpty(startTime)) {
            queryWrapper.ge("start_time", startTime);
        }
        if (StrUtil.isNotEmpty(endTime)) {
            queryWrapper.le("start_time", endTime);
        }
        queryWrapper.orderByDesc("start_time");
        IPage<DeviceAlarm> alarmPage = deviceAlarmMapper.selectPage(page, queryWrapper);

        // List<DeviceAlarmVo> deviceAlarmVoList = BeanUtil.copyToList(alarmPage.getRecords(), DeviceAlarmVo.class);
        return TableDataInfo.build(alarmPage);
    }

}


