package com.njzscloud.supervisory.station.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.security.support.UserDetail;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.biz.pojo.entity.BizCompanyEntity;
import com.njzscloud.supervisory.biz.service.BizCompanyService;
import com.njzscloud.supervisory.constant.Constant;
import com.njzscloud.supervisory.station.mapper.StationManageMapper;
import com.njzscloud.supervisory.station.pojo.entity.StationManageEntity;
import com.njzscloud.supervisory.station.pojo.param.AddStationManageParam;
import com.njzscloud.supervisory.station.pojo.param.SearchStationManageParam;
import com.njzscloud.supervisory.station.pojo.result.ListManagerResult;
import com.njzscloud.supervisory.station.pojo.result.SearchStationManageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 站点管理员
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StationManageService extends ServiceImpl<StationManageMapper, StationManageEntity> implements IService<StationManageEntity> {
    private final BizCompanyService bizCompanyService;

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(AddStationManageParam addStationManageParam) {
        Long stationId = addStationManageParam.getStationId();
        boolean exists = bizCompanyService.exists(Wrappers.lambdaQuery(BizCompanyEntity.class).eq(BizCompanyEntity::getId, stationId).eq(BizCompanyEntity::getStation, Boolean.TRUE));
        Assert.isTrue(exists, () -> Exceptions.clierr("站点不存在"));
        Set<Long> userIds = addStationManageParam.getUserIds();
        Assert.notEmpty(userIds, () -> Exceptions.clierr("未指定用户"));
        List<StationManageEntity> collect = userIds.stream().map(it -> new StationManageEntity().setStationId(stationId).setUserId(it)
                .setCanuse(Boolean.TRUE)).collect(Collectors.toList());
        this.remove(Wrappers.lambdaQuery(StationManageEntity.class).eq(StationManageEntity::getStationId, stationId));
        this.saveBatch(collect);
    }

    /**
     * 修改
     */
    public void modify(StationManageEntity stationManageEntity) {
        this.updateById(stationManageEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public StationManageEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     */
    public PageResult<SearchStationManageResult> paging(PageParam pageParam, SearchStationManageParam searchStationManageParam) {
        Long userId = searchStationManageParam.getUserId();
        String nickname = searchStationManageParam.getNickname();
        Long stationId = searchStationManageParam.getStationId();
        String stationName = searchStationManageParam.getStationName();
        return PageResult.of(baseMapper.paging(pageParam.toPage(), Wrappers.<SearchStationManageParam>query()
                .eq(userId != null, "a.user_id", userId)
                .eq(stationId != null, "a.station_id", stationId)
                .like(StrUtil.isNotBlank(stationName), "b.company_name", stationName)
                .like(StrUtil.isNotBlank(nickname), "c.nickname", nickname)
        ));
    }

    public List<SearchStationManageResult> myStation() {
        UserDetail userDetail = SecurityUtil.loginUser();
        Set<String> roles = userDetail.getRoles();
        Assert.isTrue(SecurityUtil.isAdmin() || roles.contains(Constant.ROLE_STATION_MANAGE), () -> Exceptions.clierr("当前用户无权限查询站点"));
        if (SecurityUtil.isAdmin()) {
            return baseMapper.adminStation();
        } else {
            return baseMapper.myStation(Wrappers.query().eq("a.user_id", userDetail.getUserId()));
        }
    }

    public ListManagerResult listManager(SearchStationManageParam searchStationManageParam) {
        String nickname = searchStationManageParam.getNickname();

        Long stationId = searchStationManageParam.getStationId();
        List<SearchStationManageResult> records = baseMapper.listManager(Wrappers.query()
                .like(StrUtil.isNotBlank(nickname), "b.nickname", nickname)
                .eq("c.role_code", Constant.ROLE_STATION_MANAGE)
        );
        List<Long> myManage;
        if (CollUtil.isNotEmpty(records)) {
            Set<Long> userIds = records.stream().map(SearchStationManageResult::getUserId).collect(Collectors.toSet());
            myManage = baseMapper.myManage(Wrappers.query().in("a.user_id", userIds).eq("a.station_id", stationId));
        } else {
            myManage = Collections.emptyList();
        }
        return new ListManagerResult().setRecodes(records).setManagerIds(myManage);
    }
}
