package com.boman.web.core.service.bomanMessageReceive;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.DateUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.UpdateDto;
import com.boman.web.core.mapper.MessageMapper;
import com.boman.web.core.service.common.ICommonService;
import com.boman.web.core.service.select.IBaseSelectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.List;

import static com.boman.common.core.utils.obj.ObjectUtils.*;

/**
 * @author tjf
 * @Date: 2021/07/06/15:29
 */
@Service
public class BomanMessageReceiveServiceImpl implements IBomanMessageReceiveService{

    private static final String BOMAN_MESSAGE_RECEIVE = "boman_message_receive";
    private static final String STATUS = "status";
    private static final String STATUS_N = "未读";
    private static final String STATUS_Y = "已读";
    private static final String MESSAGE_ID = "message_id";
    private static final String DELETED = "D";
    private static final String TOTAL = "total";
    private static final String NOT_READ = "notRead";
    private static final String READ = "read";
    private static final String VISIBLE = "visible";

    @Autowired
    private IBaseSelectService selectService;
    @Autowired
    private MessageMapper messageMapper;
    @Resource
    private ICommonService commonService;

    /**
     * 根据发文id查询出该发文所选人员名称和部门
     *
     * @param messageId messageId
     * @return AjaxResult
     */
    @Override
    public AjaxResult getUserNameAndDeptName(String messageId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message_id", messageId);
        List<JSONObject> list = selectService.getByMap("boman_message_receive", jsonObject);
        if (isEmpty(list)) {
            return AjaxResult.success(ifNullSetEmpty(list));
        }

        for (JSONObject json : list) {
            String userName = json.getString("receive_user_name");
            String deptName = json.getString("receive_dept_name");
            // {@link com.boman.system.service.impl.SysUserServiceImpl.listUserTree} 名称保持一致 （王梦韦）
            json.put("userName", userName);
            json.put("deptName", deptName);
        }

        return AjaxResult.success(list);
    }

    /**
     * 小程序首页统计
     * @param userId
     * @return
     */
    @Override
    public AjaxResult getIndexInfo(String userId) {
        //查询今日发文
        Long toDaySend = messageMapper.getIndexCountInfo(Long.valueOf(userId), DateUtils.getDate());

        JSONObject jsonObjectTwo = new JSONObject();
        jsonObjectTwo.put("receive_user_id",userId);
        jsonObjectTwo.put("visible","Y");
        jsonObjectTwo.put("is_del","N");
        List<JSONObject> bomanMessageReceive = selectService.getByMap("boman_message_receive", jsonObjectTwo);
        long unread = 0L;
        long read = 0L;
        long todayReceipt = 0L;
        if (bomanMessageReceive != null && bomanMessageReceive.size() > 0){
            //未读
            unread = bomanMessageReceive.stream().filter(e -> e.get("status").equals(STATUS_N)).count();
            //已读
            read = bomanMessageReceive.stream().filter(e -> e.get("status").equals(STATUS_Y)).count();
            //今日收文
             todayReceipt = bomanMessageReceive.stream().filter(e -> DateUtils.formatDate(e.get("send_message_time").toString(), DateUtils.YYYY_MM_DD).equals(DateUtils.getDate())).count();
        }

        Map<String,Long> map = new HashMap<>(4);
        map.put("toDaySend", toDaySend);
        map.put("unread", unread);
        map.put("read", read);
        map.put("todayReceipt", todayReceipt);
        return AjaxResult.success(map);
    }

    /**
     * 功能描述: 根据messageId撤回消息
     *
     * @param messageId messageId
     * @return int
     */
    @Override
    public int withdrawByMessageId(Long messageId) {
        requireNonNull(messageId, "撤回时, 发文id为空");
        UpdateDto dto = new UpdateDto();
        dto.setTableName(BOMAN_MESSAGE_RECEIVE);

        JSONObject commitData = new JSONObject();
        commitData.put(STATUS, DELETED);

        JSONObject condition = new JSONObject();
        condition.put(MESSAGE_ID, messageId);

        dto.setCommitData(commitData);
        dto.setCondition(condition);
        return commonService.update(dto);
    }

    /**
     * 功能描述: 读取发文和未读取发文的人数统计
     *
     * @param messageId messageId
     * @return com.boman.domain.dto.AjaxResult
     */
    @Override
    public AjaxResult statisticRecieve(Long messageId) {
        requireNonNull(messageId, "statisticRecieve, 发文id为空");

        JSONObject condition = new JSONObject();
        condition.put(MESSAGE_ID, messageId);
        condition.put(VISIBLE, "Y");
        List<JSONObject> recieves = commonService.getByMap(BOMAN_MESSAGE_RECEIVE, condition);
        requireNonNull(recieves, String.format("根据发文id: [%s], 未找到对应的收文列表", messageId));

        int notRead = 0, read = 0;
        for (JSONObject recieve : recieves) {
            String status = recieve.getString(STATUS);
            if (STATUS_N.equals(status)) {
                notRead++;
            } else if (STATUS_Y.equals(status)) {
                read++;
            }
        }

        JSONObject result = new JSONObject();
        result.put(TOTAL, recieves.size());
        result.put(NOT_READ, notRead);
        result.put(READ, read);
        return AjaxResult.success(result);
    }
}
