package com.yh.saas.plugin.news.service.impl;


import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.winsea.svc.base.base.entity.CommonDepartment;
import com.winsea.svc.base.base.service.ICommonDepartmentService;
import com.yh.saas.plugin.news.entity.AnnoReadUserInfo;
import com.yh.saas.plugin.news.mapper.NewsAnnoReadUserInfoMapper;
import com.yh.saas.plugin.news.service.INewsAnnoReadUserInfoService;
import com.yh.saas.common.support.util.query.QueryUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 公告模块 - 关联联系人 - 业务实现类
 * </p>
 *
 * @Auther ZhangMingYu
 * @since 2019年8月14日16:00:15
 */
@Service
public class NewsAnnoReadUserInfoServiceImpl extends ServiceImpl<NewsAnnoReadUserInfoMapper, AnnoReadUserInfo> implements INewsAnnoReadUserInfoService {

    @Autowired
    private NewsAnnoReadUserInfoMapper annoReadUserInfoMapper;

    @SofaReference
    private ICommonDepartmentService commonDepartmentService;

    @Override
    public void createAll(List<AnnoReadUserInfo> annoReadUserInfos) {
        if (CollectionUtils.isEmpty(annoReadUserInfos)){
            return;
        }

        annoReadUserInfos.forEach(annoReadUserInfo -> {
            annoReadUserInfo.setIsRead("0");
        });
        insertBatch(annoReadUserInfos);
    }

    @Override
    public void remove(String announcementId) {
        annoReadUserInfoMapper.remove(announcementId);
    }

    @Override
    public List<AnnoReadUserInfo> queryLoginUser(String loginUserId) {
        return selectList(new EntityWrapper<AnnoReadUserInfo>().eq(AnnoReadUserInfo.QueryFiles.READ_USER_ID, loginUserId));
    }

    @Override
    public void haveSee(AnnoReadUserInfo annoReadUserInfo){
        annoReadUserInfo.setIsRead("1");
        boolean update = update(annoReadUserInfo, QueryUtils.convertExampleToWrapper(annoReadUserInfo));
        //说明失败了，原因是因为注册时用的是部门为读取人
        if (!update) {
            CommonDepartment dept = commonDepartmentService.getOneBy(annoReadUserInfo.getReadUserId());
            if (null != dept) {
                String deptId = dept.getDeptId();
                annoReadUserInfo.setReadUserId(deptId);
                update(annoReadUserInfo, QueryUtils.convertExampleToWrapper(annoReadUserInfo));
            }
        }
    }

}
