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.lotPlatformProducts.LotPlatformProductsAddRequest;
import com.ruoyi.web.domain.dto.lotPlatformProducts.LotPlatformProductsEditRequest;
import com.ruoyi.web.domain.dto.lotPlatformProducts.LotPlatformProductsQueryRequest;
import com.ruoyi.web.domain.entity.LotPlatformProducts;
import com.ruoyi.web.domain.vo.LotPlatformProductsVO;
import com.ruoyi.web.mapper.LotPlatformProductsMapper;
import com.ruoyi.web.service.LotPlatformProductsService;
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 LotPlatformProductsServiceImpl extends ServiceImpl<LotPlatformProductsMapper, LotPlatformProducts>
        implements LotPlatformProductsService {
    /**
     * 添加
     *
     * @param lotPlatformProductsAddRequest
     * @return
     */
    @Override
    public Integer addLotPlatformProducts(LotPlatformProductsAddRequest lotPlatformProductsAddRequest) {
        if (lotPlatformProductsAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        int category1 = this.count(new QueryWrapper<LotPlatformProducts>().eq("category", lotPlatformProductsAddRequest.getCategory()));
        if (category1 >0){
            throw new ServiceException("设备类别重复");
        }
        try {
            // 转换为实体对象
            LotPlatformProducts lotPlatformProducts = new LotPlatformProducts();
            BeanUtil.copyProperties(lotPlatformProductsAddRequest, lotPlatformProducts);
            //数据校验
            validLotPlatformProducts(lotPlatformProducts, BusinessType.INSERT);

            // 保存到数据库
            this.save(lotPlatformProducts);
            return lotPlatformProducts.getId();
        } catch (Exception e) {
            log.error("添加失败", e);
            throw new ServiceException("添加失败");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteLotPlatformProducts(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<LotPlatformProducts> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

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

    }

    /**
     * 编辑
     *
     * @param lotPlatformProductsEditRequest
     */
    @Override
    public void editLotPlatformProducts(LotPlatformProductsEditRequest lotPlatformProductsEditRequest) {
        // 判断是否存在
        Integer id = lotPlatformProductsEditRequest.getId();
        LotPlatformProducts oldLotPlatformProducts = this.getById(id);
        if (oldLotPlatformProducts == null) {
            throw new ServiceException("没有找到物联网平台产品");
        }
        LotPlatformProducts lotPlatformProducts = new LotPlatformProducts();
        BeanUtil.copyProperties(lotPlatformProductsEditRequest, lotPlatformProducts);
        lotPlatformProducts.setUpdateTime(new Date());
        // 数据校验
        validLotPlatformProducts(lotPlatformProducts, BusinessType.UPDATE);
        int category1 = this.count(new QueryWrapper<LotPlatformProducts>().eq("category", lotPlatformProductsEditRequest.getCategory()).ne("id",lotPlatformProductsEditRequest.getId()));
        if (category1 >0){
            throw new ServiceException("设备类别重复");
        }
        // 操作数据库
        boolean result = this.updateById(lotPlatformProducts);
        if (!result) {
            throw new ServiceException("修改物联网平台产品操作失败");
        }
    }

    /**
     * 校验数据
     *
     * @param lotPlatformProducts
     */
    public void validLotPlatformProducts(LotPlatformProducts lotPlatformProducts, BusinessType type) {
        if (ObjectUtil.isEmpty(lotPlatformProducts)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = lotPlatformProducts.getId();
        String category = lotPlatformProducts.getCategory();


        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(category)) {
            throw new ServiceException("类别不能为空");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public LotPlatformProductsVO getLotPlatformProductsById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        LotPlatformProducts lotPlatformProducts = this.getById(id);
        return getLotPlatformProductsVO(lotPlatformProducts);
    }

    /**
     * 获取项目包装类
     *
     * @param lotPlatformProducts
     * @return
     */
    @Override
    public LotPlatformProductsVO getLotPlatformProductsVO(LotPlatformProducts lotPlatformProducts) {
        if (ObjectUtil.isEmpty(lotPlatformProducts)) {
            throw new ServiceException("请求参数不存在");
        }
        LotPlatformProductsVO lotPlatformProductsVO = new LotPlatformProductsVO();
        BeanUtils.copyProperties(lotPlatformProducts, lotPlatformProductsVO);
        return lotPlatformProductsVO;
    }

    /**
     * 分页获取项目列表
     *
     * @param lotPlatformProductsQueryRequest
     * @return
     */
    @Override
    public Page<LotPlatformProductsVO> getListLotPlatformProductsByPage(LotPlatformProductsQueryRequest lotPlatformProductsQueryRequest) {
        long current = lotPlatformProductsQueryRequest.getPageNum();
        long size = lotPlatformProductsQueryRequest.getPageSize();
        Page<LotPlatformProducts> page = this.page(new Page<>(current, size),
                getQueryWrapper(lotPlatformProductsQueryRequest));
        Page<LotPlatformProductsVO> lotPlatformProductsVOPage = new Page<>();
        BeanUtils.copyProperties(page, lotPlatformProductsVOPage, "records");
        List<LotPlatformProductsVO> voList = page.getRecords().stream()
                .map(lotPlatformProducts -> {
                    LotPlatformProductsVO vo = new LotPlatformProductsVO();
                    BeanUtils.copyProperties(lotPlatformProducts, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        lotPlatformProductsVOPage.setRecords(voList);
        return lotPlatformProductsVOPage;
    }

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

        // 从对象中取值
        Integer id = lotPlatformProductsQueryRequest.getId();
        String category = lotPlatformProductsQueryRequest.getCategory();
        String sortField = lotPlatformProductsQueryRequest.getSortField();
        String sortOrder = lotPlatformProductsQueryRequest.getSortOrder();

        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);

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

    @Override
    public List<LotPlatformProducts> listLotPlatformProducts(LotPlatformProductsQueryRequest lotPlatformProductsQueryRequest) {

        List<LotPlatformProducts> list = this.list(
                getQueryWrapper(lotPlatformProductsQueryRequest));

        return list;
    }
}




