package com.fuyuanshen.equipment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.DeviceAssignments;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.DeviceTypeGrants;
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.DeviceAssignmentsMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeGrantsMapper;
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.Date;
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;

    private final DeviceTypeGrantsMapper deviceTypeGrantsMapper;
    private final DeviceAssignmentsMapper deviceAssignmentsMapper;


    /**
     * 分页查询设备类型
     *
     * @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 typeName 条件参数
     * @return List<DeviceTypeDto>
     */
    @Override
    public DeviceType queryByName(String typeName) {
        DeviceTypeQueryCriteria criteria = new DeviceTypeQueryCriteria();
        criteria.setCustomerId(LoginHelper.getUserId());
        criteria.setTypeName(typeName);
        DeviceType deviceType = deviceTypeMapper.queryByName(criteria);
        return deviceType;
    }


    /**
     * 新增设备类型
     *
     * @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.setOriginalOwnerId(loginUser.getUserId());
        resources.setCreateByName(loginUser.getNickname());
        deviceTypeMapper.insert(resources);

        // 自动授权给自己
        DeviceTypeGrants deviceTypeGrants = new DeviceTypeGrants();
        deviceTypeGrants.setDeviceTypeId(resources.getId());
        deviceTypeGrants.setCustomerId(loginUser.getUserId());
        deviceTypeGrants.setGrantorCustomerId(loginUser.getUserId());
        deviceTypeGrants.setGrantedAt(new Date());
        deviceTypeGrantsMapper.insert(deviceTypeGrants);
    }


    /**
     * 修改设备类型
     *
     * @param resources /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DeviceTypeForm resources) {
        DeviceTypeGrants deviceTypeGrants = deviceTypeGrantsMapper.selectById(resources.getId());
        if (deviceTypeGrants == null) {
            throw new RuntimeException("设备类型不存在");
        }
        resources.setId(deviceTypeGrants.getDeviceTypeId());
        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> deviceTypeId = new ArrayList<>();

        for (Long id : ids) {
            DeviceTypeGrants deviceTypeGrant = deviceTypeGrantsMapper.selectById(id);

            //     List<DeviceTypeGrants> deviceTypeGrants = deviceTypeGrantsMapper.selectList(new QueryWrapper<DeviceTypeGrants>()
            //                     .eq("device_type_id", deviceTypeGrant.getDeviceTypeId()));

            // List<DeviceTypeGrants> deviceAssignments = deviceTypeGrantsMapper.selectList(new QueryWrapper<DeviceTypeGrants>()
            //         .eq("device_id", deviceTypeGrant.getDeviceTypeId()));

            // if (CollectionUtil.isNotEmpty(deviceAssignments)) {
            //     throw new RuntimeException("该设备类型已绑定设备，无法删除");
            // }
            // Device device = deviceMapper.selectById(deviceTypeGrant.getDeviceTypeId());

            List<Device> devices = deviceMapper.selectList(new QueryWrapper<Device>()
                    .eq("device_type", deviceTypeGrant.getDeviceTypeId()));
            if (CollectionUtil.isNotEmpty(devices)) {
                throw new RuntimeException("该设备类型已绑定设备，无法删除！！！");
            }
            deviceTypeId.add(deviceTypeGrant.getDeviceTypeId());
        }

        deviceTypeGrantsMapper.deleteByIds(ids);
        deviceTypeMapper.deleteByIds(deviceTypeId);

    }


    /**
     * 获取设备类型通讯方式
     *
     * @param id /
     * @return DeviceTypeDto
     */
    @Override
    public DeviceType getCommunicationMode(Long id) {

        DeviceTypeGrants deviceTypeGrants = deviceTypeGrantsMapper.selectById(id);
        if (deviceTypeGrants == null) {
            throw new RuntimeException("设备类型不存在");
        }

        DeviceType deviceType = deviceTypeMapper.selectById(deviceTypeGrants.getDeviceTypeId());
        if (deviceType == null) {
            throw new RuntimeException("设备类型不存在");
        }
        //
        // if (!Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) {
        //     throw new RuntimeException("无权获取该设备类型通讯方式");
        // }
        return deviceType;
    }


}
