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.FacInverter;
import org.dromara.facility.domain.FacMatrix;
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.dto.inverter.FacInverterCreateByGeoJsonReq;
import org.dromara.facility.domain.dto.inverter.FacInverterCreateReq;
import org.dromara.facility.domain.dto.inverter.FacInverterQueryReq;
import org.dromara.facility.domain.dto.inverter.FacInverterUpdateReq;
import org.dromara.facility.domain.vo.inverter.FacInverterVo;
import org.dromara.facility.mapper.FacInverterMapper;
import org.dromara.facility.service.IFacInverterService;
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 FacInverterServiceImpl extends ServiceImpl<FacInverterMapper, FacInverter>
    implements IFacInverterService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IFacMatrixService matrixService;

    @Resource
    private IPgsProgressCategoryService progressCategoryService;

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

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

    /**
     * 查询符合条件的设施-逆变器列表
     *
     * @param req 查询条件
     * @return 设施-逆变器列表
     */
    @Override
    public List<FacInverterVo> queryList(FacInverterQueryReq req) {
        List<FacInverter> inverterList = this.list(this.buildQueryWrapper(req));
        return inverterList.stream().map(this::getVo).toList();
    }

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

    /**
     * 新增设施-逆变器
     *
     * @param geoJson GeoJson格式
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByGeoJson(FacInverterCreateByGeoJsonReq 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<FacInverter> oldInverterList = this.lambdaQuery()
            .eq(FacInverter::getProjectId, projectId).list();
        Map<String, FacInverter> inverterMap = oldInverterList.stream().collect(Collectors.toMap(
            inverter -> inverter.getName() + "_" + inverter.getProgressCategoryId(),
            Function.identity(),
            (inverter1, inverter2) -> inverter1
        ));
        // 获取所有逆变器对应名称的点
        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.INVERTER_PROGRESS_CATEGORY_WORK_TYPE).list();
        Map<Long, List<PgsProgressCategory>> progressCategoryMap = progressCategoryList.stream()
            .collect(Collectors.groupingBy(PgsProgressCategory::getMatrixId));
        List<FacInverter> inverterList = 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) {
                FacInverter inverter = new FacInverter();
                inverter.setMatrixId(matrix.getId());
                inverter.setName(name);
                inverter.setProjectId(projectId);
                inverter.setPositions(JSONUtil.toJsonStr(coordinates));
                String mapKey = name + "_" + progressCategory.getId();
                // 如果有同名同类别箱变，则获取该箱变完成状态
                if (CollUtil.isNotEmpty(inverterMap) && inverterMap.containsKey(mapKey)) {
                    FacInverter oldInverter = inverterMap.get(mapKey);
                    inverter.setFinishType(oldInverter.getFinishType());
                    inverter.setFinishDate(oldInverter.getFinishDate());
                    inverter.setProgressCategoryId(oldInverter.getProgressCategoryId());
                    inverter.setProgressCategoryName(oldInverter.getProgressCategoryName());
                    inverter.setStatus(oldInverter.getStatus());
                } else {
                    inverter.setProgressCategoryId(progressCategory.getId());
                    inverter.setProgressCategoryName(progressCategory.getName());
                }
                inverterList.add(inverter);
            }
        }
        // 删除旧数据
        if (CollUtil.isNotEmpty(oldInverterList)) {
            boolean result = this.removeBatchByIds(oldInverterList);
            if (!result) {
                throw new ServiceException("删除逆变器失败，数据库异常", HttpStatus.ERROR);
            }
        }
        // 批量保存
        if (CollUtil.isNotEmpty(inverterList)) {
            boolean result = this.saveBatch(inverterList);
            if (!result) {
                throw new ServiceException("新增逆变器失败，数据库异常", HttpStatus.ERROR);
            }
        }
        // 更新数量
        Map<Long, List<FacInverter>> countMap = inverterList
            .stream().collect(Collectors.groupingBy(FacInverter::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(FacInverterUpdateReq req) {
        // 将实体类和 DTO 进行转换
        FacInverter inverter = new FacInverter();
        BeanUtils.copyProperties(req, inverter);
        // 将位置信息转换为 JSON 字符串
        List<String> positionList = req.getPositionList();
        if (ObjectUtils.isNotEmpty(positionList)) {
            String positionStr = JSONUtil.toJsonStr(positionList);
            inverter.setPositions(positionStr);
        }
        // 数据校验
        validEntityBeforeSave(inverter, false);
        // 判断是否存在
        FacInverter oldInverter = this.getById(inverter.getId());
        if (oldInverter == null) {
            throw new ServiceException("修改逆变器失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 判断是否修改名称
        if (!oldInverter.getName().equals(inverter.getName())) {
            Long count = this.lambdaQuery()
                .eq(FacInverter::getProjectId, inverter.getProjectId())
                .eq(FacInverter::getName, inverter.getName())
                .count();
            if (count > 0) {
                throw new ServiceException("该项目已存在同名逆变器", HttpStatus.CONFLICT);
            }
        }
        // 操作数据库
        boolean update = this.updateById(inverter);
        if (!update) {
            throw new ServiceException("修改逆变器失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

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

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

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

    /**
     * 获取设施-逆变器分页对象视图
     *
     * @param inverterPage 设施-逆变器分页对象
     * @return 设施-逆变器分页对象视图
     */
    @Override
    public Page<FacInverterVo> getVoPage(Page<FacInverter> inverterPage) {
        List<FacInverter> inverterList = inverterPage.getRecords();
        Page<FacInverterVo> inverterVoPage = new Page<>(
            inverterPage.getCurrent(),
            inverterPage.getSize(),
            inverterPage.getTotal());
        if (CollUtil.isEmpty(inverterList)) {
            return inverterVoPage;
        }
        List<FacInverterVo> inverterVoList = inverterList.stream().map(this::getVo).toList();
        inverterVoPage.setRecords(inverterVoList);
        return inverterVoPage;
    }

}
