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.thinkunion.park.service.common.utils.ReceiptCodeUtil;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectLocationReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectLocationSubmitReqDTO;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectLocation;
import com.yuchen.saas.park.api.entity.park.PmgBatPointLocationInfo;
import com.yuchen.saas.park.api.vo.fire.inspect.FireInspectLocationVO;
import com.yuchen.saas.park.service.mapper.fire.inspect.SaasParkFireInspectLocationMapper;
import com.yuchen.saas.park.service.service.PmgBatPointLocationInfoService;
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.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhouhanwei
 * @since 2024-04-01
 */
@Service
@RequiredArgsConstructor
public class SaasParkFireInspectLocationServiceImpl extends BaseServiceImpl<SaasParkFireInspectLocationMapper, SaasParkFireInspectLocation> implements ISaasParkFireInspectLocationService {

    private final PmgBatPointLocationInfoService pmgBatPointLocationInfoService;

    @Override
    public NestPage<FireInspectLocationVO> findFireInspectLocationPage(FireInspectLocationReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        Page<FireInspectLocationVO> resultPage = new Page<>();
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectLocation> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectLocation::getCustomerId, contextUser.getCustomerManageId());
        lambdaWrapper.eq(Objects.nonNull(reqDTO.getProjectId()), SaasParkFireInspectLocation::getProjectId, reqDTO.getProjectId());
        lambdaWrapper.like(StrUtil.isNotBlank(reqDTO.getInspectLocationName()), SaasParkFireInspectLocation::getInspectLocationName, reqDTO.getInspectLocationName());
        lambdaWrapper.eq(StrUtil.isNotBlank(reqDTO.getInspectState()), SaasParkFireInspectLocation::getInspectState, reqDTO.getInspectState());
        lambdaWrapper.notIn(CollUtil.isNotEmpty(reqDTO.getSelectLocationIds()), SaasParkFireInspectLocation::getId, reqDTO.getSelectLocationIds());
        lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        IPage<SaasParkFireInspectLocation> page = page(Condition.getPage(reqDTO),lambdaWrapper);
        List<SaasParkFireInspectLocation> fireInspectLocationList = page.getRecords();
        if (fireInspectLocationList.isEmpty()) {
            return PageConverterUtils.convert(resultPage);
        }
        // 空间信息
        List<Long> inspectSpaceIdList = fireInspectLocationList.stream().map(SaasParkFireInspectLocation::getInspectSpaceId).collect(Collectors.toList());
        Map<Long, String> inspectSpaceMap = new HashMap<>();
        if (Func.isNotEmpty(inspectSpaceIdList)) {
            List<PmgBatPointLocationInfo> pointLocationInfoList = pmgBatPointLocationInfoService.listByIds(inspectSpaceIdList);
            inspectSpaceMap = pointLocationInfoList.stream().collect(Collectors.toMap(PmgBatPointLocationInfo::getId, PmgBatPointLocationInfo::getName, (v1, v2) -> v2));
        }
        // 数据列表
        List<FireInspectLocationVO> resultList = new ArrayList<>();
        for (SaasParkFireInspectLocation saasParkFireInspectLocation : fireInspectLocationList) {
            FireInspectLocationVO vo = new FireInspectLocationVO();
            BeanUtil.copyProperties(saasParkFireInspectLocation, vo);
            vo.setInspectSpaceName(inspectSpaceMap.get(vo.getInspectSpaceId()));
            resultList.add(vo);
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultList);
        return PageConverterUtils.convert(resultPage);
    }

    @Override
    public List<FireInspectLocationVO> findFireInspectLocationList(List<Long> locationIds) {
        List<FireInspectLocationVO> resultList = new ArrayList<>();
        if (CollUtil.isNotEmpty(locationIds)) {
            LambdaQueryWrapper<SaasParkFireInspectLocation> lambdaWrapper = Wrappers.lambdaQuery();
            lambdaWrapper.in(SaasParkFireInspectLocation::getId, locationIds);
            List<SaasParkFireInspectLocation> fireInspectLocationList = list(lambdaWrapper);
            for (SaasParkFireInspectLocation saasParkFireInspectLocation : fireInspectLocationList) {
                FireInspectLocationVO vo = new FireInspectLocationVO();
                BeanUtil.copyProperties(saasParkFireInspectLocation, vo);
                resultList.add(vo);
            }
        }
        return resultList;
    }

    @Override
    public FireInspectLocationVO getFireInspectLocationById(Long inspectLocationId) {
        FireInspectLocationVO vo = new FireInspectLocationVO();
        SaasParkFireInspectLocation saasParkFireInspectLocation = getById(inspectLocationId);
        if (Objects.isNull(saasParkFireInspectLocation)) {
            throw new ServiceException("巡检点位数据不存在");
        }
        BeanUtil.copyProperties(saasParkFireInspectLocation, vo);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addFireInspectLocation(FireInspectLocationSubmitReqDTO reqDTO) {
        SaasParkFireInspectLocation saasParkFireInspectLocation = new SaasParkFireInspectLocation();
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectLocation);
        // 判断去重
        validRepeat(saasParkFireInspectLocation);
        saasParkFireInspectLocation.setInspectLocationCode(ReceiptCodeUtil.setLocationCodeValue("XJDW"));
        saasParkFireInspectLocation.setCustomerId(AuthUtil.getUser().getCustomerManageId());
        saasParkFireInspectLocation.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        return save(saasParkFireInspectLocation);
    }

    @Override
    public Boolean editFireInspectLocation(FireInspectLocationSubmitReqDTO reqDTO) {
        SaasParkFireInspectLocation saasParkFireInspectLocation = getById(reqDTO.getId());
        if (Objects.isNull(saasParkFireInspectLocation)) {
            throw new ServiceException("巡检点位数据不存在");
        }
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectLocation);
        // 判断去重
        validRepeat(saasParkFireInspectLocation);
        saasParkFireInspectLocation.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
        return updateById(saasParkFireInspectLocation);
    }

    @Override
    public Boolean removeFireInspectLocation(Long inspectLocationId) {
        SaasParkFireInspectLocation saasParkFireInspectLocation = getById(inspectLocationId);
        if (Objects.isNull(saasParkFireInspectLocation)) {
            throw new ServiceException("巡检点位数据不存在");
        }
        return removeById(inspectLocationId);
    }

    private void validRepeat(SaasParkFireInspectLocation saasParkFireInspectLocation) {
        int count = count(new LambdaQueryWrapper<SaasParkFireInspectLocation>()
                .eq(SaasParkFireInspectLocation::getInspectLocationName, saasParkFireInspectLocation.getInspectLocationName())
                .eq(Objects.nonNull(saasParkFireInspectLocation.getProjectId()), SaasParkFireInspectLocation::getProjectId, saasParkFireInspectLocation.getProjectId())
                .notIn(Objects.nonNull(saasParkFireInspectLocation.getId()), BaseEntity::getId, saasParkFireInspectLocation.getId()));
        if (count > 0) {
            throw new ServiceException("巡检点位名称不能重复");
        }
    }
}
