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.FacPhotovoltaicPanelColumn;
import org.dromara.facility.domain.dto.photovoltaicpanelcolumn.FacPhotovoltaicPanelColumnCreateReq;
import org.dromara.facility.domain.dto.photovoltaicpanelcolumn.FacPhotovoltaicPanelColumnQueryReq;
import org.dromara.facility.domain.dto.photovoltaicpanelcolumn.FacPhotovoltaicPanelColumnUpdateReq;
import org.dromara.facility.domain.vo.photovoltaicpanelcolumn.FacPhotovoltaicPanelColumnVo;
import org.dromara.facility.mapper.FacPhotovoltaicPanelColumnMapper;
import org.dromara.facility.service.IFacMatrixService;
import org.dromara.facility.service.IFacPhotovoltaicPanelColumnService;
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 FacPhotovoltaicPanelColumnServiceImpl extends ServiceImpl<FacPhotovoltaicPanelColumnMapper, FacPhotovoltaicPanelColumn>
    implements IFacPhotovoltaicPanelColumnService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IFacMatrixService matrixService;

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

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

    /**
     * 查询符合条件的设施-光伏板立柱列表
     *
     * @param req 查询条件
     * @return 设施-光伏板立柱列表
     */
    @Override
    public List<FacPhotovoltaicPanelColumnVo> queryList(FacPhotovoltaicPanelColumnQueryReq req) {
        List<FacPhotovoltaicPanelColumn> photovoltaicPanelColumnList = this.list(this.buildQueryWrapper(req));
        return photovoltaicPanelColumnList.stream().map(this::getVo).toList();
    }

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

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

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

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

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

    /**
     * 获取设施-光伏板立柱分页对象视图
     *
     * @param photovoltaicPanelColumnPage 设施-光伏板立柱分页对象
     * @return 设施-光伏板立柱分页对象视图
     */
    @Override
    public Page<FacPhotovoltaicPanelColumnVo> getVoPage(Page<FacPhotovoltaicPanelColumn> photovoltaicPanelColumnPage) {
        List<FacPhotovoltaicPanelColumn> photovoltaicPanelColumnList = photovoltaicPanelColumnPage.getRecords();
        Page<FacPhotovoltaicPanelColumnVo> photovoltaicPanelColumnVoPage = new Page<>(
            photovoltaicPanelColumnPage.getCurrent(),
            photovoltaicPanelColumnPage.getSize(),
            photovoltaicPanelColumnPage.getTotal());
        if (CollUtil.isEmpty(photovoltaicPanelColumnList)) {
            return photovoltaicPanelColumnVoPage;
        }
        List<FacPhotovoltaicPanelColumnVo> photovoltaicPanelColumnVoList = photovoltaicPanelColumnList.stream().map(this::getVo).toList();
        photovoltaicPanelColumnVoPage.setRecords(photovoltaicPanelColumnVoList);
        return photovoltaicPanelColumnVoPage;
    }

}
