package com.ruoyi.message.frequency.interactionmessagerecord.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.controller.req.MessageReadOrDeleteReq;
import com.ruoyi.enums.message.InteractionMessageEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.message.controller.resp.InteractionMessagePageResp;
import com.ruoyi.message.frequency.interactionmessagerecord.entity.InteractionMessageRecord;
import com.ruoyi.message.frequency.interactionmessagerecord.mapper.InteractionMessageRecordMapper;
import com.ruoyi.message.frequency.interactionmessagerecord.service.InteractionMessageRecordService;
import com.ruoyi.push.service.PushService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.utils.wx.wecom.WecomUtil;
import com.ruoyi.vo.PageBasic;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 互动消息记录Service业务层处理
 *
 * @author liwenlong
 * @date 2023-10-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InteractionMessageRecordServiceImpl extends ServiceImpl<InteractionMessageRecordMapper, InteractionMessageRecord> implements InteractionMessageRecordService {
    @Autowired
    private InteractionMessageRecordMapper interactionMessageRecordMapper;

    /**
     * 查询互动消息记录
     *
     * @param id 互动消息记录主键
     * @return 互动消息记录
     */
    @Override
    public InteractionMessageRecord selectInteractionMessageRecordById(Long id) {
        return interactionMessageRecordMapper.selectInteractionMessageRecordById(id);
    }

    /**
     * 查询互动消息记录列表
     *
     * @param interactionMessageRecord 互动消息记录
     * @return 互动消息记录
     */
    @Override
    public List<InteractionMessageRecord> selectInteractionMessageRecordList(InteractionMessageRecord interactionMessageRecord) {
        return interactionMessageRecordMapper.selectInteractionMessageRecordList(interactionMessageRecord);
    }

    /**
     * 新增互动消息记录
     *
     * @param interactionMessageRecord 互动消息记录
     * @return 结果
     */
    @Override
    public int insertInteractionMessageRecord(InteractionMessageRecord interactionMessageRecord) {
        interactionMessageRecord.setCreateTime(DateUtils.getNowDate());
        return interactionMessageRecordMapper.insertInteractionMessageRecord(interactionMessageRecord);
    }

    /**
     * 修改互动消息记录
     *
     * @param interactionMessageRecord 互动消息记录
     * @return 结果
     */
    @Override
    public int updateInteractionMessageRecord(InteractionMessageRecord interactionMessageRecord) {
        interactionMessageRecord.setUpdateTime(DateUtils.getNowDate());
        return interactionMessageRecordMapper.updateInteractionMessageRecord(interactionMessageRecord);
    }

    /**
     * 批量删除互动消息记录
     *
     * @param ids 需要删除的互动消息记录主键
     * @return 结果
     */
    @Override
    public int deleteInteractionMessageRecordByIds(Long[] ids) {
        this.lambdaUpdate().set(InteractionMessageRecord::getDelFlag, PublicCommon.删除).in(InteractionMessageRecord::getId, ids).update();
        return ids.length;
    }

    /**
     * 删除互动消息记录信息
     *
     * @param id 互动消息记录主键
     * @return 结果
     */
    @Override
    public int deleteInteractionMessageRecordById(Long id) {
        this.lambdaUpdate().set(InteractionMessageRecord::getDelFlag, PublicCommon.删除).eq(InteractionMessageRecord::getId, id).update();
        return 1;
    }

    @Autowired
    private UserService userService;

    @Override
    public ResponseData interactionMessagePage(PageBasic req, UserVo userVo) {
        Page<InteractionMessagePageResp> page = this.baseMapper.interactionMessagePage(new Page<>(req.getPageNo(), req.getPageSize()), userVo);

        if (!page.getRecords().isEmpty()) {
            Set<UserVo> userVoSet = page.getRecords().stream().map(resp -> new UserVo(resp.getUserType(), resp.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, userVo);

            page.getRecords().stream().forEach(resp -> {
                resp.setUserInfo(userMap.get(new UserVo(resp.getUserType(), resp.getUserId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Override
    public ResponseData interactionMessageReadOrDelete(MessageReadOrDeleteReq req, UserVo userVo) {
        //1 标记已读 2 删除消息
        switch (req.getType()) {
            case 1:
                this.update().set("is_read", PublicCommon.Message.已读)
                        .eq("user_type", userVo.getUserType())
                        .eq("user_id", userVo.getUserId())
                        .eq("is_read", PublicCommon.Message.未读)
                        .in(CollectionUtil.isNotEmpty(req.getIds()), "id", req.getIds()).update();
                break;
            case 2:

                this.update().set("is_show", PublicCommon.Message.清空)
                        .set("is_read", PublicCommon.Message.已读)
                        .eq("user_type", userVo.getUserType())
                        .eq("user_id", userVo.getUserId())
                        .eq("is_show", PublicCommon.Message.未清空)
                        .in(CollectionUtil.isNotEmpty(req.getIds()), "id", req.getIds()).update();
                break;

            default:
                throw new IllegalStateException("Unexpected value: " + req.getType());
        }
        return ResponseData.success();
    }


    @Autowired
    private PushService pushService;

    @Autowired
    private WecomUtil wecomUtil;

    @Autowired
    private StoreService storeService;

    @Autowired
    private BusinessUtil businessUtil;


    @Override
    public void addInteractionMessage(UserVo userVo, UserVo sendUserVo, Integer messageType, Long objectId, Boolean isPush, InteractionMessageEnums enums) {

        if (!isPush) {
            return;
        }
        if (BusinessUtil.isSelf(userVo, sendUserVo)) {
            return;
        }
        if (sendUserVo == null) {
            return;
        }

        Boolean canPushMessage = businessUtil.canPushMessage(userVo, sendUserVo);
        if (!canPushMessage) {
            return;
        }
        //互动消息
        InteractionMessageRecord messageRecord = new InteractionMessageRecord()
                .setMessageType(messageType)
                .setInteractionUserId(userVo.getUserId())
                .setInteractionUserType(userVo.getUserType())
                .setSkipId(objectId)
                .setObjectId(objectId);

        String title = enums.getTitle();
        String content = enums.getContent();

        messageRecord.setTitle(title);
        messageRecord.setContent(content);

        messageRecord.setType(enums.getCode());

        messageRecord.setUserType(sendUserVo.getUserType())
                .setUserId(sendUserVo.getUserId());

        this.save(messageRecord);

        pushService.push(sendUserVo, objectId, messageRecord.getId(), enums);

        //给表现师发送企业微信消息
        if (ObjectUtil.equal(UserEnums.store.getCode(), sendUserVo.getUserType())) {

            Store store = storeService.getById(sendUserVo.getUserId());

            if (store != null) {

                if (ObjectUtil.isNotEmpty(store.getWecomUserid())) {
                    wecomUtil.sendTextMessage(content, store.getWecomUserid());
                } else {
                    //获取表现师在企业微信中的userid
                    if (ObjectUtil.isNotEmpty(store.getMobile())) {
                        String userid = wecomUtil.getUserid(store.getMobile());
                        if (ObjectUtil.isNotEmpty(userid)) {
                            storeService.lambdaUpdate().set(Store::getWecomUserid, userid).eq(Store::getId, store.getId()).update();
                            wecomUtil.sendTextMessage(content, store.getWecomUserid());
                        }
                    }

                }

            }


        }

    }
}
