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.FacBoxTransformer;
import org.dromara.facility.domain.FacMatrix;
import org.dromara.facility.domain.dto.boxtransformer.FacBoxTransformerCreateByGeoJsonReq;
import org.dromara.facility.domain.dto.boxtransformer.FacBoxTransformerCreateReq;
import org.dromara.facility.domain.dto.boxtransformer.FacBoxTransformerQueryReq;
import org.dromara.facility.domain.dto.boxtransformer.FacBoxTransformerUpdateReq;
import org.dromara.facility.domain.dto.geojson.FacFeatureByPoint;
import org.dromara.facility.domain.dto.geojson.FacGeoJsonByPoint;
import org.dromara.facility.domain.dto.geojson.FacGeometryByPoint;
import org.dromara.facility.domain.vo.boxtransformer.FacBoxTransformerVo;
import org.dromara.facility.mapper.FacBoxTransformerMapper;
import org.dromara.facility.service.IFacBoxTransformerService;
import org.dromara.facility.service.IFacMatrixService;
import org.dromara.progress.constant.PgsProgressCategoryConstant;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 设施-箱变Service业务层处理
 *
 * @author lcj
 * @date 2025-04-21
 */
@Service
public class FacBoxTransformerServiceImpl extends ServiceImpl<FacBoxTransformerMapper, FacBoxTransformer>
    implements IFacBoxTransformerService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IFacMatrixService matrixService;

    @Resource
    private IPgsProgressCategoryService progressCategoryService;

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

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

    /**
     * 查询符合条件的设施-箱变列表
     *
     * @param req 查询条件
     * @return 设施-箱变列表
     */
    @Override
    public List<FacBoxTransformerVo> queryList(FacBoxTransformerQueryReq req) {
        List<FacBoxTransformer> boxTransformerList = this.list(this.buildQueryWrapper(req));
        return boxTransformerList.stream().map(this::getVo).toList();
    }

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

    /**
     * 新增设施-箱变
     *
     * @param geoJson GeoJson格式
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByGeoJson(FacBoxTransformerCreateByGeoJsonReq geoJson) {
        Long projectId = geoJson.getProjectId();
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("项目不存在", HttpStatus.NOT_FOUND);
        }
        // 获取当前项目下方阵信息
        List<FacMatrix> matrixList = matrixService.lambdaQuery()
            .eq(FacMatrix::getProjectId, projectId).list();
        if (CollUtil.isEmpty(matrixList)) {
            throw new ServiceException("项目下无方阵数据，请先创建方阵信息后再添加箱变信息", HttpStatus.NOT_FOUND);
        }
        // 获取箱变信息
        List<FacBoxTransformer> oldBoxTransformerList = this.lambdaQuery()
            .eq(FacBoxTransformer::getProjectId, projectId).list();
        Map<String, FacBoxTransformer> boxTransformerMap = oldBoxTransformerList.stream().collect(Collectors.toMap(
            boxTransformer -> boxTransformer.getName() + "_" + boxTransformer.getProgressCategoryId(),
            Function.identity(),
            (boxTransformer1, boxTransformer2) -> boxTransformer1
        ));
        // 获取箱变地理信息
        List<FacGeoJsonByPoint> locationGeoJsonList = geoJson.getLocationGeoJson();
        List<FacFeatureByPoint> locationGeoJson = new ArrayList<>();
        for (FacGeoJsonByPoint geoJsonByPoint : locationGeoJsonList) {
            locationGeoJson.addAll(geoJsonByPoint.getFeatures());
        }
        // 获取所有对应名称的点
        List<FacGeoJsonByPoint> nameGeoJsonList = geoJson.getNameGeoJson();
        List<FacFeatureByPoint> nameGeoJson = new ArrayList<>();
        for (FacGeoJsonByPoint geoJsonByPoint : nameGeoJsonList) {
            nameGeoJson.addAll(geoJsonByPoint.getFeatures());
        }
        // 获取进度类别信息
        List<PgsProgressCategory> progressCategoryList = progressCategoryService.lambdaQuery()
            .in(PgsProgressCategory::getWorkType, PgsProgressCategoryConstant.BOX_TRANSFORMER_PROGRESS_CATEGORY_WORK_TYPE).list();
        Map<Long, List<PgsProgressCategory>> progressCategoryMap = progressCategoryList
            .stream().collect(Collectors.groupingBy(PgsProgressCategory::getMatrixId));
        List<FacBoxTransformer> boxTransformerList = new ArrayList<>();
        for (FacFeatureByPoint locationFeature : locationGeoJson) {
            FacGeometryByPoint geometry = locationFeature.getGeometry();
            List<Double> coordinates = geometry.getCoordinates();
            // 判断箱变在哪个方阵里
            FacMatrix matrix = matrixService.getMatrixIdByCoordinates(matrixList, coordinates);
            if (matrix == null) {
                continue;
            }
            // 获取箱变名称
            String name = JSTUtils.findNearestText(coordinates, nameGeoJson);
            if (name == null) {
                continue;
            }
            // 根据进度类别创建
            Long matrixId = matrix.getId();
            List<PgsProgressCategory> progressCategoryListByMatrix = progressCategoryMap.get(matrixId);
            for (PgsProgressCategory progressCategory : progressCategoryListByMatrix) {
                FacBoxTransformer boxTransformer = new FacBoxTransformer();
                boxTransformer.setMatrixId(matrix.getId());
                boxTransformer.setName(name);
                boxTransformer.setProjectId(projectId);
                boxTransformer.setPositions(JSONUtil.toJsonStr(coordinates));
                String mapKey = name + "_" + progressCategory.getId();
                // 如果有同名同类别箱变，则获取该箱变完成状态
                if (CollUtil.isNotEmpty(boxTransformerMap) && boxTransformerMap.containsKey(mapKey)) {
                    FacBoxTransformer oldBoxTransformer = boxTransformerMap.get(mapKey);
                    boxTransformer.setFinishType(oldBoxTransformer.getFinishType());
                    boxTransformer.setFinishDate(oldBoxTransformer.getFinishDate());
                    boxTransformer.setProgressCategoryId(oldBoxTransformer.getProgressCategoryId());
                    boxTransformer.setProgressCategoryName(oldBoxTransformer.getProgressCategoryName());
                    boxTransformer.setStatus(oldBoxTransformer.getStatus());
                } else {
                    boxTransformer.setProgressCategoryId(progressCategory.getId());
                    boxTransformer.setProgressCategoryName(progressCategory.getName());
                }
                boxTransformerList.add(boxTransformer);
            }
        }
        // 删除旧数据
        if (CollUtil.isNotEmpty(oldBoxTransformerList)) {
            boolean result = this.removeBatchByIds(oldBoxTransformerList);
            if (!result) {
                throw new ServiceException("删除箱变失败，数据库异常", HttpStatus.ERROR);
            }
        }
        // 批量保存
        if (CollUtil.isNotEmpty(boxTransformerList)) {
            boolean result = this.saveBatch(boxTransformerList);
            if (!result) {
                throw new ServiceException("新增箱变失败，数据库异常", HttpStatus.ERROR);
            }
        }
        // 更新数量
        Map<Long, List<FacBoxTransformer>> countMap = boxTransformerList
            .stream().collect(Collectors.groupingBy(FacBoxTransformer::getProgressCategoryId));
        for (PgsProgressCategory progressCategory : progressCategoryList) {
            Long progressCategoryId = progressCategory.getId();
            int total = 0;
            if (countMap.containsKey(progressCategoryId)) {
                total = countMap.get(progressCategoryId).size();
            }
            progressCategory.setTotal(BigDecimal.valueOf(total));
        }
        boolean result = progressCategoryService.updateBatchById(progressCategoryList);
        if (!result) {
            throw new ServiceException("更新进度类别失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

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

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

    /**
     * 获取设施-箱变视图对象
     *
     * @param boxTransformer 设施-箱变对象
     * @return 设施-箱变视图对象
     */
    @Override
    public FacBoxTransformerVo getVo(FacBoxTransformer boxTransformer) {
        // 对象转封装类
        FacBoxTransformerVo boxTransformerVo = new FacBoxTransformerVo();
        if (boxTransformer == null) {
            return boxTransformerVo;
        }
        BeanUtils.copyProperties(boxTransformer, boxTransformerVo);
        // 将 JSON 字符串转化为 List
        String positions = boxTransformer.getPositions();
        if (StringUtils.isNotBlank(positions)) {
            List<String> positionList = JSONUtil.toList(positions, String.class);
            boxTransformerVo.setPositionList(positionList);
        }
        return boxTransformerVo;
    }

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

    /**
     * 获取设施-箱变分页对象视图
     *
     * @param boxTransformerPage 设施-箱变分页对象
     * @return 设施-箱变分页对象视图
     */
    @Override
    public Page<FacBoxTransformerVo> getVoPage(Page<FacBoxTransformer> boxTransformerPage) {
        List<FacBoxTransformer> boxTransformerList = boxTransformerPage.getRecords();
        Page<FacBoxTransformerVo> boxTransformerVoPage = new Page<>(
            boxTransformerPage.getCurrent(),
            boxTransformerPage.getSize(),
            boxTransformerPage.getTotal());
        if (CollUtil.isEmpty(boxTransformerList)) {
            return boxTransformerVoPage;
        }
        List<FacBoxTransformerVo> boxTransformerVoList = boxTransformerList.stream().map(this::getVo).toList();
        boxTransformerVoPage.setRecords(boxTransformerVoList);
        return boxTransformerVoPage;
    }

}
