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.web.domain.dto.facility.FacilityAddRequest;
import com.ruoyi.web.domain.dto.facility.FacilityEditRequest;
import com.ruoyi.web.domain.dto.facility.FacilityQueryRequest;
import com.ruoyi.web.domain.entity.FacilityManagement;
import com.ruoyi.web.domain.vo.FacilityManagement.BaseFacilityVO;
import com.ruoyi.web.domain.vo.FacilityManagement.FacilityVOFactory;
import com.ruoyi.web.mapper.FacilityManagementMapper;
import com.ruoyi.web.service.FacilityManagementService;
import org.springframework.beans.BeanUtils;
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 FacilityManagementServiceImpl extends ServiceImpl<FacilityManagementMapper, FacilityManagement>
        implements FacilityManagementService {

    /**
     * 添加
     *
     * @param facilityAddRequest
     * @return
     */
    @Override
    public Integer addFacility(FacilityAddRequest facilityAddRequest) {
        if (facilityAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        FacilityManagement facilityManagement = new FacilityManagement();
        BeanUtil.copyProperties(facilityAddRequest, facilityManagement);
        // 数据校验
        validFacility(facilityManagement, BusinessType.INSERT);
        // 插入数据库
        this.save(facilityManagement);
        return facilityManagement.getId();
    }

    /**
     * 编辑
     *
     * @param facilityEditRequest
     */
    @Override
    public void editFacility(FacilityEditRequest facilityEditRequest) {
        // 实体类和 DTO 进行转换
        FacilityManagement facilityManagement = new FacilityManagement();
        BeanUtils.copyProperties(facilityEditRequest, facilityManagement);
        // 设置编辑时间
        facilityManagement.setUpdateTime(new Date());
        // 数据校验
        validFacility(facilityManagement, BusinessType.UPDATE);
        // 判断是否存在
        Integer id = facilityEditRequest.getId();
        FacilityManagement oldFacility = this.getById(id);
        if (oldFacility == null) {
            throw new ServiceException("没有找到设施");
        }
        // 操作数据库
        boolean result = this.updateById(facilityManagement);
        if (!result) {
            throw new ServiceException("操作失败");
        }
    }

    /**
     * 校验设施
     *
     * @param facilityManagement
     */
    public void validFacility(FacilityManagement facilityManagement, BusinessType type) {
        if (ObjectUtil.isEmpty(facilityManagement)) {
            throw new ServiceException("数据为空");
        }
        Integer id = facilityManagement.getId();
        String facilityType = facilityManagement.getFacilityType();
        String facilityName = facilityManagement.getFacilityName();
        String location = facilityManagement.getLocation();
        String extent = facilityManagement.getExtent();
        String breadth = facilityManagement.getBreadth();
        String area = facilityManagement.getArea();
        String year = facilityManagement.getYear();
        Integer classNum = facilityManagement.getClassNum();
        Integer teacherNum = facilityManagement.getTeacherNum();
        Integer studentNum = facilityManagement.getStudentNum();

        // 修改数据时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(facilityType)) {
            throw new ServiceException("设施类型不能为空");
        }
        if (StrUtil.isBlank(facilityName)) {
            throw new ServiceException("设施名称不能为空");
        }
        if (StrUtil.isBlank(location)) {
            throw new ServiceException("位置不能为空");
        }
        if (StrUtil.isBlank(year)) {
            throw new ServiceException("建成年份不能为空");
        }

        // 道路
        if ("1".equals(facilityType)) {
            if (StrUtil.isBlank(extent)) {
                throw new ServiceException("长度不能为空");
            }
            if (StrUtil.isBlank(breadth)) {
                throw new ServiceException("宽度不能为空");
            }
        }
        // 学校
        if ("4".equals(facilityType)) {
            if (StrUtil.isBlank(area)) {
                throw new ServiceException("占地面积不能为空");
            }
            if (ObjectUtil.isEmpty(classNum)) {
                throw new ServiceException("班级数量不能为空");
            }
            if (ObjectUtil.isEmpty(teacherNum)) {
                throw new ServiceException("教师数量不能为空");
            }
            if (ObjectUtil.isEmpty(studentNum)) {
                throw new ServiceException("学生数量不能为空");
            }
        }
    }

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

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

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public BaseFacilityVO getFacilityById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        FacilityManagement facilityManagement = this.getById(id);
        return FacilityVOFactory.convert(facilityManagement);
    }

    /**
     * 分页查询
     *
     * @param facilityQueryRequest
     * @return
     */
    @Override
    public Page<? extends BaseFacilityVO> getListFacilityManagementByPage(FacilityQueryRequest facilityQueryRequest) {

        QueryWrapper<FacilityManagement> queryWrapper = new QueryWrapper<>();
        String facilityType = facilityQueryRequest.getFacilityType();
        String facilityName = facilityQueryRequest.getFacilityName();
        long current = facilityQueryRequest.getPageNum();
        long pageSize = facilityQueryRequest.getPageSize();
        String sortField = facilityQueryRequest.getSortField();
        String sortOrder = facilityQueryRequest.getSortOrder();

        //
        queryWrapper.eq(StrUtil.isNotBlank(facilityType), "facility_type", facilityType);
        queryWrapper.like(StrUtil.isNotBlank(facilityName), "facility_name", facilityName);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);

        // 1. 分页查询
        Page<FacilityManagement> facilityManagementPage = this.page(new Page<>(current, pageSize),
                queryWrapper);

        // 转换为VO
        List<? extends BaseFacilityVO> voList = facilityManagementPage.getRecords().stream()
                .map(FacilityVOFactory::convert)
                .collect(Collectors.toList());

        // 创建新的Page对象并复制分页信息
        Page<BaseFacilityVO> resultPage = new Page<>();
        resultPage.setCurrent(facilityManagementPage.getCurrent());
        resultPage.setSize(facilityManagementPage.getSize());
        resultPage.setTotal(facilityManagementPage.getTotal());
        resultPage.setPages(facilityManagementPage.getPages());
        resultPage.setRecords((List<BaseFacilityVO>) voList);

        return resultPage;
    }
}




