package com.starry.admin.modules.personnel.service.impl;

import cn.hutool.core.collection.CollectionUtil;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.starry.admin.common.domain.LoginUser;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.module.enums.ClerkRoleStatus;
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
import com.starry.admin.modules.personnel.mapper.PlayPersonnelGroupInfoMapper;
import com.starry.admin.modules.personnel.module.entity.PlayPersonnelGroupInfoEntity;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoQueryVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoReturnVo;
import com.starry.admin.modules.personnel.service.IPlayPersonnelGroupInfoService;
import com.starry.common.enums.TenantRoleEnum;
import com.starry.common.utils.IdUtils;
import com.starry.common.utils.StringUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 店员分组信息Service业务层处理
 *
 * @author admin
 * @since 2024-05-31
 */
@Service
public class PlayPersonnelGroupInfoServiceImpl
        extends
            ServiceImpl<PlayPersonnelGroupInfoMapper, PlayPersonnelGroupInfoEntity>
        implements
            IPlayPersonnelGroupInfoService {
    @Resource
    private PlayPersonnelGroupInfoMapper playClerkGroupInfoMapper;
    @Resource
    private IPlayClerkUserInfoService clerkUserInfoService;

    /**
     * 查询店员分组信息
     *
     * @param id
     *            店员分组信息主键
     * @return 店员分组信息
     */
    @Override
    public PlayPersonnelGroupInfoEntity selectPlayClerkGroupInfoById(String id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public PlayPersonnelGroupInfoEntity selectByUserId(String userId) {
        LambdaQueryWrapper<PlayPersonnelGroupInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlayPersonnelGroupInfoEntity::getSysUserId, userId);
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<PlayPersonnelGroupInfoEntity> selectAll() {
        return this.baseMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public IPage<PlayPersonnelGroupInfoReturnVo> selectByPage(PlayPersonnelGroupInfoQueryVo vo) {
        MPJLambdaWrapper<PlayPersonnelGroupInfoEntity> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        if (StrUtil.isNotBlank(vo.getLeaderName())) {
            lambdaQueryWrapper.eq(PlayPersonnelGroupInfoEntity::getLeaderName, vo.getLeaderName());
        }
        return this.baseMapper.selectJoinPage(new Page<>(vo.getPageNum(), vo.getPageSize()),
                PlayPersonnelGroupInfoReturnVo.class, lambdaQueryWrapper);
    }

    /**
     * 新增店员分组信息
     *
     * @param playClerkGroupInfo
     *            店员分组信息
     * @return 结果
     */
    @Override
    public boolean create(PlayPersonnelGroupInfoEntity playClerkGroupInfo) {
        if (StrUtil.isBlankIfStr(playClerkGroupInfo.getId())) {
            playClerkGroupInfo.setId(IdUtils.getUuid());
        }
        return save(playClerkGroupInfo);
    }

    /**
     * 修改店员分组信息
     *
     * @param playClerkGroupInfo
     *            店员分组信息
     * @return 结果
     */
    @Override
    public boolean update(PlayPersonnelGroupInfoEntity playClerkGroupInfo) {
        return updateById(playClerkGroupInfo);
    }

    /**
     * 批量删除店员分组信息
     *
     * @param ids
     *            需要删除的店员分组信息主键
     * @return 结果
     */
    @Override
    public int deletePlayClerkGroupInfoByIds(String[] ids) {
        return playClerkGroupInfoMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除店员分组信息信息
     *
     * @param id
     *            店员分组信息主键
     */
    @Override
    public void deletePlayClerkGroupInfoById(String id) {
        playClerkGroupInfoMapper.deleteById(id);
    }

    @Override
    public List<String> getValidClerkIdList(LoginUser loginUser, String clerkNickName) {
        List<String> idList;
        Set<String> roleKeys = loginUser != null && loginUser.getRoles() != null ? loginUser.getRoles()
                : Collections.emptySet();
        boolean hasOperatorRole = TenantRoleEnum.hasOperatorPrivilege(roleKeys);
        PlayPersonnelGroupInfoEntity groupInfoEntity = null;
        if (!hasOperatorRole && loginUser != null) {
            groupInfoEntity = this.selectByUserId(loginUser.getUserId());
        }
        if (Objects.nonNull(groupInfoEntity)) {
            List<PlayClerkUserInfoEntity> list = clerkUserInfoService
                    .list(Wrappers.lambdaQuery(PlayClerkUserInfoEntity.class)
                            .eq(PlayClerkUserInfoEntity::getGroupId, groupInfoEntity.getId())
                            .select(PlayClerkUserInfoEntity::getId));
            idList = list.stream().map(PlayClerkUserInfoEntity::getId).collect(Collectors.toList());
            PlayClerkUserInfoEntity entity = clerkUserInfoService
                    .getOne(Wrappers.lambdaQuery(PlayClerkUserInfoEntity.class)
                            .eq(PlayClerkUserInfoEntity::getSysUserId, loginUser.getUserId()), false);
            if (Objects.nonNull(entity)) {
                idList.add(entity.getId());
            }
        } else {
            // 返回所有的clerkId
            idList = clerkUserInfoService
                    .list(Wrappers.lambdaQuery(PlayClerkUserInfoEntity.class).select(PlayClerkUserInfoEntity::getId)
                            .eq(PlayClerkUserInfoEntity::getClerkState, ClerkRoleStatus.CLERK.getCode()))
                    .stream().map(PlayClerkUserInfoEntity::getId).collect(Collectors.toList());
        }

        if (CollectionUtil.isEmpty(idList)) {
            idList = Collections.singletonList("-999");
        }
        // 加入nickName的筛选
        if (StringUtils.isNotEmpty(clerkNickName)) {
            LambdaQueryWrapper<PlayClerkUserInfoEntity> wrapper = Wrappers.lambdaQuery(PlayClerkUserInfoEntity.class)
                    .in(PlayClerkUserInfoEntity::getId, idList)
                    .like(PlayClerkUserInfoEntity::getNickname, clerkNickName).select(PlayClerkUserInfoEntity::getId);
            idList = clerkUserInfoService.list(wrapper).stream().map(PlayClerkUserInfoEntity::getId)
                    .collect(Collectors.toList());
        }
        if (CollectionUtil.isEmpty(idList)) {
            idList = Collections.singletonList("-999");
        }
        return idList;
    }
}
