package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.lotPlatFormDevice.LotPlatformDeviceAddRequest;
import com.ruoyi.web.domain.dto.lotPlatFormDevice.LotPlatformDeviceEditRequest;
import com.ruoyi.web.domain.dto.lotPlatFormDevice.LotPlatformDeviceQueryRequest;
import com.ruoyi.web.domain.entity.LotPlatformDevice;
import com.ruoyi.web.domain.vo.LotPlatformDeviceVO;
import com.ruoyi.web.mapper.LotPlatformDeviceMapper;
import com.ruoyi.web.service.LotPlatformDeviceService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class LotPlatformDeviceServiceImpl extends ServiceImpl<LotPlatformDeviceMapper, LotPlatformDevice>
        implements LotPlatformDeviceService {
    /**
     * 添加
     *
     * @param lotPlatformDeviceAddRequest
     * @return
     */
    @Override
    public Integer addLotPlatformDevice(LotPlatformDeviceAddRequest lotPlatformDeviceAddRequest) {
        if (lotPlatformDeviceAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }

            // 转换为实体对象
            LotPlatformDevice lotPlatformDevice = new LotPlatformDevice();
            BeanUtil.copyProperties(lotPlatformDeviceAddRequest, lotPlatformDevice);
            //数据校验
            validLotPlatformDevice(lotPlatformDevice, BusinessType.INSERT);
        int code = this.count(new QueryWrapper<LotPlatformDevice>().eq("code", lotPlatformDeviceAddRequest.getCode()));
        if (code > 0){
            throw new ServiceException("设备编号不能重复");
        }

        // 保存到数据库
            this.save(lotPlatformDevice);
            return lotPlatformDevice.getId();

    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteLotPlatformDevice(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("id不能为空或id异常");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<LotPlatformDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

        // 4. 执行删除（返回是否删除成功）
        return remove(queryWrapper);

    }

    /**
     * 编辑
     *
     * @param lotPlatformDeviceEditRequest
     */
    @Override
    public void editLotPlatformDevice(LotPlatformDeviceEditRequest lotPlatformDeviceEditRequest) {
        // 判断是否存在
        Integer id = lotPlatformDeviceEditRequest.getId();
        LotPlatformDevice oldLotPlatformDevice = this.getById(id);
        if (oldLotPlatformDevice == null) {
            throw new ServiceException("没有找到物联网平台设备");
        }
        LotPlatformDevice lotPlatformDevice = new LotPlatformDevice();
        BeanUtil.copyProperties(lotPlatformDeviceEditRequest, lotPlatformDevice);
        lotPlatformDevice.setUpdateTime(new Date());
        // 数据校验
        validLotPlatformDevice(lotPlatformDevice, BusinessType.UPDATE);
        int code = this.count(new QueryWrapper<LotPlatformDevice>().eq("code", lotPlatformDeviceEditRequest.getCode()).ne("id",lotPlatformDeviceEditRequest.getId()));
        if (code > 0){
            throw new ServiceException("设备编号不能重复");
        }
        // 操作数据库
        boolean result = this.updateById(lotPlatformDevice);
        if (!result) {
            throw new ServiceException("修改物联网平台设备操作失败");
        }
    }

    /**
     * 校验数据
     *
     * @param lotPlatformDevice
     */
    public void validLotPlatformDevice(LotPlatformDevice lotPlatformDevice, BusinessType type) {
        if (ObjectUtil.isEmpty(lotPlatformDevice)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = lotPlatformDevice.getId();
        String code = lotPlatformDevice.getCode();
        String name = lotPlatformDevice.getName();
        String category = lotPlatformDevice.getCategory();
        String location = lotPlatformDevice.getLocation();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(code)) {
            throw new ServiceException("设备编号不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("设备名称不能为空");
        }
        if (StrUtil.isBlank(category)) {
            throw new ServiceException("类别不能为空");
        }
        if (StrUtil.isBlank(location)) {
            throw new ServiceException("安装位置不能为空");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public LotPlatformDeviceVO getLotPlatformDeviceById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        LotPlatformDevice lotPlatformDevice = this.getById(id);
        return getLotPlatformDeviceVO(lotPlatformDevice);
    }

    /**
     * 获取项目包装类
     *
     * @param lotPlatformDevice
     * @return
     */
    @Override
    public LotPlatformDeviceVO getLotPlatformDeviceVO(LotPlatformDevice lotPlatformDevice) {
        if (ObjectUtil.isEmpty(lotPlatformDevice)) {
            throw new ServiceException("请求参数不存在");
        }
        LotPlatformDeviceVO lotPlatformDeviceVO = new LotPlatformDeviceVO();
        BeanUtils.copyProperties(lotPlatformDevice, lotPlatformDeviceVO);
        return lotPlatformDeviceVO;
    }

    /**
     * 分页获取项目列表
     *
     * @param lotPlatformDeviceQueryRequest
     * @return
     */
    @Override
    public Page<LotPlatformDeviceVO> getListLotPlatformDeviceByPage(LotPlatformDeviceQueryRequest lotPlatformDeviceQueryRequest) {
        long current = lotPlatformDeviceQueryRequest.getPageNum();
        long size = lotPlatformDeviceQueryRequest.getPageSize();
        Page<LotPlatformDevice> page = this.page(new Page<>(current, size),
                getQueryWrapper(lotPlatformDeviceQueryRequest));
        Page<LotPlatformDeviceVO> lotPlatformDeviceVOPage = new Page<>();
        BeanUtils.copyProperties(page, lotPlatformDeviceVOPage, "records");
        List<LotPlatformDeviceVO> voList = page.getRecords().stream()
                .map(lotPlatformDevice -> {
                    LotPlatformDeviceVO vo = new LotPlatformDeviceVO();
                    BeanUtils.copyProperties(lotPlatformDevice, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        lotPlatformDeviceVOPage.setRecords(voList);
        return lotPlatformDeviceVOPage;
    }

    /**
     * 获取查询条件
     *
     * @param lotPlatformDeviceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<LotPlatformDevice> getQueryWrapper(LotPlatformDeviceQueryRequest lotPlatformDeviceQueryRequest) {
        QueryWrapper<LotPlatformDevice> queryWrapper = new QueryWrapper<>();
        if (lotPlatformDeviceQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        Integer id = lotPlatformDeviceQueryRequest.getId();
        String code = lotPlatformDeviceQueryRequest.getCode();
        String name = lotPlatformDeviceQueryRequest.getName();
        String category = lotPlatformDeviceQueryRequest.getCategory();
        String location = lotPlatformDeviceQueryRequest.getLocation();
        String sortField = lotPlatformDeviceQueryRequest.getSortField();
        String sortOrder = lotPlatformDeviceQueryRequest.getSortOrder();

        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.like(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.like(StrUtil.isNotBlank(code), "code", code);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(location), "location", location);

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }

    @Override
    public List<LotPlatformDevice> listLotPlatformDevice(LotPlatformDeviceQueryRequest lotPlatformDeviceQueryRequest) {

        List<LotPlatformDevice> list = this.list(
                getQueryWrapper(lotPlatformDeviceQueryRequest));
        Page<LotPlatformDeviceVO> lotPlatformDeviceVOPage = new Page<>();

        return list;
    }
}




