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.manage.system.api.entity.NestOrgUser;
import com.yuchen.saas.manage.system.api.feign.IOrgUserClient;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectTypeReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectTypeSubmitReqDTO;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectType;
import com.yuchen.saas.park.api.vo.fire.inspect.FireInspectTypeVO;
import com.yuchen.saas.park.service.mapper.fire.inspect.SaasParkFireInspectTypeMapper;
import com.yuchen.saas.park.service.service.fire.inspect.ISaasParkFireInspectTypeService;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhouhanwei
 * @since 2024-04-01
 */
@Service
@RequiredArgsConstructor
public class SaasParkFireInspectTypeServiceImpl extends BaseServiceImpl<SaasParkFireInspectTypeMapper, SaasParkFireInspectType> implements ISaasParkFireInspectTypeService {

    private final IOrgUserClient iOrgUserClient;

    @Override
    public NestPage<FireInspectTypeVO> findFireInspectTypePage(FireInspectTypeReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        Page<FireInspectTypeVO> resultPage = new Page<>();
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectType> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectType::getCustomerId, contextUser.getCustomerManageId());
        lambdaWrapper.like(Func.isNotEmpty(reqDTO.getInspectTypeName()), SaasParkFireInspectType::getInspectTypeName, reqDTO.getInspectTypeName());
        lambdaWrapper.like(Func.isNotEmpty(reqDTO.getInspectTypeCode()), SaasParkFireInspectType::getInspectTypeCode, reqDTO.getInspectTypeCode());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getBusinessId()), SaasParkFireInspectType::getBusinessId, reqDTO.getBusinessId());
        lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        IPage<SaasParkFireInspectType> page = page(Condition.getPage(reqDTO), lambdaWrapper);
        List<SaasParkFireInspectType> fireInspectTypeList = page.getRecords();

        // 数据列表
        List<FireInspectTypeVO> resultList = new ArrayList<>();
        if (CollUtil.isEmpty(fireInspectTypeList)) {
            resultPage.setTotal(page.getTotal());
            resultPage.setSize(page.getSize());
            resultPage.setCurrent(page.getCurrent());
            resultPage.setRecords(resultList);
            return PageConverterUtils.convert(resultPage);
        }
        // 组织用户列表
        List<Long> orgUserIdList = fireInspectTypeList.stream().map(SaasParkFireInspectType::getCreateOrgUser).collect(Collectors.toList());
        List<NestOrgUser> orgUserList = iOrgUserClient.findOrgUserListByIds(orgUserIdList).getData();
        Map<Long, String> orgUserMap = orgUserList.stream().collect(Collectors.toMap(BaseEntity::getId, NestOrgUser::getName));
        for (SaasParkFireInspectType saasParkFireInspectType : fireInspectTypeList) {
            FireInspectTypeVO vo = new FireInspectTypeVO();
            BeanUtil.copyProperties(saasParkFireInspectType, vo);
            vo.setOrgUserName(orgUserMap.get(saasParkFireInspectType.getCreateOrgUser()));
            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<FireInspectTypeVO> getClientInspectTypeList(FireInspectTypeReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectType> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectType::getCustomerId, contextUser.getCustomerManageId());
        lambdaWrapper.like(StrUtil.isNotBlank(reqDTO.getInspectTypeName()), SaasParkFireInspectType::getInspectTypeName, reqDTO.getInspectTypeName());
        lambdaWrapper.like(StrUtil.isNotBlank(reqDTO.getInspectTypeCode()), SaasParkFireInspectType::getInspectTypeCode, reqDTO.getInspectTypeCode());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getBusinessId()), SaasParkFireInspectType::getBusinessId, reqDTO.getBusinessId());
        lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        List<SaasParkFireInspectType> fireInspectTypeList = list(lambdaWrapper);
        return fireInspectTypeList.stream().map(s -> {
            FireInspectTypeVO vo = new FireInspectTypeVO();
            BeanUtil.copyProperties(s, vo);
            return vo;
        }).collect(Collectors.toList());
    }


    @Override
    public Map<Long, String> findFireInspectTypeMap(List<Long> ids) {
        List<SaasParkFireInspectType> fireInspectTypeList = listByIds(ids);
        return fireInspectTypeList.stream()
                .collect(Collectors.toMap(SaasParkFireInspectType::getId, SaasParkFireInspectType::getInspectTypeName));
    }

    @Override
    public FireInspectTypeVO getFireInspectTypeById(Long inspectTypeById) {
        FireInspectTypeVO vo = new FireInspectTypeVO();
        SaasParkFireInspectType saasParkFireInspectType = getById(inspectTypeById);
        if (Objects.isNull(saasParkFireInspectType)) {
            throw new ServiceException("巡检类型数据不存在");
        }
        BeanUtil.copyProperties(saasParkFireInspectType, vo);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addFireInspectType(FireInspectTypeSubmitReqDTO reqDTO) {
        SaasParkFireInspectType saasParkFireInspectType = new SaasParkFireInspectType();
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectType);
        // 判断去重
        validRepeat(saasParkFireInspectType);
        saasParkFireInspectType.setCustomerId(AuthUtil.getUser().getCustomerManageId());
        saasParkFireInspectType.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        return save(saasParkFireInspectType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editFireInspectType(FireInspectTypeSubmitReqDTO reqDTO) {
        SaasParkFireInspectType saasParkFireInspectType = getById(reqDTO.getId());
        if (Objects.isNull(saasParkFireInspectType)) {
            throw new ServiceException("巡检类型数据不存在");
        }
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectType);
        // 判断去重
        validRepeat(saasParkFireInspectType);
        saasParkFireInspectType.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
        return updateById(saasParkFireInspectType);
    }

    @Override
    public Boolean removeFireInspectType(Long inspectTypeById) {
        SaasParkFireInspectType saasParkFireInspectType = getById(inspectTypeById);
        if (Objects.isNull(saasParkFireInspectType)) {
            throw new ServiceException("巡检类型数据不存在");
        }
        return removeById(inspectTypeById);
    }


    private void validRepeat(SaasParkFireInspectType saasParkFireInspectType) {
        int count = count(new LambdaQueryWrapper<SaasParkFireInspectType>()
                .and(s -> s.eq(SaasParkFireInspectType::getInspectTypeName, saasParkFireInspectType.getInspectTypeName())
                        .or()
                        .eq(SaasParkFireInspectType::getInspectTypeCode, saasParkFireInspectType.getInspectTypeCode()))
                .notIn(Objects.nonNull(saasParkFireInspectType.getId()), BaseEntity::getId, saasParkFireInspectType.getId()));
        if (count > 0) {
            throw new ServiceException("巡检类型名称或编码不能重复");
        }
    }
}
