package com.mcwl.communityCenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.constant.AdviceConstant;
import com.mcwl.communityCenter.constant.StatusConstant;
import com.mcwl.communityCenter.domain.*;
import com.mcwl.communityCenter.domain.dto.*;
import com.mcwl.communityCenter.domain.vo.CommentVo;
import com.mcwl.communityCenter.domain.vo.PersonHomeVo;
import com.mcwl.communityCenter.domain.vo.QuestionCommentVo;
import com.mcwl.communityCenter.domain.vo.QuestionVo;
import com.mcwl.communityCenter.mapper.*;
import com.mcwl.communityCenter.service.CommunityService;
import com.mcwl.communityCenter.service.QuestionCommentService;
import com.mcwl.communityCenter.service.QuestionService;
import com.mcwl.myInvitation.domain.Consume;
import com.mcwl.myInvitation.mapper.ConsumeMapper;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {


    private final CommunityAdviceMapper communityAdviceMapper;

    private final CommunityMapper communityMapper;

    private final ISysUserService sysUserService;

    private final InviteMapper inviteMapper;

    private final CommunityUserMapper communityUserMapper;

    private final QuestionCommentService questionCommentService;

    private final ConsumeMapper consumeMapper;


    /**
     * 添加问题
     *
     * @param questionRes 问题信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Object> addQuestion(QuestionRes questionRes) {
        Long communityId = questionRes.getCommunityId();
        Long userId = SecurityUtils.getUserId();

        // 获取租户id
        Long tenantId = questionRes.getTenantId();
        Long questionUserId = questionRes.getQuestionUserId();

        Community community = communityMapper.getByTenantIdAndCommunityId(tenantId, communityId);

        if (Objects.isNull(community)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "租户或社区不存在");
        }

        //提问人（userId）是否在社区中
        CommunityUser communityUser = communityUserMapper.selectCommunityUser(tenantId, communityId, userId);
        if (Objects.isNull(communityUser)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "您不是该社区成员，不能提问");
        }

        if ("1".equals(communityUser.getIsBlack())) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "您已被拉黑");
        }

        Question question = new Question();
        BeanUtil.copyProperties(questionRes, question);
        question.setQuestionUserId(userId);
//        question.setStatus(StatusConstant.STATUS_UNREPLIED);
        baseMapper.insert(question);

        SysUser sysUser = sysUserService.selectUserById(userId);

        BigDecimal sysWallet = new BigDecimal(sysUser.getWallet().toString());
        BigDecimal amount = new BigDecimal(questionRes.getAmount().toString());

        // 扣除钱包
        BigDecimal subtract = sysWallet.subtract(amount);

        sysUser.setWallet(subtract.doubleValue());
        sysUserService.updateUser(sysUser);


        Consume consume = new Consume();
        consume.setUserId(SecurityUtils.getUserId());
        consume.setAmount(-questionRes.getAmount());
        consume.setType(4);
        consume.setWallet(sysUser.getWallet());
        consumeMapper.insert(consume);


//        CommunityAdvice communityAdvice = new CommunityAdvice();
//        communityAdvice.setTenantId(tenantId);
//        communityAdvice.setCommunityId(communityId);
//        communityAdvice.setSendUserId(SecurityUtils.getUserId());
//        communityAdvice.setAdviceType(AdviceConstant.WAIT_ME_ANSWER);
//        communityAdvice.setUserId(questionUserId);
//        communityAdvice.setTitle(StringUtils.format("{}向你提问:", SecurityUtils.getLoginUser().getUser().getNickName()));
//        communityAdvice.setContent(questionRes.getContent());
//        communityAdviceMapper.insert(communityAdvice);


        return R.ok();

    }

    @Override
    public TableDataInfo list(QuestionPageRes questionPageRes) {

        Page<Question> page = initPage(questionPageRes);

        List<QuestionVo> questionVoList = baseMapper.list(page, questionPageRes.getTenantId(), questionPageRes.getCommunityId());
        for (QuestionVo questionVo : questionVoList) {

            QuestionDetailRes questionDetailRes = new QuestionDetailRes();
            questionDetailRes.setTenantId(questionVo.getTenantId());
            questionDetailRes.setCommunityId(questionVo.getCommunityId());
            questionDetailRes.setQuestionId(questionVo.getId());

            List<QuestionCommentVo> commentList = questionCommentService.getComment(questionDetailRes);

            questionVo.setCommentList(commentList);
        }

        // 封装分页信息
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(questionVoList);
        rspData.setTotal(page.getTotal());

        return rspData;
    }

    @Override
    public QuestionVo getDetail(QuestionDetailRes questionDetailRes) {
        Long questionId = questionDetailRes.getQuestionId();
        Long tenantId = questionDetailRes.getTenantId();
        Long communityId = questionDetailRes.getCommunityId();

        Question question = baseMapper.selectByIdAndTenantIdAndCommunityId(questionId, tenantId, communityId);
        if (Objects.isNull(question)) {
            return null;
        }
        QuestionVo questionVo = new QuestionVo();
        BeanUtil.copyProperties(question, questionVo);
        Long questionUserId = question.getQuestionUserId();
        SysUser sysUser = sysUserService.selectUserById(questionUserId);
        questionVo.setQuestionUserName(sysUser.getNickName());
        questionVo.setQuestionUserAvatar(sysUser.getAvatar());


        return questionVo;
    }

//    /**
//     * 回复问题
//     *
//     * @param questionReplyRes 回复信息
//     */
//    @Override
//    public AjaxResult reply(QuestionReplyRes questionReplyRes) {
//
//        Long communityId = questionReplyRes.getCommunityId();
//        Long questionId = questionReplyRes.getQuestionId();
//        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Question::getId, questionId)
//                .eq(Question::getCommunityId, communityId)
//                .eq(Question::getStatus, StatusConstant.STATUS_UNREPLIED);
//
//        // 查询问题信息
//        Question question = baseMapper.selectOne(lqw);
//
//        if (Objects.isNull(question)) {
//            return AjaxResult.error("问题不存在或已被回复");
//        }
//
//        question.setReply(questionReplyRes.getReply());
//        question.setStatus(StatusConstant.STATUS_REPLIED);
//        question.setReplyTime(new Date());
//
//        baseMapper.updateById(question);
//        return AjaxResult.success();
//
//    }

    @Override
    public TableDataInfo listImage(QuestionPageRes questionPageRes) {

        Page<Question> page = initPage(questionPageRes);

//        baseMapper.listImage(page, questionPageRes.getTenantId(), questionPageRes.getCommunityId(), questionPageRes.getStatus());
        baseMapper.listImage(page, questionPageRes.getTenantId(), questionPageRes.getCommunityId());

        // 获取分页数据
        List<Question> questionList = page.getRecords();
        // Question数据转为QuestionVo
        List<QuestionVo> questionVoList = new ArrayList<>();
        for (Question question : questionList) {
            QuestionVo questionVo = new QuestionVo();
            BeanUtil.copyProperties(question, questionVo);
            Long questionUserId = question.getQuestionUserId();
            SysUser sysUser = sysUserService.selectUserById(questionUserId);
            questionVo.setQuestionUserName(sysUser.getNickName());
            questionVo.setQuestionUserAvatar(sysUser.getAvatar());
            questionVoList.add(questionVo);

        }

        // 封装分页信息
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(questionVoList);
        rspData.setTotal(page.getTotal());

        return rspData;
    }

    @Override
    public TableDataInfo myQuestionList(QuestionPageRes questionPageRes) {
        Page<Question> page = initPage(questionPageRes);
        List<QuestionVo> questionList = baseMapper.myQuestionList(page, questionPageRes, SecurityUtils.getUserId());
        List<PersonHomeVo> personHomeVoList = new ArrayList<>();
        for (QuestionVo questionVo : questionList) {
            PersonHomeVo personHomeVo = BeanUtil.toBean(questionVo, PersonHomeVo.class);

            Long questionUserId = questionVo.getQuestionUserId();
            String questionUserName = questionVo.getQuestionUserName();
            String questionUserAvatar = questionVo.getQuestionUserAvatar();
            String questionUrl = questionVo.getQuestionUrl();

            personHomeVo.setUserId(questionUserId);
            personHomeVo.setUserName(questionUserName);
            personHomeVo.setAvatar(questionUserAvatar);
            personHomeVo.setImageUrl(questionUrl);

            QuestionDetailRes questionDetailRes = new QuestionDetailRes();
            questionDetailRes.setTenantId(questionVo.getTenantId());
            questionDetailRes.setCommunityId(questionVo.getCommunityId());
            questionDetailRes.setQuestionId(questionVo.getId());

            List<QuestionCommentVo> questionCommentList = questionCommentService.getComment(questionDetailRes);

//            List<QuestionCommentVo> questionCommentList = questionVo.getCommentList();

            List<CommentVo> commentList = BeanUtil.copyToList(questionCommentList, CommentVo.class);

            personHomeVo.setCommentList(commentList);

            personHomeVoList.add(personHomeVo);

        }



        // 封装分页信息
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(personHomeVoList);
        rspData.setTotal(page.getTotal());
        return rspData;
    }

    private Page<Question> initPage(QuestionPageRes questionPageRes) {
        Page<Question> page = new Page<>(questionPageRes.getPageNum(), questionPageRes.getPageSize());
        page.addOrder(new OrderItem("create_time", false));
        return page;
    }


}
