package com.willalp.msg.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.common.core.domain.entity.SysDictData;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.framework.websocket.WebSocketUsers;
import com.willalp.msg.domain.HsAppUserMsg;
import com.willalp.msg.mapper.HsAppUserMsgMapper;
import com.willalp.msg.service.IHsAppUserMsgService;
import com.willalp.system.service.ISysDictTypeService;
import com.willalp.wx.service.WxMsgService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * APP用户消息Service业务层处理
 *
 * @author willalp
 * @date 2022-10-26
 */
@Service
public class HsAppUserMsgServiceImpl extends ServiceImpl<HsAppUserMsgMapper, HsAppUserMsg> implements IHsAppUserMsgService {
    @Resource
    private HsAppUserMsgMapper hsAppUserMsgMapper;

    @Resource
    private WxMsgService wxMsgService;

    @Resource
    private ISysDictTypeService sysDictTypeService;

    /**
     * 查询APP用户消息列表
     *
     * @param hsAppUserMsg APP用户消息
     * @return APP用户消息
     */
    @Override
    public List<HsAppUserMsg> selectHsAppUserMsgList(HsAppUserMsg hsAppUserMsg) {
        return hsAppUserMsgMapper.selectHsAppUserMsgList(hsAppUserMsg);
    }

    @Override
    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.SECONDS)
    public void pushMsgSum() {
        List<HsAppUserMsg> msgs = hsAppUserMsgMapper.selectList(new QueryWrapper<HsAppUserMsg>()
                .eq("msg_is_read", "0"));
        userMsgStatPush(msgs);
    }

    @Override
    public void readReceiptVerify(String userCode) {
        List<HsAppUserMsg> msgsByUserCode = hsAppUserMsgMapper.selectList(new QueryWrapper<HsAppUserMsg>()
                .eq("msg_is_read", "0").eq("user_code", userCode));
        if (msgsByUserCode.size() > 0) {
            userMsgStatPush(msgsByUserCode);
        } else {
            List<SysDictData> appMsgType = sysDictTypeService.selectDictDataByType("app_msg_type");
            if (null == appMsgType || appMsgType.size() <= 0) {
                throw new BaseException("消息推送配置错误：【请配置字典】");
            }
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < appMsgType.size(); i++) {
                //jsonObj key -> m1 ~ m[n]
                jsonObject.put("m" + (i + 1), 0);
            }
            if (null != WebSocketUsers.getUsers().get(userCode)) {
                WebSocketUsers.sendMessageToUserByText(WebSocketUsers.getUsers().get(userCode), jsonObject.toString());
            }
        }
    }

    private void userMsgStatPush(List<HsAppUserMsg> msgs) {
        List<SysDictData> appMsgType = sysDictTypeService.selectDictDataByType("app_msg_type");
        if (null == appMsgType || appMsgType.size() <= 0) {
            throw new BaseException("消息推送配置错误：【请配置字典】");
        }
        Map<String, JSONObject> userMap = new HashMap<>();
        msgs.forEach((item) -> {
            if (StringUtils.isNotBlank(item.getUserCode()) && null != userMap.get(item.getUserCode())) {
                userMap.get(item.getUserCode()).put("m" + item.getMsgType(), (Integer) userMap.get(item.getUserCode()).get("m" + item.getMsgType()) + 1);
            } else {
                if (StringUtils.isNotBlank(item.getUserCode())) {
                    //初始化Map<用户编号,JSONObj>
                    JSONObject jsonObject = new JSONObject();
                    for (int i = 0; i < appMsgType.size(); i++) {
                        //jsonObj key -> m1 ~ m[n]
                        jsonObject.put("m" + (i + 1), 0);
                    }
                    jsonObject.put("m" + item.getMsgType(), 1);
                    userMap.put(item.getUserCode(), jsonObject);
                }
            }
        });
        userMap.forEach((k, v) -> {
            if (null != WebSocketUsers.getUsers().get(k)) {
                WebSocketUsers.sendMessageToUserByText(WebSocketUsers.getUsers().get(k), v.toString());
            }
        });
    }

    @Override
    public void readMsgByTaskId(String taskId, String userCode) {
        hsAppUserMsgMapper.readMsgByTaskId(taskId, userCode);
    }

    @Override
    public void readMsgById(String id) {
        if (StringUtils.isNotBlank(id)) {
            hsAppUserMsgMapper.readMsgById(id);
        }
    }

    @Override
    public void allReadMsgByUserCode(String uc) {
        if (StringUtils.isNotBlank(uc)) {
            hsAppUserMsgMapper.allReadMsgByUserCode(uc);
        }
    }

    @Override
    public void saveApprovalMsgAndPush(String msgType, String title, String content, String taskId, String sendUser, String applyUn, Date createTime) {
        HsAppUserMsg appUserMsg = new HsAppUserMsg();
        appUserMsg.setMsgTitle(title);
        appUserMsg.setMsgContent(content);
        appUserMsg.setMsgIsRead("0");
        appUserMsg.setUserCode(sendUser);
        appUserMsg.setMsgType(msgType);
        appUserMsg.setRemark(taskId);
        appUserMsg.setIsPush("0");
        appUserMsg.setCreateTime(createTime);
        save(appUserMsg);
        wxMsgService.sendApprovalMsg(title, sendUser, applyUn, createTime);
    }

}
