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.FacPhotovoltaicPanelPoint;
import org.dromara.facility.domain.dto.photovoltaicpanelpoint.FacPhotovoltaicPanelPointCreateReq;
import org.dromara.facility.domain.dto.photovoltaicpanelpoint.FacPhotovoltaicPanelPointQueryReq;
import org.dromara.facility.domain.dto.photovoltaicpanelpoint.FacPhotovoltaicPanelPointUpdateReq;
import org.dromara.facility.domain.vo.photovoltaicpanelpoint.FacPhotovoltaicPanelPointVo;
import org.dromara.facility.mapper.FacPhotovoltaicPanelPointMapper;
import org.dromara.facility.service.IFacMatrixService;
import org.dromara.facility.service.IFacPhotovoltaicPanelPointService;
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 FacPhotovoltaicPanelPointServiceImpl extends ServiceImpl<FacPhotovoltaicPanelPointMapper, FacPhotovoltaicPanelPoint>
    implements IFacPhotovoltaicPanelPointService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IFacMatrixService matrixService;

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

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

    /**
     * 查询符合条件的设施-光伏板桩点列表
     *
     * @param req 查询条件
     * @return 设施-光伏板桩点列表
     */
    @Override
    public List<FacPhotovoltaicPanelPointVo> queryList(FacPhotovoltaicPanelPointQueryReq req) {
        List<FacPhotovoltaicPanelPoint> photovoltaicPanelPointList = this.list(this.buildQueryWrapper(req));
        return photovoltaicPanelPointList.stream().map(this::getVo).toList();
    }

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FacPhotovoltaicPanelPoint 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<FacPhotovoltaicPanelPoint> photovoltaicPanelPointList = this.list(this.buildQueryWrapper(null));
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectId = photovoltaicPanelPointList.stream().map(FacPhotovoltaicPanelPoint::getProjectId).toList();
            projectService.validAuth(projectId, userId);
        }
        return this.removeBatchByIds(ids);
    }

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

    /**
     * 获取设施-光伏板桩点查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<FacPhotovoltaicPanelPoint> buildQueryWrapper(FacPhotovoltaicPanelPointQueryReq req) {
        LambdaQueryWrapper<FacPhotovoltaicPanelPoint> 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), FacPhotovoltaicPanelPoint::getName, name);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(projectId), FacPhotovoltaicPanelPoint::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(matrixId), FacPhotovoltaicPanelPoint::getMatrixId, matrixId);
        lqw.eq(StringUtils.isNotBlank(status), FacPhotovoltaicPanelPoint::getStatus, status);
        lqw.eq(StringUtils.isNotBlank(finishType), FacPhotovoltaicPanelPoint::getFinishType, finishType);
        return lqw;
    }

    /**
     * 获取设施-光伏板桩点分页对象视图
     *
     * @param photovoltaicPanelPointPage 设施-光伏板桩点分页对象
     * @return 设施-光伏板桩点分页对象视图
     */
    @Override
    public Page<FacPhotovoltaicPanelPointVo> getVoPage(Page<FacPhotovoltaicPanelPoint> photovoltaicPanelPointPage) {
        List<FacPhotovoltaicPanelPoint> photovoltaicPanelPointList = photovoltaicPanelPointPage.getRecords();
        Page<FacPhotovoltaicPanelPointVo> photovoltaicPanelPointVoPage = new Page<>(
            photovoltaicPanelPointPage.getCurrent(),
            photovoltaicPanelPointPage.getSize(),
            photovoltaicPanelPointPage.getTotal());
        if (CollUtil.isEmpty(photovoltaicPanelPointList)) {
            return photovoltaicPanelPointVoPage;
        }
        List<FacPhotovoltaicPanelPointVo> photovoltaicPanelPointVoList = photovoltaicPanelPointList.stream().map(this::getVo).toList();
        photovoltaicPanelPointVoPage.setRecords(photovoltaicPanelPointVoList);
        return photovoltaicPanelPointVoPage;
    }

}
