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.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.entity.CrmPlatformAnnouncement;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.util.TrimStrMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public class CrmPlatformAnnouncementDao extends DjxBaseDao<CrmPlatformAnnouncement> {

    public void listData(TrimStrMap paras, LayuiPage<Record> page) {
        SqlBuilder sb = new SqlBuilder()
                .line("select c.* from crm_platform_announcement as c")
                .line("where c.status='0'")
                .line(" and c.obj_type=? ")
                .line(buildQuery(paras))
                .line("order by c.create_time desc")
                .limit(page.getPage(), page.getLimit());

        page.setData(Db.find(sb.build(), paras.get("objType")));
        long count = listDataCount(paras);
        page.setCount(count);
    }

    private long listDataCount(TrimStrMap paras) {
        SqlBuilder sb = new SqlBuilder()
                .line("select count(*) from crm_platform_announcement as c")
                .line("where c.status='0'")
                .line(" and c.obj_type=?")
                .line(buildQuery(paras));

        return Db.queryLong(sb.toString(), paras.get("objType"));
    }

    private String buildQuery(TrimStrMap paras) {
        return "";
    }

    /**
     * 消息中心的消息列表。
     */
    public void listMessageData(TrimStrMap paras, LayuiPage<Record> page) {



        User user = UserUtils.getUser();
        String userId = user.getId();

        SqlBuilder sb = new SqlBuilder()

               .line( " SELECT c.*,b.id as bid,b.`read_id` FROM `crm_platform_announcement` c  ")
                .line(" LEFT JOIN `crm_announcement_readinfo` b ON c.id=b.`platform_announcement_id`")
                .line(" AND b.`read_id`= ? ")
                .line(" WHERE c.`obj_type`=? AND c.`status`='0'")
                .line(queryCondition(paras))
                .line("order by c.create_time desc")
                .limit(page.getPage(), page.getLimit());
        page.setData(Db.find(sb.build(), userId,paras.get("objType")));
        long count = listMessageDataCount(paras, userId,paras.get("objType"));
        page.setCount(count);
    }

    //服务商通知公告搜索条件
    public String queryCondition(Map<String,String> map){
        if(map ==null || map.size()==0){
            return "";
        }
        SqlBuilder sb = new SqlBuilder();
        if(StringUtils.isNotBlank(map.get("applyTimeSta"))){
           sb.line("and c.create_time >= '" + map.get("applyTimeSta") + " 00:00:00' ");
        }
        if(StringUtils.isNotBlank(map.get("applyTimeEnd"))){
            sb.line("and c.create_time <= '" + map.get("applyTimeEnd") + " 23:59:59' ");
        }
        if(StringUtils.isNotBlank(map.get("read"))){
            String read = map.get("read"); // 1,表示已读，0:表示未读
            if("1".equals(read)) {
                sb.line("and b.read_id is not null ");
            } else if ("0".equals(read)) {
                sb.line("and b.read_id is null ");
            }
        }
        return sb.toString();
    }


    /**
     * 公告消息的数量。
     */
    private long listMessageDataCount(TrimStrMap parasMap, String userId, String objType) {

        SqlBuilder sb = new SqlBuilder()
                .line("select count(*) from crm_platform_announcement as c")
                .line("LEFT JOIN `crm_announcement_readinfo` AS b ")
                .line("ON c.`id`=b.platform_announcement_id AND b.read_id=? ")
                .line("where c.status='0'")
                .line("and c.`obj_type`=?")
                .line(queryCondition(parasMap));

        return Db.queryLong(sb.toString(), userId,objType);
    }

    public long unReadMsgCount() {
        User user = UserUtils.getUser();
        // 2.管理人员，3.服务商
        String userType = user.getUserType();
        String objType = userTypeToObjType(userType);

        SqlBuilder sb = new SqlBuilder()
                .line("SELECT COUNT(*)")
                .line("FROM `crm_platform_announcement` AS a WHERE NOT EXISTS(")
                .line("  SELECT 1 FROM `crm_announcement_readinfo` AS b WHERE b.`platform_announcement_id`=a.`id` AND b.`read_id`=? ")
                .line(")")
                .line("AND FIND_IN_SET(?, a.`obj_type`)");

        return Db.queryLong(sb.build(), user.getId(), objType);
    }

    private static String userTypeToObjType(String userType) {
        String objType = "";
        if ("2".equals(userType)) {
            objType = "1"; //
        } else if ("3".equals(userType)) {
            objType = "2"; // 服务商
        }else if ("5".equals(userType)) {//服务商人员
            objType = "2"; // 服务商
        }

        return objType;
    }

    public Record findAnnouncementOne(String userId){
        SqlBuilder sb = new SqlBuilder()
                .line( " SELECT c.id,c.title,c.html,b.id as bid,b.`read_id` FROM `crm_platform_announcement` c  ")
                .line(" LEFT JOIN `crm_announcement_readinfo` b ON c.id=b.`platform_announcement_id`")
                .line(" AND b.`read_id`= ? ",userId)
                .line(" WHERE c.`obj_type`='3' AND c.`status`='0'  AND b.id IS NULL ORDER BY c.create_time DESC LIMIT 1  ");
        return Db.findFirst(sb.build(),sb.params());

    }

    public List<Record> indexGetAnnounceList(String userId){
        SqlBuilder sb = new SqlBuilder()
                .line( " SELECT c.id,c.obj_type,c.title,c.html,b.id as bid,b.`read_id`,DATE_FORMAT(c.create_time,'%Y-%m-%d %H:%i') AS createTime FROM `crm_platform_announcement` c  ")
                .line(" LEFT JOIN `crm_announcement_readinfo` b ON c.id=b.`platform_announcement_id`")
                .line(" AND b.`read_id`= ? ",userId)
                .line(" WHERE  c.`status`='0'  ORDER BY c.create_time DESC LIMIT 4  ");
        return Db.find(sb.build(),sb.params());
    }

}
