package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.junmp.junmpProcess.dto.json.UserInfo;
import com.junmp.jyzb.service.PublicService;
import com.junmp.v2.auth.api.context.LoginContext;
import com.junmp.v2.common.bean.response.ApiRes;
import com.junmp.v2.common.enums.StatusEnum;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.dict.api.bean.req.SysDictItemReq;
import com.junmp.v2.dict.api.bean.vo.SimpleDictItemVo;
import com.junmp.v2.dict.api.bean.vo.SimpleDictVo;
import com.junmp.v2.dict.api.exception.DictException;
import com.junmp.v2.dict.api.exception.DictExceptionEnum;
import com.junmp.v2.dict.entity.SysDict;
import com.junmp.v2.dict.entity.SysDictItem;
import com.junmp.v2.dict.service.SysDictItemService;
import com.junmp.v2.dict.service.SysDictService;
import com.junmp.v2.message.api.MessageApi;
import com.junmp.v2.message.api.bean.req.MessageReq;
import com.junmp.v2.message.api.bean.req.MessageSendReq;
import com.junmp.v2.message.api.enums.MsgReadStateEnum;
import com.junmp.v2.message.db.entity.SysMessage;
import com.junmp.v2.message.db.service.SysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.junmp.junmpProcess.common.CommonConstants.START_USER_INFO;
import static com.junmp.junmpProcess.common.CommonConstants.TYPE_ORDER;

@Service
@Slf4j
public class PublicServiceImpl implements PublicService {

    @Resource
    private SysDictItemService sysDictItemService;
    @Resource
    private SysDictService sysDictService;

    @Resource
    private MessageApi messageApi;
    
    @Resource
    private SysMessageService sysMessageService;
    public Long addDictType(SysDictItemReq req){
        SysDictItem sysDictType = (SysDictItem) BeanPlusUtil.toBean(req, SysDictItem.class);
        LambdaQueryWrapper<SysDictItem> eq = new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId, req.getItemText()).eq(SysDictItem::getItemText, req.getDictId());

        boolean flag = sysDictItemService.count(eq) > 0L;
        if (flag) {
            throw new DictException(DictExceptionEnum.DICT_NAME_REPEAT);
        } else {
            sysDictType.setStatusFlag(StatusEnum.ENABLE.getCode());
            sysDictItemService.save(sysDictType);
        }
        return sysDictType.getDictItemId();
    }

    @Override
    public List<SimpleDictItemVo> findListByDict(Long dictId) {

        LambdaQueryWrapper<SysDictItem> wp = Wrappers.lambdaQuery();
        wp.eq(SysDictItem::getDictId, dictId);
        wp.eq(SysDictItem::getDelFlag,0);
        List<SimpleDictItemVo> voList = BeanPlusUtil.toBeanList(sysDictItemService.list(wp), SimpleDictItemVo.class);
        return voList;
    }

    @Override
    public List<SimpleDictVo> getAllDictItem() {
        List<SysDict> list = sysDictService.list();
        if (CollectionUtil.isNotEmpty(list)) {
            List<SimpleDictVo> tempList = (List)list.stream().map((it) -> {
                SimpleDictVo dict = (SimpleDictVo)BeanPlusUtil.toBean(it, SimpleDictVo.class);
                List<SimpleDictItemVo> itemVoList =findListByDict(dict.getDictId());
                dict.setItemList(itemVoList);
                return dict;
            }).collect(Collectors.toList());
            return tempList;
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMessage(MessageReq req) {
        SysMessage message = sysMessageService.getById(req.getMsgIdList().get(0));
        Long bizId = message.getBizId();
        //将该条消息全设置为已读并且更新再推送一条消息
        List<SysMessage> list = sysMessageService.list(new LambdaQueryWrapper<SysMessage>().eq(SysMessage::getBizId, bizId));
        List<Long> idList = list.stream()
                .map(SysMessage::getMsgId).collect(Collectors.toList());
        messageApi.batchReadFlagByMessageIds(StrUtil.join(",", new Object[]{idList}), MsgReadStateEnum.READ);
        List<Long> userIdList = list.stream().map(SysMessage::getReceiveUserId).collect(Collectors.toList());
        userIdList.forEach(userId ->{
            if (userId!= LoginContext.getContext().getLoginUser().getUserId())//非本人审核单据
            {
                MessageSendReq sendReq = new MessageSendReq();
                sendReq.setReceiveUserIds(String.valueOf(userId));
                sendReq.setMsgTitle("refresh");
                sendReq.setMsgContent("消息更新");
                sendReq.setPriority("1");
                sendReq.setSendTime(DateTime.now());
                messageApi.sendMessage(sendReq);
            }
        });
        return true;
    }

}
