package org.dromara.facility.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.facility.domain.FacPhotovoltaicPanelSupport;
import org.dromara.facility.domain.dto.photovoltaicpanelsupport.FacPhotovoltaicPanelSupportCreateReq;
import org.dromara.facility.domain.dto.photovoltaicpanelsupport.FacPhotovoltaicPanelSupportQueryReq;
import org.dromara.facility.domain.dto.photovoltaicpanelsupport.FacPhotovoltaicPanelSupportUpdateReq;
import org.dromara.facility.domain.vo.photovoltaicpanelsupport.FacPhotovoltaicPanelSupportVo;
import org.dromara.facility.mapper.FacPhotovoltaicPanelSupportMapper;
import org.dromara.facility.service.IFacMatrixService;
import org.dromara.facility.service.IFacPhotovoltaicPanelSupportService;
import org.dromara.project.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 设施-光伏板支架Service业务层处理
 *
 * @author lcj
 * @date 2025-04-21
 */
@Service
public class FacPhotovoltaicPanelSupportServiceImpl extends ServiceImpl<FacPhotovoltaicPanelSupportMapper, FacPhotovoltaicPanelSupport>
    implements IFacPhotovoltaicPanelSupportService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IFacMatrixService matrixService;

    /**
     * 查询设施-光伏板支架
     *
     * @param id 主键
     * @return 设施-光伏板支架
     */
    @Override
    public FacPhotovoltaicPanelSupportVo queryById(Long id) {
        FacPhotovoltaicPanelSupport photovoltaicPanelSupport = this.getById(id);
        if (photovoltaicPanelSupport == null) {
            throw new ServiceException("查询光伏板支架失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(photovoltaicPanelSupport);
    }

    /**
     * 分页查询设施-光伏板支架列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 设施-光伏板支架分页列表
     */
    @Override
    public TableDataInfo<FacPhotovoltaicPanelSupportVo> queryPageList(FacPhotovoltaicPanelSupportQueryReq req, PageQuery pageQuery) {
        Page<FacPhotovoltaicPanelSupport> result = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的设施-光伏板支架列表
     *
     * @param req 查询条件
     * @return 设施-光伏板支架列表
     */
    @Override
    public List<FacPhotovoltaicPanelSupportVo> queryList(FacPhotovoltaicPanelSupportQueryReq req) {
        List<FacPhotovoltaicPanelSupport> photovoltaicPanelSupportList = this.list(this.buildQueryWrapper(req));
        return photovoltaicPanelSupportList.stream().map(this::getVo).toList();
    }

    /**
     * 新增设施-光伏板支架
     *
     * @param req 设施-光伏板支架
     * @return 新增光伏板支架id
     */
    @Override
    public Long insertByBo(FacPhotovoltaicPanelSupportCreateReq req) {
        // 将实体类和 DTO 进行转换
        FacPhotovoltaicPanelSupport photovoltaicPanelSupport = new FacPhotovoltaicPanelSupport();
        BeanUtils.copyProperties(req, photovoltaicPanelSupport);
        // 将位置信息转换为 JSON 字符串
        List<String> positionList = req.getPositionList();
        if (ObjectUtils.isNotEmpty(positionList)) {
            String positionStr = JSONUtil.toJsonStr(positionList);
            photovoltaicPanelSupport.setPositions(positionStr);
        }
        // 数据校验
        validEntityBeforeSave(photovoltaicPanelSupport, true);
        // 判断是否存在同名光伏板支架
        Long count = this.lambdaQuery()
            .eq(FacPhotovoltaicPanelSupport::getProjectId, photovoltaicPanelSupport.getProjectId())
            .eq(FacPhotovoltaicPanelSupport::getName, photovoltaicPanelSupport.getName())
            .count();
        if (count > 0) {
            throw new ServiceException("该项目已存在同名光伏板支架", HttpStatus.CONFLICT);
        }
        // 操作数据库
        boolean save = this.save(photovoltaicPanelSupport);
        if (!save) {
            throw new ServiceException("新增光伏板支架失败，数据库异常", HttpStatus.ERROR);
        }
        return photovoltaicPanelSupport.getId();
    }

    /**
     * 修改设施-光伏板支架
     *
     * @param req 设施-光伏板支架
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(FacPhotovoltaicPanelSupportUpdateReq req) {
        // 将实体类和 DTO 进行转换
        FacPhotovoltaicPanelSupport photovoltaicPanelSupport = new FacPhotovoltaicPanelSupport();
        BeanUtils.copyProperties(req, photovoltaicPanelSupport);
        // 将位置信息转换为 JSON 字符串
        List<String> positionList = req.getPositionList();
        if (ObjectUtils.isNotEmpty(positionList)) {
            String positionStr = JSONUtil.toJsonStr(positionList);
            photovoltaicPanelSupport.setPositions(positionStr);
        }
        // 数据校验
        validEntityBeforeSave(photovoltaicPanelSupport, false);
        // 判断是否存在
        FacPhotovoltaicPanelSupport oldPhotovoltaicPanelSupport = this.getById(photovoltaicPanelSupport.getId());
        if (oldPhotovoltaicPanelSupport == null) {
            throw new ServiceException("修改光伏板支架失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 判断是否修改名称
        if (!oldPhotovoltaicPanelSupport.getName().equals(photovoltaicPanelSupport.getName())) {
            Long count = this.lambdaQuery()
                .eq(FacPhotovoltaicPanelSupport::getProjectId, photovoltaicPanelSupport.getProjectId())
                .eq(FacPhotovoltaicPanelSupport::getName, photovoltaicPanelSupport.getName())
                .count();
            if (count > 0) {
                throw new ServiceException("该项目已存在同名光伏板支架", HttpStatus.CONFLICT);
            }
        }
        // 操作数据库
        boolean update = this.updateById(photovoltaicPanelSupport);
        if (!update) {
            throw new ServiceException("修改光伏板支架失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FacPhotovoltaicPanelSupport entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        Long matrixId = entity.getMatrixId();
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
            if (matrixId == null) {
                throw new ServiceException("方阵id不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        if (matrixId != null && matrixService.getById(matrixId) == null) {
            throw new ServiceException("对应方阵不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 校验并批量删除设施-光伏板支架信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<FacPhotovoltaicPanelSupport> photovoltaicPanelSupportList = this.listByIds(ids);
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectId = photovoltaicPanelSupportList.stream().map(FacPhotovoltaicPanelSupport::getProjectId).toList();
            projectService.validAuth(projectId, userId);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取设施-光伏板支架视图对象
     *
     * @param photovoltaicPanelSupport 设施-光伏板支架对象
     * @return 设施-光伏板支架视图对象
     */
    @Override
    public FacPhotovoltaicPanelSupportVo getVo(FacPhotovoltaicPanelSupport photovoltaicPanelSupport) {
        // 对象转封装类
        FacPhotovoltaicPanelSupportVo photovoltaicPanelSupportVo = new FacPhotovoltaicPanelSupportVo();
        if (photovoltaicPanelSupport == null) {
            return photovoltaicPanelSupportVo;
        }
        BeanUtils.copyProperties(photovoltaicPanelSupport, photovoltaicPanelSupportVo);
        // 将 JSON 字符串转化为 List
        String positions = photovoltaicPanelSupport.getPositions();
        if (StringUtils.isNotBlank(positions)) {
            List<String> positionList = JSONUtil.toList(positions, String.class);
            photovoltaicPanelSupportVo.setPositionList(positionList);
        }
        return photovoltaicPanelSupportVo;
    }

    /**
     * 获取设施-光伏板支架查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<FacPhotovoltaicPanelSupport> buildQueryWrapper(FacPhotovoltaicPanelSupportQueryReq req) {
        LambdaQueryWrapper<FacPhotovoltaicPanelSupport> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long projectId = req.getProjectId();
        Long matrixId = req.getMatrixId();
        String name = req.getName();
        String status = req.getStatus();
        String finishType = req.getFinishType();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(name), FacPhotovoltaicPanelSupport::getName, name);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(projectId), FacPhotovoltaicPanelSupport::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(matrixId), FacPhotovoltaicPanelSupport::getMatrixId, matrixId);
        lqw.eq(StringUtils.isNotBlank(status), FacPhotovoltaicPanelSupport::getStatus, status);
        lqw.eq(StringUtils.isNotBlank(finishType), FacPhotovoltaicPanelSupport::getFinishType, finishType);
        return lqw;
    }

    /**
     * 获取设施-光伏板支架分页对象视图
     *
     * @param photovoltaicPanelSupportPage 设施-光伏板支架分页对象
     * @return 设施-光伏板支架分页对象视图
     */
    @Override
    public Page<FacPhotovoltaicPanelSupportVo> getVoPage(Page<FacPhotovoltaicPanelSupport> photovoltaicPanelSupportPage) {
        List<FacPhotovoltaicPanelSupport> photovoltaicPanelSupportList = photovoltaicPanelSupportPage.getRecords();
        Page<FacPhotovoltaicPanelSupportVo> photovoltaicPanelSupportVoPage = new Page<>(
            photovoltaicPanelSupportPage.getCurrent(),
            photovoltaicPanelSupportPage.getSize(),
            photovoltaicPanelSupportPage.getTotal());
        if (CollUtil.isEmpty(photovoltaicPanelSupportList)) {
            return photovoltaicPanelSupportVoPage;
        }
        List<FacPhotovoltaicPanelSupportVo> photovoltaicPanelSupportVoList = photovoltaicPanelSupportList.stream().map(this::getVo).toList();
        photovoltaicPanelSupportVoPage.setRecords(photovoltaicPanelSupportVoList);
        return photovoltaicPanelSupportVoPage;
    }

}
