package com.yuchen.saas.park.service.service.fire.inspect.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectLineManageSubmitReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectLineManageReqDTO;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectLineManage;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectLocation;
import com.yuchen.saas.park.api.vo.fire.inspect.FireInspectLocationVO;
import com.yuchen.saas.park.api.vo.fire.inspect.FireInspectLineManageVO;
import com.yuchen.saas.park.service.mapper.fire.inspect.SaasParkFireInspectLineManageMapper;
import com.yuchen.saas.park.service.service.fire.inspect.ISaasParkFireInspectLineManageService;
import com.yuchen.saas.park.service.service.fire.inspect.ISaasParkFireInspectLocationService;
import com.yuchen.saas.park.service.util.PageConverterUtils;
import lombok.RequiredArgsConstructor;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseEntity;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.NestPage;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhouhanwei
 * @since 2024-04-01
 */
@Service
@RequiredArgsConstructor
public class SaasParkFireInspectLineManageServiceImpl extends BaseServiceImpl<SaasParkFireInspectLineManageMapper, SaasParkFireInspectLineManage> implements ISaasParkFireInspectLineManageService {

    private final ISaasParkFireInspectLocationService locationService;

    @Override
    public NestPage<FireInspectLineManageVO> findFireInspectLineManagePage(FireInspectLineManageReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        Long customerId = contextUser.getCustomerManageId();
        Page<FireInspectLineManageVO> resultPage = new Page<>();
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectLineManage> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectLineManage::getCustomerId, customerId);
        lambdaWrapper.eq(Objects.nonNull(reqDTO.getProjectId()), SaasParkFireInspectLineManage::getProjectId, reqDTO.getProjectId());
        lambdaWrapper.like(StrUtil.isNotBlank(reqDTO.getInspectLineName()), SaasParkFireInspectLineManage::getInspectLineName, reqDTO.getInspectLineName());
        lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        IPage<SaasParkFireInspectLineManage> page = page(Condition.getPage(reqDTO),lambdaWrapper);
        List<SaasParkFireInspectLineManage> fireInspectLineManageList = page.getRecords();
        // 根据客户id及管理区id获取当前点位位置列表
        List<SaasParkFireInspectLocation> locationList = locationService.list(new LambdaQueryWrapper<SaasParkFireInspectLocation>()
                .eq(SaasParkFireInspectLocation::getCustomerId, customerId)
                .eq(Objects.nonNull(reqDTO.getProjectId()), SaasParkFireInspectLocation::getProjectId, reqDTO.getProjectId()));
        // 数据列表
        List<FireInspectLineManageVO> resultList = new ArrayList<>();
        for (SaasParkFireInspectLineManage saasParkFireInspectLineManage : fireInspectLineManageList) {
            FireInspectLineManageVO vo = new FireInspectLineManageVO();
            BeanUtil.copyProperties(saasParkFireInspectLineManage, vo);
            // 赋值空间点位信息
            setLineLocationInfo(vo, locationList);
            resultList.add(vo);
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultList);
        return PageConverterUtils.convert(resultPage);
    }

    @Override
    public FireInspectLineManageVO getFireInspectLineManageById(Long inspectLineManageId) {
        FireInspectLineManageVO vo = new FireInspectLineManageVO();
        SaasParkFireInspectLineManage saasParkFireInspectLineManage = getById(inspectLineManageId);
        if (Objects.isNull(saasParkFireInspectLineManage)) {
            throw new ServiceException("巡检线路管理详情数据不存在");
        }
        BeanUtil.copyProperties(saasParkFireInspectLineManage, vo);
        // 获取巡检点位列表
        String[] locations = vo.getInspectLocations().split(",");
        List<Long> locationIdList = Arrays.stream(locations).map(Long::parseLong).collect(Collectors.toList());
        List<FireInspectLocationVO> locationList = locationService.findFireInspectLocationList(locationIdList);
        vo.setFireInspectLocationVOList(locationList);
        return vo;
    }

    @Override
    public Boolean addFireInspectLineManage(FireInspectLineManageSubmitReqDTO reqDTO) {
        if (CollUtil.isEmpty(reqDTO.getInspectLocationIdList())) {
            throw new ServiceException("请选择巡检位置定位");
        }
        SaasParkFireInspectLineManage saasParkFireInspectLineManage = new SaasParkFireInspectLineManage();
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectLineManage);
        String inspectLocations = CollUtil.join(reqDTO.getInspectLocationIdList(), ",");
        saasParkFireInspectLineManage.setInspectLocations(inspectLocations);
        // 判断去重
        validRepeat(saasParkFireInspectLineManage);
        saasParkFireInspectLineManage.setCustomerId(AuthUtil.getUser().getCustomerManageId());
        saasParkFireInspectLineManage.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        return save(saasParkFireInspectLineManage);
    }


    @Override
    public Boolean editFireInspectLineManage(FireInspectLineManageSubmitReqDTO reqDTO) {
        if (CollUtil.isEmpty(reqDTO.getInspectLocationIdList())) {
            throw new ServiceException("请选择巡检位置定位");
        }
        SaasParkFireInspectLineManage saasParkFireInspectLineManage = getById(reqDTO.getId());
        if (Objects.isNull(saasParkFireInspectLineManage)) {
            throw new ServiceException("巡检线路管理详情数据不存在");
        }
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectLineManage);
        String inspectLocations = CollUtil.join(reqDTO.getInspectLocationIdList(), ",");
        saasParkFireInspectLineManage.setInspectLocations(inspectLocations);
        // 判断去重
        validRepeat(saasParkFireInspectLineManage);
        saasParkFireInspectLineManage.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
        return updateById(saasParkFireInspectLineManage);
    }

    @Override
    public Boolean removeFireInspectLineManage(Long inspectLineManageId) {
        SaasParkFireInspectLineManage saasParkFireInspectLineManage = getById(inspectLineManageId);
        if (Objects.isNull(saasParkFireInspectLineManage)) {
            throw new ServiceException("巡检线路管理详情数据不存在");
        }
        return removeById(inspectLineManageId);
    }

    private void validRepeat(SaasParkFireInspectLineManage saasParkFireInspectLineManage) {
        int count = count(new LambdaQueryWrapper<SaasParkFireInspectLineManage>()
                .eq(SaasParkFireInspectLineManage::getInspectLineName, saasParkFireInspectLineManage.getInspectLineName())
                .eq(Objects.nonNull(saasParkFireInspectLineManage.getProjectId()), SaasParkFireInspectLineManage::getProjectId, saasParkFireInspectLineManage.getProjectId())
                .notIn(Objects.nonNull(saasParkFireInspectLineManage.getId()), BaseEntity::getId, saasParkFireInspectLineManage.getId()));
        if (count > 0) {
            throw new ServiceException("巡检线路名称不能重复");
        }
    }

    private void setLineLocationInfo(FireInspectLineManageVO vo, List<SaasParkFireInspectLocation> locationList) {
        String[] locations = vo.getInspectLocations().split(",");
        List<Long> locationIdList = Arrays.stream(locations).map(Long::parseLong).collect(Collectors.toList());
        List<String> inspectLocationNames = new ArrayList<>();
        for (SaasParkFireInspectLocation saasParkFireInspectLocation : locationList) {
            if (locationIdList.contains(saasParkFireInspectLocation.getId())) {
                inspectLocationNames.add(saasParkFireInspectLocation.getInspectLocationName());
            }
        }
        vo.setInspectLocationCount(inspectLocationNames.size());
        vo.setInspectLocationNames(CollUtil.join(inspectLocationNames, "->"));
    }
}
