package com.sifang.modules.sys.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.entity.CrmAnnouncementReadinfo;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.util.SqlUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
public class CrmAnnouncementReadInfoDao extends DjxBaseDao<CrmAnnouncementReadinfo> {

    /**
     * 标记消息为已读。
     */
    public Result<Void> markMsgAsRead(String[] markIdList) {

        if (markIdList == null || markIdList.length <= 0) {
            return Result.ok();
        }

        User user = UserUtils.getUser();
        String readerType = "1";

        String parentId = CrmUtils.getUserRelId(user);
        String username = CrmUtils.getUserXM(user);

        // 找出用户勾选的公告中已经阅读过的公告
        SqlBuilder sb = new SqlBuilder()
                .line("select platform_announcement_id from crm_announcement_readinfo")
                .line("where read_id=? and platform_announcement_id in(" + SqlUtils.inParam(markIdList) + ")");

        List<Record> readRecords = Db.find(sb.build(), user.getId());
        List<String> readIds = new ArrayList<>();
        for (Record r : readRecords) {
            readIds.add(r.getStr("platform_announcement_id"));
        }

        // 找出未阅读的公告，未阅读的公告=用户勾选的公告 - 已经阅读过的公告
        List<String> unReadIds = new ArrayList<>();
        for (String id : markIdList) {
            if (!readIds.contains(id)) {
                unReadIds.add(id);
            }
        }

        for (String id : unReadIds) {
            CrmAnnouncementReadinfo info = new CrmAnnouncementReadinfo();
            info.setReadId(user.getId());
            info.setReader(username);
            info.setPlatformAnnouncementId(id);
            info.setStatus("1");
            info.setCreateTime(new Date());
            info.setReaderType(readerType);
            info.setParentId(parentId);
            save(info);
        }

        return Result.ok();
    }

    private static boolean contains(String[] list, String val) {
        for (String v : list) {
            if (val.equals(v)) {
                return true;
            }
        }

        return false;
    }

    public boolean hasRead(String announcementId) {
        SqlBuilder sb = new SqlBuilder()
                .line("select platform_announcement_id from crm_announcement_readinfo")
                .line("where read_id=? and platform_announcement_id=?");

        return Db.findFirst(sb.build(), UserUtils.getUser().getId(), announcementId) != null;
    }
}
