package com.mcwl.communityCenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.AjaxResult;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.communityCenter.domain.Community;
import com.mcwl.communityCenter.domain.Publish;
import com.mcwl.communityCenter.domain.Question;
import com.mcwl.communityCenter.domain.dto.PublishDetailRes;
import com.mcwl.communityCenter.domain.dto.PublishPageRes;
import com.mcwl.communityCenter.domain.dto.PublishRes;
import com.mcwl.communityCenter.domain.vo.PublishVo;
import com.mcwl.communityCenter.mapper.CommunityMapper;
import com.mcwl.communityCenter.mapper.InviteMapper;
import com.mcwl.communityCenter.mapper.PublishMapper;
import com.mcwl.communityCenter.mapper.QuestionMapper;
import com.mcwl.communityCenter.service.PublishService;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import nonapi.io.github.classgraph.concurrency.AutoCloseableExecutorService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@RequiredArgsConstructor
public class PublishServiceImpl extends ServiceImpl<PublishMapper, Publish> implements PublishService {

    private final ISysUserService sysUserService;

    private final InviteMapper inviteMapper;

    private final CommunityMapper communityMapper;


    @Override
    public PublishVo getDetail(PublishDetailRes publishDetailRes) {
        Long id = publishDetailRes.getId();
        Long tenantId = publishDetailRes.getTenantId();
        Long communityId = publishDetailRes.getCommunityId();

        // 根据id和租户id和社区id查询发布信息
        Publish publish = baseMapper.selectByIdAndTenantIdAndCommunityId(id, tenantId, communityId);

        if (Objects.isNull(publish)) {
            return null;
        }
        PublishVo publishVo = new PublishVo();
        BeanUtil.copyProperties(publish, publishVo);
        Long userId = publish.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        publishVo.setUserName(sysUser.getUserName());
        publishVo.setAvatar(sysUser.getAvatar());
        return publishVo;
    }

    @Override
    public R<Object> publish(PublishRes publishRes) {

        Long userId = SecurityUtils.getUserId();

        Community community = communityMapper.getByTenantIdAndCommunityId(publishRes.getTenantId(), publishRes.getCommunityId());

        if (Objects.isNull(community)) {
            return R.fail("用户社区未创建");
        }


        Set<Long> invites = inviteMapper.selectInviteIds(publishRes.getTenantId(), publishRes.getCommunityId());

        // 判断用户是否是群主
        if (!Objects.equals(userId, publishRes.getTenantId())) {
            // 判断用户是否被邀请
            if (invites.isEmpty() || !invites.contains(userId)) {
                return R.fail("您没有被邀请");
            }
        }
        Publish publish = new Publish();
        BeanUtil.copyProperties(publishRes, publish);
        publish.setUserId(userId);
        if (Objects.isNull(publish.getPublishTime())) {
            publish.setPublishTime(new Date());
        }
        baseMapper.insert(publish);
        return R.ok();
    }

    @Override
    public TableDataInfo getPublishList(PublishPageRes publishPageRes) {

        Page<Publish> page = this.initPage(publishPageRes);

        // 根据租户id和社区id查询分页数据
        baseMapper.selectByTenantIdAndCommunityIdPage(page, publishPageRes.getTenantId(), publishPageRes.getCommunityId());


        List<Publish> publishList = page.getRecords();
        List<PublishVo> publishVoList = new ArrayList<>();
        for (Publish publish : publishList) {
            PublishVo publishVo = new PublishVo();
            BeanUtil.copyProperties(publish, publishVo);
            Long userId = publish.getUserId();
            SysUser sysUser = sysUserService.selectUserById(userId);
            publishVo.setUserName(sysUser.getUserName());
            publishVo.setAvatar(sysUser.getAvatar());
            publishVoList.add(publishVo);
        }


        // 封装返回
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(publishVoList);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    @Override
    public TableDataInfo publishImage(PublishPageRes publishPageRes) {

        Page<Publish> page = this.initPage(publishPageRes);

        // 根据租户id和社区id和fileUrl不为空查询分页数据
        baseMapper.selectByTenantIdAndCommunityIdAndNotNullFilePage(page, publishPageRes.getTenantId(), publishPageRes.getCommunityId());

        List<Publish> publishList = page.getRecords();
        List<PublishVo> publishVoList = new ArrayList<>();
        for (Publish publish : publishList) {
            PublishVo publishVo = new PublishVo();
            BeanUtil.copyProperties(publish, publishVo);
            Long userId = publish.getUserId();
            SysUser sysUser = sysUserService.selectUserById(userId);
            publishVo.setUserName(sysUser.getUserName());
            publishVo.setAvatar(sysUser.getAvatar());
            publishVoList.add(publishVo);
        }


        // 封装返回
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(publishVoList);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    @Override
    public TableDataInfo publishFile(PublishPageRes publishPageRes) {
        Page<Publish> page = this.initPage(publishPageRes);

        // 根据租户id和社区id和imageUrl不为空查询分页数据
        baseMapper.selectByTenantIdAndCommunityIdAndNotNullFilePage(page, publishPageRes.getTenantId(), publishPageRes.getCommunityId());

        List<Publish> publishList = page.getRecords();
        List<PublishVo> publishVoList = new ArrayList<>();
        for (Publish publish : publishList) {
            PublishVo publishVo = new PublishVo();
            BeanUtil.copyProperties(publish, publishVo);
            Long userId = publish.getUserId();
            SysUser sysUser = sysUserService.selectUserById(userId);
            publishVo.setUserName(sysUser.getUserName());
            publishVo.setAvatar(sysUser.getAvatar());
            publishVoList.add(publishVo);
        }


        // 封装返回
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(publishVoList);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    private Page<Publish> initPage(PublishPageRes publishPageRes) {
        Page<Publish> page = new Page<>(publishPageRes.getPageNum(), publishPageRes.getPageSize());

        if (StringUtils.isBlank(publishPageRes.getOrderByColumn())) {
            publishPageRes.setOrderByColumn("create_time");
        }
        boolean isAsc = Objects.equals(publishPageRes.getIsAsc(), "asc");
        OrderItem orderItem = new OrderItem(publishPageRes.getOrderByColumn(), isAsc);

        page.addOrder(orderItem);

        return page;
    }
}
