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.StatusConstant;
import com.mcwl.communityCenter.domain.Community;
import com.mcwl.communityCenter.domain.CommunityAdvice;
import com.mcwl.communityCenter.domain.Invite;
import com.mcwl.communityCenter.domain.Question;
import com.mcwl.communityCenter.domain.dto.QuestionDetailRes;
import com.mcwl.communityCenter.domain.dto.QuestionPageRes;
import com.mcwl.communityCenter.domain.dto.QuestionReplyRes;
import com.mcwl.communityCenter.domain.dto.QuestionRes;
import com.mcwl.communityCenter.domain.vo.QuestionVo;
import com.mcwl.communityCenter.mapper.CommunityAdviceMapper;
import com.mcwl.communityCenter.mapper.CommunityMapper;
import com.mcwl.communityCenter.mapper.InviteMapper;
import com.mcwl.communityCenter.mapper.QuestionMapper;
import com.mcwl.communityCenter.service.CommunityService;
import com.mcwl.communityCenter.service.QuestionService;
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.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;

    /**
     * 添加问题
     *
     * @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();

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

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

//        if (Objects.equals(tenantId, userId)) {
//            return AjaxResult.error("您不能提问自己的问题");
//        }

        //提问人（userId）是否在社区中
//        Invite invite = inviteMapper.selectByTenantIdAndCommunityIdAndInviteeUserId(tenantId, communityId, userId);
//        if (Objects.isNull(invite)) {
//            return AjaxResult.error("您不是该社区成员，不能提问");
//        }

        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);


//        CommunityAdvice communityAdvice = new CommunityAdvice();
//        communityAdvice.setTenantId(tenantId);
//        communityAdvice.setCommunityId(communityId);
//        communityAdvice.setUserId(tenantId);
//        communityAdvice.setTitle("您有新的问题");
//        communityAdvice.setContent(questionRes.getContent());
//        communityAdviceMapper.insert(communityAdvice);


        return R.ok();

    }

    @Override
    public TableDataInfo list(QuestionPageRes questionPageRes) {

        Page<Question> page = initPage(questionPageRes);

//        baseMapper.list(page, questionPageRes.getTenantId(), questionPageRes.getCommunityId(), questionPageRes.getStatus());
        baseMapper.list(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 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;
    }

    private Page<Question> initPage(QuestionPageRes questionPageRes) {
        Page<Question> page = new Page<>(questionPageRes.getPageNum(), questionPageRes.getPageSize());
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isBlank(questionPageRes.getOrderByColumn())) {
            questionPageRes.setOrderByColumn("create_time");
        }
        orderItem.setColumn(questionPageRes.getOrderByColumn());
        orderItem.setAsc(Objects.equals(questionPageRes.getIsAsc(), "asc"));
        page.addOrder(orderItem);
        return page;
    }


}
