package com.tofly.feesapi.yhgl.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.feesapi.bmgl.entity.BmCbb;
import com.tofly.feesapi.bmgl.service.BmCbbService;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.common.feign.UserClient;
import com.tofly.feesapi.common.feign.vo.User;
import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.yhgl.entity.Yhsjqx;
import com.tofly.feesapi.yhgl.entity.vo.YhSjQxVo;
import com.tofly.feesapi.yhgl.entity.vo.YhsjqxReq;
import com.tofly.feesapi.yhgl.mapper.YhsjqxMapper;
import com.tofly.feesapi.yhgl.service.YhsjqxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class YhsjqxServiceImpl extends ServiceImpl<YhsjqxMapper, Yhsjqx> implements YhsjqxService {

    @Resource
    private UserClient userClient;
    @Resource
    private BmCbbService bmCbbService;

    @Override
    public void add(YhsjqxReq req) {
        if (ObjectUtil.isNull(req) || CollectionUtil.isEmpty(req.getUserIds())
                || CollectionUtil.isEmpty(req.getCbbbms())) {
            throw new FeesException("请选择用户和抄表册", FeesErrorCode.BUSINESS_ERROR);
        }

        List<Long> userIds = req.getUserIds();
        List<String> cbbbms = req.getCbbbms();

        LambdaQueryWrapper<Yhsjqx> queryWrapper = Wrappers.<Yhsjqx>lambdaQuery().in(Yhsjqx::getUserId, userIds);
        List<Yhsjqx> existingList = baseMapper.selectList(queryWrapper);

        // 每次添加前先删除原数据权限
        if (CollectionUtil.isNotEmpty(existingList)) {
            List<Long> idList = existingList.stream().map(Yhsjqx::getId).collect(Collectors.toList());
            baseMapper.deleteBatchIds(idList);
        }

        for (Long userId : userIds) {
            for (String cbbbm : cbbbms) {
                Yhsjqx yhsjqx = new Yhsjqx();
                yhsjqx.setUserId(userId);
                yhsjqx.setCbbbm(cbbbm);
                baseMapper.add(yhsjqx);
            }
        }

    }

    @Override
    public List<YhSjQxVo> queryByKeyWord(String keyWord) {
        ResultRespone<List<User>> response = userClient.getUserInfoByKeyWord(keyWord);
        if (ObjectUtil.isNull(response) || response.getCode() != 1) {
            throw new FeesException("远程调用失败", FeesErrorCode.INTERNAL_SERVER_ERROR);
        }

        List<User> users = response.getResult();
        if (CollectionUtil.isEmpty(users)) {
            return new ArrayList<>();
        }

        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        LambdaQueryWrapper<Yhsjqx> wrapper = Wrappers.<Yhsjqx>lambdaQuery().in(Yhsjqx::getUserId, userIds);
        List<Yhsjqx> yhsjqxes = baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(yhsjqxes)) {
            return new ArrayList<>();
        }

        List<String> cbbbmList = yhsjqxes.stream().map(Yhsjqx::getCbbbm).distinct().collect(Collectors.toList());
        List<BmCbb> bmCbbs = bmCbbService.selectByBmList(cbbbmList);

        Map<String, BmCbb> cbbMap = bmCbbs.stream().collect(Collectors.toMap(BmCbb::getCbbbm, o -> o));
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, o -> o));

        List<YhSjQxVo> dataList = new ArrayList<>();
        for (Yhsjqx yhsjqx : yhsjqxes) {
            Long userId = yhsjqx.getUserId();
            User user = userMap.get(userId);
            YhSjQxVo yhSjQxVo = YhSjQxVo.buildVoByUser(user);

            String cbbbm = yhsjqx.getCbbbm();
            BmCbb bmCbb = cbbMap.get(cbbbm);
            yhSjQxVo.setCbbInfoByBmCbb(bmCbb);
            dataList.add(yhSjQxVo);
        }

        return dataList;
    }

    @Override
    public List<String> queryByPermission() {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Yhsjqx> wrapper = Wrappers.<Yhsjqx>lambdaQuery().eq(Yhsjqx::getUserId, userId);
        List<Yhsjqx> yhsjqxes = baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(yhsjqxes)) {
            return new ArrayList<>();
        }

        return yhsjqxes.stream().map(Yhsjqx::getCbbbm).collect(Collectors.toList());
    }

}
