package com.fuyuanshen.equipment.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.common.core.domain.PageResult;
import com.fuyuanshen.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.core.utils.PageUtil;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.form.DeviceTypeForm;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.query.DeviceTypeQueryCriteria;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.service.DeviceTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Author: WY
 * @Date: 2025/5/14
 **/
@Service
@RequiredArgsConstructor
public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceType> implements DeviceTypeService {

    private final DeviceTypeMapper deviceTypeMapper;
    private final DeviceMapper deviceMapper;


    /**
     * 分页查询设备类型
     *
     * @param criteria 条件
     * @param page     分页参数
     * @return
     */
    @Override
    public TableDataInfo<DeviceType> queryAll(DeviceTypeQueryCriteria criteria, Page<DeviceType> page) {
        criteria.setCustomerId(LoginHelper.getUserId());
        // return
        IPage<DeviceType> deviceTypeIPage = deviceTypeMapper.findAll(criteria, page);
        return new TableDataInfo<DeviceType>(deviceTypeIPage.getRecords(), deviceTypeIPage.getTotal());
    }


    @Override
    public List<DeviceType> queryAll(DeviceTypeQueryCriteria criteria) {
        return deviceTypeMapper.findAll(criteria);
    }


    /**
     * 查询所有设备类型
     *
     * @return
     */
    @Override
    public List<DeviceType> queryDeviceTypes() {
        DeviceTypeQueryCriteria criteria = new DeviceTypeQueryCriteria();
        Long userId = LoginHelper.getUserId();
        criteria.setCustomerId(userId);
        return deviceTypeMapper.findAll(criteria);
    }


    /**
     * 新增设备类型
     *
     * @param resources /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DeviceType resources) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        resources.setCustomerId(loginUser.getUserId());
        resources.setOwnerCustomerId(loginUser.getUserId());
        resources.setCreateByName(loginUser.getNickname());
        deviceTypeMapper.insert(resources);
    }


    /**
     * 修改设备类型
     *
     * @param resources /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DeviceTypeForm resources) {
        DeviceType deviceType = deviceTypeMapper.selectById(resources.getId());
        if (deviceType == null) {
            throw new RuntimeException("设备类型不存在");
        }
        if (!Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) {
            throw new RuntimeException("无权修改该设备类型");
        }
        // if (deviceMapper.countByTypeId(resources.getId()) > 0)
        //     throw new RuntimeException("该设备类型已被使用，无法删除");
        BeanUtil.copyProperties(resources, deviceType);
        deviceTypeMapper.updateById(deviceType);
    }


    /**
     * 删除设备类型
     *
     * @param ids /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {

        List<Long> invalidIds = new ArrayList<>();
        List<Long> invalidId2 = new ArrayList<>();
        for (Long id : ids) {
            DeviceType deviceType = deviceTypeMapper.selectById(id);
            if (deviceType == null || !Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) {
                invalidIds.add(id);
            }
            DeviceQueryCriteria deviceQueryCriteria = new DeviceQueryCriteria();
            deviceQueryCriteria.setDeviceTypeId(id);
            List<Device> devices = deviceMapper.findAll(deviceQueryCriteria);
            if (!devices.isEmpty()) {
                invalidId2.add(id);
            }
        }
        if (!invalidIds.isEmpty()) {
            throw new RuntimeException("以下设备类型无法删除（ID 不存在或无权限）: " + invalidIds);
        }
        if (!invalidId2.isEmpty()) {
            throw new RuntimeException("以下设备类型无法删除（已绑定设备）: " + invalidId2);
        }

        deviceTypeMapper.deleteByIds(ids);
    }


    /**
     * 获取设备类型通讯方式
     *
     * @param id /
     * @return DeviceTypeDto
     */
    @Override
    public DeviceType getCommunicationMode(Long id) {
        DeviceType deviceType = deviceTypeMapper.selectById(id);
        if (deviceType == null) {
            throw new RuntimeException("设备类型不存在");
        }
        if (!Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) {
            throw new RuntimeException("无权获取该设备类型通讯方式");
        }
        return deviceType;
    }


}
