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.constant.FacRedisKeyConstant;
import org.dromara.facility.domain.*;
import org.dromara.facility.domain.dto.geojson.*;
import org.dromara.facility.domain.dto.matrix.*;
import org.dromara.facility.domain.enums.FacFinishStatusEnum;
import org.dromara.facility.domain.vo.matrix.FacMatrixDetailGisVo;
import org.dromara.facility.domain.vo.matrix.FacMatrixVo;
import org.dromara.facility.mapper.FacMatrixMapper;
import org.dromara.facility.service.*;
import org.dromara.progress.domain.PgsProgressCategory;
import org.dromara.progress.service.IPgsProgressCategoryService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.utils.JSTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 设施-方阵Service业务层处理
 *
 * @author lcj
 * @date 2025-04-21
 */
@Service
public class FacMatrixServiceImpl extends ServiceImpl<FacMatrixMapper, FacMatrix>
    implements IFacMatrixService {

    @Resource
    private IBusProjectService projectService;

    @Lazy
    @Resource
    private IFacPhotovoltaicPanelService photovoltaicPanelService;

    @Lazy
    @Resource
    private IFacPhotovoltaicPanelPartsService photovoltaicPanelPartsService;

    @Lazy
    @Resource
    private IFacPhotovoltaicPanelPointService photovoltaicPanelPointService;

    @Lazy
    @Resource
    private IFacPhotovoltaicPanelColumnService photovoltaicPanelColumnService;

    @Lazy
    @Resource
    private IFacPhotovoltaicPanelSupportService photovoltaicPanelSupportService;

    @Lazy
    @Resource
    private IFacBoxTransformerService boxTransformerService;

    @Lazy
    @Resource
    private IFacInverterService inverterService;

    @Lazy
    @Resource
    private IPgsProgressCategoryService progressCategoryService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 查询设施-方阵
     *
     * @param id 主键
     * @return 设施-方阵
     */
    @Override
    public FacMatrixVo queryById(Long id) {
        FacMatrix matrix = this.getById(id);
        if (matrix == null) {
            throw new ServiceException("查询方阵失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(matrix);
    }

    /**
     * 分页查询设施-方阵列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 设施-方阵分页列表
     */
    @Override
    public TableDataInfo<FacMatrixVo> queryPageList(FacMatrixQueryReq req, PageQuery pageQuery) {
        Page<FacMatrix> result = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的设施-方阵列表
     *
     * @param req 查询条件
     * @return 设施-方阵列表
     */
    @Override
    public List<FacMatrixVo> queryList(FacMatrixQueryReq req) {
        List<FacMatrix> matrixList = this.list(this.buildQueryWrapper(req));
        return matrixList.stream().map(this::getVo).toList();
    }

    /**
     * 获取大屏方阵详情信息
     *
     * @param req 获取大屏方阵详情信息参数
     * @return 大屏方阵详情信息
     */
    @Override
    public FacMatrixDetailGisVo getMatrixDetailGis(FacMatrixDetailGisReq req) {
        Long projectId = req.getProjectId();
        if (projectId == null || projectService.getById(projectId) == null) {
            throw new ServiceException("项目不存在", HttpStatus.NOT_FOUND);
        }
        Long matrixId = req.getMatrixId();
        FacMatrixDetailGisVo matrixDetailGisVo = new FacMatrixDetailGisVo();
        // 获取箱变数量
        List<FacBoxTransformer> boxTransformerList = boxTransformerService.lambdaQuery()
            .select(FacBoxTransformer::getId, FacBoxTransformer::getStatus)
            .eq(FacBoxTransformer::getProjectId, projectId)
            .eq(ObjectUtils.isNotEmpty(matrixId), FacBoxTransformer::getMatrixId, matrixId)
            .list();
        if (CollUtil.isNotEmpty(boxTransformerList)) {
            matrixDetailGisVo.setBoxTransformerCount((long) boxTransformerList.size());
            matrixDetailGisVo.setBoxTransformerFinishCount(boxTransformerList.stream()
                .filter(boxTransformer ->
                    FacFinishStatusEnum.FINISH.getValue().equals(boxTransformer.getStatus())).count());
        }
        // 获取逆变器数量
        List<FacInverter> inverterList = inverterService.lambdaQuery()
            .select(FacInverter::getId, FacInverter::getStatus)
            .eq(FacInverter::getProjectId, projectId)
            .eq(ObjectUtils.isNotEmpty(matrixId), FacInverter::getMatrixId, matrixId)
            .list();
        if (CollUtil.isNotEmpty(inverterList)) {
            matrixDetailGisVo.setInverterCount((long) inverterList.size());
            matrixDetailGisVo.setInverterFinishCount(inverterList.stream()
                .filter(inverter ->
                    FacFinishStatusEnum.FINISH.getValue().equals(inverter.getStatus())).count());
        }
        // 获取光伏板数量
        List<FacPhotovoltaicPanel> photovoltaicPanelList = photovoltaicPanelService.lambdaQuery()
            .select(FacPhotovoltaicPanel::getId, FacPhotovoltaicPanel::getStatus)
            .eq(FacPhotovoltaicPanel::getProjectId, projectId)
            .eq(ObjectUtils.isNotEmpty(matrixId), FacPhotovoltaicPanel::getMatrixId, matrixId)
            .list();
        if (CollUtil.isNotEmpty(photovoltaicPanelList)) {
            matrixDetailGisVo.setPhotovoltaicPanelCount((long) photovoltaicPanelList.size());
            matrixDetailGisVo.setPhotovoltaicPanelFinishCount(photovoltaicPanelList.stream()
                .filter(photovoltaicPanel ->
                    FacFinishStatusEnum.FINISH.getValue().equals(photovoltaicPanel.getStatus())).count());
        }
        // 获取光伏板点数量
        List<FacPhotovoltaicPanelPoint> photovoltaicPanelPointList = photovoltaicPanelPointService.lambdaQuery()
            .select(FacPhotovoltaicPanelPoint::getId, FacPhotovoltaicPanelPoint::getStatus)
            .eq(FacPhotovoltaicPanelPoint::getProjectId, projectId)
            .eq(ObjectUtils.isNotEmpty(matrixId), FacPhotovoltaicPanelPoint::getMatrixId, matrixId)
            .list();
        if (CollUtil.isNotEmpty(photovoltaicPanelPointList)) {
            matrixDetailGisVo.setPointCount((long) photovoltaicPanelPointList.size());
            matrixDetailGisVo.setPointFinishCount(photovoltaicPanelPointList.stream()
                .filter(photovoltaicPanelPoint ->
                    FacFinishStatusEnum.FINISH.getValue().equals(photovoltaicPanelPoint.getStatus())).count());
        }
        // 获取支架数量
        List<FacPhotovoltaicPanelSupport> photovoltaicPanelSupportList = photovoltaicPanelSupportService.lambdaQuery()
            .select(FacPhotovoltaicPanelSupport::getId, FacPhotovoltaicPanelSupport::getStatus)
            .eq(FacPhotovoltaicPanelSupport::getProjectId, projectId)
            .eq(ObjectUtils.isNotEmpty(matrixId), FacPhotovoltaicPanelSupport::getMatrixId, matrixId)
            .list();
        if (CollUtil.isNotEmpty(photovoltaicPanelSupportList)) {
            matrixDetailGisVo.setSupportCount((long) photovoltaicPanelSupportList.size());
            matrixDetailGisVo.setSupportFinishCount(photovoltaicPanelSupportList.stream()
                .filter(photovoltaicPanelSupport ->
                    FacFinishStatusEnum.FINISH.getValue().equals(photovoltaicPanelSupport.getStatus())).count());
        }
        // 获取立柱数量
        List<FacPhotovoltaicPanelColumn> photovoltaicPanelColumnList = photovoltaicPanelColumnService.lambdaQuery()
            .select(FacPhotovoltaicPanelColumn::getId, FacPhotovoltaicPanelColumn::getStatus)
            .eq(FacPhotovoltaicPanelColumn::getProjectId, projectId)
            .eq(ObjectUtils.isNotEmpty(matrixId), FacPhotovoltaicPanelColumn::getMatrixId, matrixId)
            .list();
        if (CollUtil.isNotEmpty(photovoltaicPanelColumnList)) {
            matrixDetailGisVo.setColumnCount((long) photovoltaicPanelColumnList.size());
            matrixDetailGisVo.setColumnFinishCount(photovoltaicPanelColumnList.stream()
                .filter(photovoltaicPanelColumn ->
                    FacFinishStatusEnum.FINISH.getValue().equals(photovoltaicPanelColumn.getStatus())).count());
        }
        return matrixDetailGisVo;
    }

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

    /**
     * 新增设施-方阵
     *
     * @param geoJson GeoJson格式
     * @return 新增方阵id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByGeoJson(FacMatrixCreateByGeoJsonReq geoJson) {
        // 判断当前项目是否正在执行桩点、立柱、支架数据
        String operationRedisKey = FacRedisKeyConstant.getInOperationByProjectRedisKey(geoJson.getProjectId());
        // 判断 redis key 是否存在，存在则返回
        Object object = redisTemplate.opsForValue().get(operationRedisKey);
        if (object != null && (Boolean) object) {
            throw new ServiceException("项目下桩点、立柱、支架数据正在处理中，请等待处理完毕后操作", HttpStatus.BAD_REQUEST);
        }
        Long projectId = geoJson.getProjectId();
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("项目不存在", HttpStatus.NOT_FOUND);
        }
        // 获取当前项目下方阵信息
        List<FacMatrix> oldMatrixList = this.lambdaQuery()
            .eq(FacMatrix::getProjectId, projectId).list();
        List<FacMatrix> matrixList = new ArrayList<>();
        List<FacGeoJson> locationGeoJsonList = geoJson.getLocationGeoJson();
        List<FacFeature> locationFeatures = new ArrayList<>();
        for (FacGeoJson geoJsonByPoint : locationGeoJsonList) {
            locationFeatures.addAll(geoJsonByPoint.getFeatures());
        }
        // 获取所有对应名称的点
        List<FacGeoJsonByPoint> nameGeoJsonList = geoJson.getNameGeoJson();
        List<FacFeatureByPoint> nameFeatures = new ArrayList<>();
        for (FacGeoJsonByPoint geoJsonByPoint : nameGeoJsonList) {
            nameFeatures.addAll(geoJsonByPoint.getFeatures());
        }
        // 遍历位置信息
        for (FacFeature feature : locationFeatures) {
            FacMatrix matrix = new FacMatrix();
            matrix.setProjectId(projectId);
            FacGeometry geometry = feature.getGeometry();
            // 获取坐标信息
            List<List<Double>> coordinatesList = JSTUtils.getTwoDimensionalCoordinates(geometry);
            // 获取方阵名称
            String nameStr = JSTUtils.findNearestPointText(coordinatesList, nameFeatures);
            String name = nameStr.split(" ")[0];
            if (name == null) {
                continue;
            }
            // 将位置信息转换为 JSON 字符串
            String positionStr = JSONUtil.toJsonStr(coordinatesList);
            matrix.setPositions(positionStr);
            matrix.setMatrixName(name);
            matrixList.add(matrix);
        }
        // todo 关联数据处理
        if (CollUtil.isNotEmpty(oldMatrixList)) {
            boolean result = this.removeBatchByIds(oldMatrixList);
            if (!result) {
                throw new ServiceException("删除老方阵失败，数据库异常", HttpStatus.ERROR);
            }
            LambdaQueryWrapper<PgsProgressCategory> lqw = new LambdaQueryWrapper<>();
            lqw.eq(PgsProgressCategory::getProjectId, projectId)
                .in(PgsProgressCategory::getMatrixId, oldMatrixList.stream().map(FacMatrix::getId).toList());
            List<PgsProgressCategory> progressCategories = progressCategoryService.list(lqw);
            if (CollUtil.isNotEmpty(progressCategories)) {
                boolean remove = progressCategoryService.remove(lqw);
                if (!remove) {
                    throw new ServiceException("删除老方阵进度分类失败，数据库异常", HttpStatus.ERROR);
                }
            }
        }
        if (CollUtil.isNotEmpty(matrixList)) {
            boolean result = this.saveBatch(matrixList);
            if (!result) {
                throw new ServiceException("批量新增方阵失败，数据库异常", HttpStatus.ERROR);
            }
            List<Long> matrixIdList = matrixList.stream().map(FacMatrix::getId).toList();
            Boolean save = progressCategoryService.insertByTemplate(projectId, matrixIdList);
            if (!save) {
                throw new ServiceException("批量新增方阵进度分类失败，数据库异常", HttpStatus.ERROR);
            }
        }
        return true;
    }

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FacMatrix entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && projectService.getById(projectId) == 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<FacMatrix> matrixList = this.listByIds(ids);
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectIds = matrixList.stream().map(FacMatrix::getProjectId).distinct().toList();
            if (CollUtil.isNotEmpty(projectIds) && projectIds.size() > 1) {
                throw new ServiceException("仅能删除单个项目下的方阵", HttpStatus.BAD_REQUEST);
            }
            Long projectId = projectIds.getFirst();
            projectService.validAuth(projectId, userId);
            // 判断方阵下是否存在光伏板信息
            Long photovoltaicPanelCount = photovoltaicPanelService.lambdaQuery()
                .eq(FacPhotovoltaicPanel::getProjectId, projectId)
                .in(FacPhotovoltaicPanel::getMatrixId, ids).count();
            if (photovoltaicPanelCount > 0) {
                throw new ServiceException("删除失败，方阵下存在光伏板信息", HttpStatus.CONFLICT);
            }
            // 判断方阵下是否存在箱变信息
            Long boxTransformerCount = boxTransformerService.lambdaQuery()
                .eq(FacBoxTransformer::getProjectId, projectId)
                .in(FacBoxTransformer::getMatrixId, ids).count();
            if (boxTransformerCount > 0) {
                throw new ServiceException("删除失败，方阵下存在箱变信息", HttpStatus.CONFLICT);
            }
            // 判断方阵下是否存在逆变器信息
            Long inverterCount = inverterService.lambdaQuery()
                .eq(FacInverter::getProjectId, projectId)
                .in(FacInverter::getMatrixId, ids).count();
            if (inverterCount > 0) {
                throw new ServiceException("删除失败，方阵下存在逆变器信息", HttpStatus.CONFLICT);
            }
            // 判断方阵下是否存在光伏板点信息
            Boolean result = photovoltaicPanelPartsService.validPartsExistByMatrix(projectId, ids);
            if (result) {
                throw new ServiceException("删除失败，方阵下存在光伏板点信息", HttpStatus.CONFLICT);
            }
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取设施-方阵视图对象
     *
     * @param matrix 设施-方阵对象
     * @return 设施-方阵视图对象
     */
    @Override
    public FacMatrixVo getVo(FacMatrix matrix) {
        // 对象转封装类
        FacMatrixVo matrixVo = new FacMatrixVo();
        if (matrix == null) {
            return matrixVo;
        }
        BeanUtils.copyProperties(matrix, matrixVo);
        // 将 JSON 字符串转化为 List
        String positions = matrix.getPositions();
        if (StringUtils.isNotBlank(positions)) {
            List<List<String>> positionList = new ArrayList<>();
            List<String> arr = JSONUtil.toList(positions, String.class);
            for (String s : arr) {
                positionList.add(JSONUtil.toList(s, String.class));
            }
            matrixVo.setPositionList(positionList);
        }
        return matrixVo;
    }

    /**
     * 获取设施-方阵查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<FacMatrix> buildQueryWrapper(FacMatrixQueryReq req) {
        LambdaQueryWrapper<FacMatrix> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long projectId = req.getProjectId();
        String matrixName = req.getMatrixName();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(matrixName), FacMatrix::getMatrixName, matrixName);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(projectId), FacMatrix::getProjectId, projectId);
        return lqw;
    }

    /**
     * 获取设施-方阵分页对象视图
     *
     * @param matrixPage 设施-方阵分页对象
     * @return 设施-方阵分页对象视图
     */
    @Override
    public Page<FacMatrixVo> getVoPage(Page<FacMatrix> matrixPage) {
        List<FacMatrix> matrixList = matrixPage.getRecords();
        Page<FacMatrixVo> matrixVoPage = new Page<>(
            matrixPage.getCurrent(),
            matrixPage.getSize(),
            matrixPage.getTotal());
        if (CollUtil.isEmpty(matrixList)) {
            return matrixVoPage;
        }
        List<FacMatrixVo> matrixVoList = matrixList.stream().map(this::getVo).toList();
        matrixVoPage.setRecords(matrixVoList);
        return matrixVoPage;
    }

    /**
     * 根据坐标获取符合的方阵
     *
     * @param matrixList  方阵集合
     * @param coordinates 坐标
     * @return 符合的方阵
     */
    @Override
    public FacMatrix getMatrixIdByCoordinates(List<FacMatrix> matrixList, List<Double> coordinates) {
        // 判断在哪个方阵里
        FacMatrix matchMatrix = null;
        for (FacMatrix matrix : matrixList) {
            String positions = matrix.getPositions();
            List<List<Double>> positionList = new ArrayList<>();
            List<String> arr = JSONUtil.toList(positions, String.class);
            for (String s : arr) {
                positionList.add(JSONUtil.toList(s, Double.class));
            }
            Boolean result = JSTUtils.pointIsWithInPlane(positionList, coordinates);
            if (result) {
                matchMatrix = matrix;
                break;
            }
        }
        return matchMatrix;
    }

    /**
     * 根据二维坐标获取符合的方阵
     *
     * @param matrixList  方阵集合
     * @param coordinates 坐标
     * @return 符合的方阵
     */
    @Override
    public FacMatrix getMatrixIdBy2Coordinates(List<FacMatrix> matrixList, List<List<Double>> coordinates) {
        FacMatrix matchMatrix = null;
        for (FacMatrix matrix : matrixList) {
            String positions = matrix.getPositions();
            List<List<Double>> positionList = new ArrayList<>();
            List<String> arr = JSONUtil.toList(positions, String.class);
            for (String s : arr) {
                positionList.add(JSONUtil.toList(s, Double.class));
            }
            Boolean result = JSTUtils.planeIsWithInPlane(positionList, coordinates);
            if (result) {
                matchMatrix = matrix;
                break;
            } else {
                Boolean areResult = JSTUtils.arePolygonsIntersecting(positionList, coordinates);
                if (areResult) {
                    matchMatrix = matrix;
                    break;
                }
            }
        }
        return matchMatrix;
    }

}
