package com.mcwl.communityCenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.domain.*;
import com.mcwl.communityCenter.domain.dto.*;
import com.mcwl.communityCenter.domain.vo.QuestionCommentVo;
import com.mcwl.communityCenter.domain.vo.QuestionVo;
import com.mcwl.communityCenter.mapper.*;
import com.mcwl.communityCenter.service.IncomeInfoService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@RequiredArgsConstructor
public class QuestionCommentServiceImpl extends ServiceImpl<QuestionCommentMapper, QuestionComment> implements QuestionCommentService {

    private final QuestionMapper questionMapper;

    private final ISysUserService sysUserService;

    private final CommunityAdviceMapper communityAdviceMapper;

    private final CommunityUserMapper communityUserMapper;

    private final ConsumeMapper consumeMapper;

    private final IncomeInfoService incomeInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Object> comment(QuestionCommentRes questionCommentRes) {

        Long tenantId = questionCommentRes.getTenantId();
        Long communityId = questionCommentRes.getCommunityId();
        Long questionId = questionCommentRes.getQuestionId();

        Question question = questionMapper.selectByIdAndTenantIdAndCommunityId(questionId, tenantId, communityId);

        if (Objects.isNull(question)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "提问不存在");
        }

        CommunityUser communityUser = communityUserMapper.selectCommunityUser(tenantId, communityId, SecurityUtils.getUserId());
        if (Objects.isNull(communityUser)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "您不是该社区成员，不能评论");
        }
        if ("1".equals(communityUser.getIsBlack())) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"您已被拉黑");
        }

        QuestionComment questionComment = new QuestionComment();
        BeanUtil.copyProperties(questionCommentRes, questionComment);
        questionComment.setUserId(SecurityUtils.getUserId());

        baseMapper.insert(questionComment);

        CommunityAdvice communityAdvice = new CommunityAdvice();

        communityAdvice.setTenantId(tenantId);
        communityAdvice.setCommunityId(communityId);
        communityAdvice.setSendUserId(SecurityUtils.getUserId());
        communityAdvice.setAdviceType(AdviceConstant.REPLY_ME);
        communityAdvice.setUserId(question.getQuestionUserId());
        communityAdvice.setTitle(StringUtils.format("{}回复{}",
                SecurityUtils.getLoginUser().getUser().getNickName(),
                question.getContent()));
        communityAdvice.setContent(questionCommentRes.getContent());

        communityAdviceMapper.insert(communityAdvice);

        return R.ok(null, "评论成功");
    }


    @Override
    public TableDataInfo listByPage(QuestionCommentPageRes questionCommentPageRes) {

        Page<QuestionComment> page = initPage(questionCommentPageRes);

        baseMapper.selectByTenantIdAndCommunityIdAndQuestionIdPage(page, questionCommentPageRes.getTenantId(), questionCommentPageRes.getCommunityId(), questionCommentPageRes.getQuestionId());


        List<QuestionComment> questionCommentList = page.getRecords();
        List<QuestionCommentVo> questionCommentVoList = new ArrayList<>();
        for (QuestionComment questionComment : questionCommentList) {
            QuestionCommentVo questionCommentVo = new QuestionCommentVo();
            BeanUtil.copyProperties(questionComment, questionCommentVo);
            questionCommentVoList.add(questionCommentVo);
        }

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setRows(questionCommentVoList);
        tableDataInfo.setTotal(page.getTotal());

        return tableDataInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Object> adopt(QuestionCommentAdoptRes questionCommentAdoptRes) {

        Long tenantId = questionCommentAdoptRes.getTenantId();
        Long communityId = questionCommentAdoptRes.getCommunityId();
        Long questionId = questionCommentAdoptRes.getQuestionId();
        Long commentId = questionCommentAdoptRes.getCommentId();

        Question question = questionMapper.selectByIdAndTenantIdAndCommunityId(questionId, tenantId, communityId);
        if (Objects.isNull(question)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "提问不存在");
        }

        if (question.getStatus() == 1) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "该提问已解决");
        }

        QuestionComment questionComment = baseMapper.selectByIdAndTenantIdAndCommunityIdAndQuestionIdAndCommentId(tenantId, communityId, questionId, commentId);
        if (Objects.isNull(questionComment)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "评论不存在");
        }

        if (questionComment.getIsAccept() == 1) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "该评论已被采纳");
        }

        Long questionUserId = question.getQuestionUserId();
        if (questionComment.getUserId().equals(questionUserId)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "您不能采纳自己的评论");
        }

        questionComment.setIsAccept(1);
        baseMapper.updateById(questionComment);

        question.setStatus(1);

        questionMapper.updateById(question);


        SysUser sysUser = sysUserService.selectUserById(questionComment.getUserId());
        BigDecimal sysWallet = new BigDecimal(sysUser.getWallet().toString());
        BigDecimal amount = new BigDecimal(question.getAmount().toString());
        // 添加钱包
        BigDecimal wallet = sysWallet.add(amount);
        sysUser.setWallet(wallet.doubleValue());
        sysUserService.updateUser(sysUser);


        Consume consume = new Consume();
        consume.setUserId(questionComment.getUserId());
        consume.setAmount(question.getAmount());
        consume.setType(4);
        consume.setWallet(sysUser.getWallet());
        consumeMapper.insert(consume);

        IncomeInfo incomeInfo = new IncomeInfo();
        incomeInfo.setTenantId(tenantId);
        incomeInfo.setCommunityId(communityId);
        incomeInfo.setUserId(questionComment.getUserId());
        incomeInfo.setType(1);
        incomeInfo.setAmount(question.getAmount());
        incomeInfoService.save(incomeInfo);


        return R.ok();
    }

    @Override
    public List<QuestionCommentVo> getComment(QuestionDetailRes questionDetailRes) {

        return baseMapper.getComment(questionDetailRes);
    }

    private Page<QuestionComment> initPage(QuestionCommentPageRes questionCommentPageRes) {

        Page<QuestionComment> page = new Page<>(questionCommentPageRes.getPageNum(), questionCommentPageRes.getPageSize());

        page.addOrder(new OrderItem("create_time", false));


        return page;
    }


}
