package com.xxfc.platform.im.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.config.rabbit.RabbitConstant;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.im.dto.MsgTypeEnum;
import com.xxfc.platform.im.dto.QuestionParamDto;
import com.xxfc.platform.im.dto.UpdateTypeEnum;
import com.xxfc.platform.im.entity.ImQuestion;
import com.xxfc.platform.im.mapper.ImQuestionMapper;
import com.xxfc.platform.im.vo.QuestionListVo;
import com.xxfc.platform.universal.feign.MQSenderFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class ImQuestionBiz extends BaseBiz<ImQuestionMapper, ImQuestion> {

    @Autowired
    UserBiz userBiz;

    @Autowired
    MQSenderFeign mqSenderFeign;

    @Autowired
    ImPraiseBiz imPraiseBiz;

    @Autowired
    UserFeign userFeign;
    /**
     * 获取列表
     *
     * @param questionParamDto
     * @return
     */
    public ObjectRestResponse getList(QuestionParamDto questionParamDto) {

        if(StringUtils.isNotBlank(questionParamDto.getUsername())) {
            AppUserLogin appUserLogin = userFeign.one(questionParamDto.getUsername());
            if(appUserLogin != null) {
                questionParamDto.setUserId(Long.parseLong(appUserLogin.getId() + ""));
            }
        }
        if (questionParamDto.getStartTime() != null) {
            if(questionParamDto.getEndTime() == null) {
                questionParamDto.setEndTime(System.currentTimeMillis());
            }
        }
        Query query = new Query(questionParamDto);
        PageDataVO<QuestionListVo> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.getQuestionList(query.getSuper()));
        AppUserDTO appUserDTO = userBiz.getUserInfo();
        if(appUserDTO != null) {
            pageDataVO.getData().forEach((a) -> a.setPraise(imPraiseBiz.isExist(appUserDTO.getImUserid(), a.getId())));
        }

    return new ObjectRestResponse<>().data(pageDataVO);
    }


    public ObjectRestResponse one(Integer id) {
        return ObjectRestResponse.succ(mapper.getOne(id));
    }


    /**
     * 添加问题
     *
     * @param imQuestion
     * @return
     */
    public ObjectRestResponse<ImQuestion> add(ImQuestion imQuestion) {
        AppUserDTO appUserDTO = userBiz.getUserInfo();
        if (appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        imQuestion.setSource(2);
        imQuestion.setUserId(Long.parseLong(appUserDTO.getImUserid() + ""));
        imQuestion.setNickname(appUserDTO.getNickname());
        imQuestion.setPicUrl(appUserDTO.getHeadimgurl());
        if (imQuestion == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        insertSelective(imQuestion);
        ImQuestion newValue = mapper.selectOne(imQuestion);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", appUserDTO.getUserid());
        jsonObject.put("channelId", newValue.getId());
        jsonObject.put("integralRuleCode", "PUBLISH");
        mqSenderFeign.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
        return ObjectRestResponse.succ();
    }

    public ObjectRestResponse update(ImQuestion imQuestion) {
        if (imQuestion == null || imQuestion.getId() == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        ImQuestion oldValue = mapper.selectByPrimaryKey(imQuestion.getId());
        if (oldValue == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.IM_MSG_NOT_EXIST_CODE, ResultCode.getMsg(ResultCode.IM_MSG_NOT_EXIST_CODE));
        }
        BeanUtil.copyProperties(imQuestion, oldValue, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        updateSelectiveByIdRe(oldValue);
        return ObjectRestResponse.succ();
    }

    /**
     * 后台创建
     * @return
     */
    public ObjectRestResponse bgAdd(ImQuestion imQuestion) {
        if(imQuestion == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        imQuestion.setSource(1);
        insertSelectiveRe(imQuestion);
        return ObjectRestResponse.succ();
    }


    /**
     * 删除消息，修改isDel为true
     *
     * @param id
     * @return
     */
    public ObjectRestResponse delete(Long id) {
        AppUserDTO appUserDTO = userBiz.getUserInfo();
        if (appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        if (id == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        ImQuestion imQuestion = mapper.selectByPrimaryKey(id);
        if (imQuestion == null) {
            return ObjectRestResponse.createDefaultFail();
        }
        imQuestion.setIsDel(true);
        updateSelectiveByIdRe(imQuestion);
        return ObjectRestResponse.succ();
    }

    public ObjectRestResponse deleteById(Long id) {
        if (id == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        ImQuestion imQuestion = mapper.selectByPrimaryKey(id);
        if (imQuestion == null) {
            return ObjectRestResponse.createDefaultFail();
        }
        imQuestion.setIsDel(true);
        updateSelectiveByIdRe(imQuestion);
        return ObjectRestResponse.succ();
    }

    public ObjectRestResponse update(Long id, MsgTypeEnum type, UpdateTypeEnum updateType) {
        if (id == null || type == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        ImQuestion imQuestion = mapper.selectByPrimaryKey(id);
        if (imQuestion == null) {
            return ObjectRestResponse.createDefaultFail();
        }

        if (type == MsgTypeEnum.comment) { //评论
            synchronized (imQuestion) {
                if (updateType == UpdateTypeEnum.add) { //添加
                    imQuestion.setCommentCount(imQuestion.getCommentCount() + 1);
                } else {
                    imQuestion.setCommentCount((imQuestion.getCommentCount() > 0 ? imQuestion.getCommentCount() - 1 : 0));
                }
            }
        }
        if (type == MsgTypeEnum.praise) { //点赞
            synchronized (imQuestion) {
                if (updateType == UpdateTypeEnum.add) { //添加
                    imQuestion.setPraiseCount(imQuestion.getPraiseCount() + 1);
                } else {
                    imQuestion.setPraiseCount(imQuestion.getPraiseCount() > 0 ? imQuestion.getPraiseCount() - 1 : 0);
                }
            }
        }
       updateSelectiveByIdRe(imQuestion);
        return ObjectRestResponse.succ();
    }

}
