package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.mapper.PubOrgMapper;
import com.junmp.jyzb.service.PublicService;
import com.junmp.v2.common.enums.StatusEnum;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.db.api.entity.BaseEntity;
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.db.entity.SysMessage;
import com.junmp.v2.message.db.service.SysMessageService;
import com.junmp.v2.sys.api.bean.user.req.SysUserReq;
import com.junmp.v2.sys.user.entity.SysUser;
import com.junmp.v2.sys.user.service.SysUserService;
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;

@Service
@Slf4j
public class PublicServiceImpl implements PublicService {

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

    @Resource
    private MessageApi messageApi;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private PubOrgMapper pubOrgMapper;
    
    @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) {
        //将该条消息全设置为已读并且更新再推送一条消息
        List<SysMessage> list1 = sysMessageService.list(new LambdaQueryWrapper<SysMessage>()
                .eq(SysMessage::getBizId, req.getBizId())
                .like(SysMessage::getBizType,"assign"));
        sysMessageService.update(new LambdaUpdateWrapper<SysMessage>()
                .set(SysMessage::getReadFlag,1).set(BaseEntity::getUpdateUser, 123456)
                .eq(SysMessage::getBizId,req.getBizId()).like(SysMessage::getBizType,"assign"));
        List<SysMessage> list = sysMessageService.list(new LambdaQueryWrapper<SysMessage>().eq(SysMessage::getBizId, req.getBizId()));
        List<Long> userIdList = list.stream().map(SysMessage::getReceiveUserId).collect(Collectors.toList());

        MessageSendReq sendReq = new MessageSendReq();
        sendReq.setReceiveUserIds(userIdList.stream()
                .map(Object::toString)
                .collect(Collectors.joining(",")));
        sendReq.setMsgTitle("refresh");
        sendReq.setMsgContent("消息更新");
        sendReq.setBizType("1");
        sendReq.setPriority("1");
        sendReq.setSendTime(DateTime.now());
        messageApi.sendMessageNoToken(sendReq);

        return true;
    }

    //是否需要重定向
    @Override
    public boolean isRedirect(SysUserReq user) {
        //如果该用户不存在，返回false
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getAccount, user.getAccount()));
        if (CollectionUtil.isEmpty(list)){
            return false;
        }
        //如果存在，判断该账号所属组织机构是否使用3.0需要，组织机构表中中的字段值是否为1，是1，则直接返回true，否则直接返回false
        PubOrg pubOrg=pubOrgMapper.isRedirect(user.getAccount());

        if (ObjectUtil.isNull(pubOrg)){
            return false;
        }else {
            return pubOrg.getIsFlag()==1;
        }
    }

}
