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.model.LoginUser;
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.DeviceTypeGrants;
import com.fuyuanshen.equipment.domain.form.DeviceTypeForm;
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 com.fuyuanshen.equipment.utils.FileHashUtil;
import com.fuyuanshen.system.domain.vo.SysOssVo;
import com.fuyuanshen.system.domain.vo.SysRoleVo;
import com.fuyuanshen.system.service.ISysOssService;
import com.fuyuanshen.system.service.ISysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
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;

    private final ISysRoleService roleService;
    private final ISysOssService ossService;
    private final FileHashUtil fileHashUtil;


    /**
     * 分页查询设备类型
     *
     * @param criteria 条件
     * @param page     分页参数
     * @return
     */
    @Override
    public TableDataInfo<DeviceType> queryAll(DeviceTypeQueryCriteria criteria, Page<DeviceType> page) {
        // 管理员
        // String username = LoginHelper.getUsername();
        // if (!username.equals("admin")) {
        //     criteria.setCustomerId(LoginHelper.getUserId());
        // }
        // 角色管理员
        Long userId = LoginHelper.getUserId();
        List<SysRoleVo> roles = roleService.selectRolesAuthByUserId(userId);
        boolean isAdmin = false;
        if (CollectionUtil.isNotEmpty(roles)) {
            for (SysRoleVo role : roles) {
                if (role.getRoleKey().contains("admin")) {
                    isAdmin = true;
                    break;
                }
            }
        }
        if (!isAdmin) {
            criteria.setCustomerId(LoginHelper.getUserId());
        }

        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();

        // // 管理员
        // String username = LoginHelper.getUsername();
        // if (!username.equals("admin")) {
        //     criteria.setCustomerId(LoginHelper.getUserId());
        //
        //     Long userId = LoginHelper.getUserId();
        //     criteria.setCustomerId(userId);
        // }

        // 角色管理员
        Long userId = LoginHelper.getUserId();
        List<SysRoleVo> roles = roleService.selectRolesAuthByUserId(userId);
        boolean isAdmin = false;
        if (CollectionUtil.isNotEmpty(roles)) {
            for (SysRoleVo role : roles) {
                if (role.getRoleKey().contains("admin")) {
                    isAdmin = true;
                    break;
                }
            }
        }
        if (!isAdmin) {
            criteria.setCustomerId(LoginHelper.getUserId());
        }

        return deviceTypeMapper.findAll(criteria);
    }


    /**
     * 根据设备类型名称查询设备类型
     *
     * @param typeName 条件参数
     * @return List<DeviceTypeDto>
     */
    @Override
    public DeviceType queryByName(String typeName) {
        DeviceTypeQueryCriteria criteria = new DeviceTypeQueryCriteria();

        // 角色管理员
        Long userId = LoginHelper.getUserId();
        List<SysRoleVo> roles = roleService.selectRolesAuthByUserId(userId);
        boolean isAdmin = false;
        if (CollectionUtil.isNotEmpty(roles)) {
            for (SysRoleVo role : roles) {
                if (role.getRoleKey().contains("admin")) {
                    isAdmin = true;
                    break;
                }
            }
        }
        if (!isAdmin) {
            criteria.setCustomerId(LoginHelper.getUserId());
        }

        criteria.setTypeName(typeName);
        DeviceType deviceType = deviceTypeMapper.queryByName(criteria);
        return deviceType;
    }


    /**
     * 根据设备类型名称列表查询设备类型
     *
     * @param typeNames 设备类型名称列表
     * @return List<DeviceType>
     */
    @Override
    public List<DeviceType> queryByNames(List<String> typeNames) {
        if (typeNames == null || typeNames.isEmpty()) {
            return new ArrayList<>();
        }
        return deviceTypeMapper.selectByNames(typeNames);
    }


    /**
     * 新增设备类型
     *
     * @param resources /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DeviceTypeForm resources) throws IOException {

        // 校验设备类型名称
        List<DeviceType> typeName = deviceTypeMapper.selectList(new QueryWrapper<DeviceType>().eq("type_name", resources.getTypeName()));
        if (CollectionUtil.isNotEmpty(typeName)) {
            throw new RuntimeException("设备类型名称已存在，无法新增!!!");
        }
        // 保存图片并获取URL
        if (resources.getFile() != null) {
            String fileHash = fileHashUtil.hash(resources.getFile());
            SysOssVo upload = ossService.updateHash(resources.getFile(), fileHash);
            // 强制将HTTP替换为HTTPS
            if (upload.getUrl() != null && upload.getUrl().startsWith("http://")) {
                upload.setUrl(upload.getUrl().replaceFirst("^http://", "https://"));
            }
            // 设置图片路径
            resources.setDevicePic(upload.getUrl());
        }

        DeviceType deviceType = new DeviceType();
        BeanUtil.copyProperties(resources, deviceType, true);

        LoginUser loginUser = LoginHelper.getLoginUser();
        deviceType.setCustomerId(loginUser.getUserId());
        deviceType.setOwnerCustomerId(loginUser.getUserId());
        deviceType.setOriginalOwnerId(loginUser.getUserId());
        deviceType.setCreateByName(loginUser.getNickname());
        deviceTypeMapper.insert(deviceType);

        // 自动授权给自己
        DeviceTypeGrants deviceTypeGrants = new DeviceTypeGrants();
        deviceTypeGrants.setDeviceTypeId(deviceType.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) throws IOException {
        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 (!deviceType.getTypeName().equals(resources.getTypeName()) || !deviceType.getAppModelDictionary().equals(resources.getAppModelDictionary())) {
            int count = deviceMapper.countByDeviceTypeId(deviceType.getId());
            if (count > 0) {
                throw new RuntimeException("该设备类型下已有设备，无法修改设备类型名称和路由跳转!!!");
            }
        }

        // 校验设备类型名称
        DeviceType dt = deviceTypeMapper.selectOne(new QueryWrapper<DeviceType>().eq("type_name", resources.getTypeName()));
        if (dt != null && !dt.getId().equals(deviceType.getId())) {
            throw new RuntimeException("设备类型名称已存在,无法修改!!!");
        }

        // 管理员
        String username = LoginHelper.getUsername();
        if (!username.equals("admin")) {
            if (!Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) {
                throw new RuntimeException("无权修改该设备类型");
            }
        }
        // 保存图片并获取URL
        if (resources.getFile() != null) {
            String fileHash = fileHashUtil.hash(resources.getFile());
            SysOssVo upload = ossService.updateHash(resources.getFile(), fileHash);
            // 强制将HTTP替换为HTTPS
            if (upload.getUrl() != null && upload.getUrl().startsWith("http://")) {
                upload.setUrl(upload.getUrl().replaceFirst("^http://", "https://"));
            }
            // 设置图片路径
            resources.setDevicePic(upload.getUrl());
        }

        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;
    }


}
