package com.ssj.dao.sys.schoolmatecircle.dao.impl;

import com.ssj.dao.sys.schoolmatecircle.dao.SchoolmateCircleQueryDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Repository;

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

/**
 * @author Mount Liu
 * @date 2018/8/15
 */
@Repository
public class SchoolmateCircleQueryDaoImpl implements SchoolmateCircleQueryDao {
    @Autowired
    private PagingHibernateJdbcDao dao;

    @Override
    public Map<String, Object> findCircleById(String id,String userId) {
        StringBuilder selSql = new StringBuilder();
        List<Object> queryParams = new ArrayList<>();
        publicCircleSql(selSql,userId);
        selSql.append(" and t1.id = ?");
        queryParams.add(id);
        List<Map<String, Object>> list = dao.findMap(selSql.toString(),queryParams.toArray());
        return list.get(0);
    }

    @Override
    public Page<Map<String, Object>> findCircleByPage(Map<String, Object> searchParams, Pageable pageable) {
        StringBuilder selSql = new StringBuilder();
        List<Object> queryParams = new ArrayList<>();
        String userId= (String) searchParams.get("userId");
        publicCircleSql(selSql, userId);
        //同学圈类型（1：分享圈，2：答题榜）
        int type = (int)searchParams.get("type");
        selSql.append(" and t1.type = ?");
        queryParams.add(type);
        List<String> userIdList = (List)searchParams.get("userIdList");
        if (userIdList != null && userIdList.size() > 0) {
            selSql.append(" and t1.user_id in (");
            for (int i = 0; i < userIdList.size(); i++) {
                String id = userIdList.get(i);
                if (i == userIdList.size() - 1) {
                    selSql.append("'" + id + "'");
                } else {
                    selSql.append("'" + id + "',");
                }
            }
            selSql.append(")");
        } else if(userIdList != null && userIdList.size() == 0){
            selSql.append(" and 1>2 ");
        }
        String maxCreateTime = (String) searchParams.get("maxCreateTime");
        if (StringUtils.isNotBlank(maxCreateTime)) {
            selSql.append(" and t1.create_time <= ?");
            queryParams.add(maxCreateTime);
        }
        selSql.append(" order by t1.create_time desc ");
        return dao.findPage(selSql.toString(), queryParams.toArray(), pageable);
    }

    private void publicCircleSql(StringBuilder selSql, String userId) {
        selSql.append("select t1.*,t2.user_name name,t2.photo photo_url, ")
                .append("case when exists(select 1 from scon_schoolmate_like ")
                .append(" where user_id = '").append(userId).append("'")
                .append(" and t1.id = head_id)" +
                        "    then 1" +
                        "  else 0 end   is_like ")
                .append(" from scon_circle_schoolmate t1" +
                        " left join tb_user t2 on t1.user_id = t2.id " +
                        " where t1.is_delete = 0");
    }



    @Override
    public Page<Map<String, Object>> findFirstCommentByPage(Map<String, Object> searchParams, Pageable pageable) {
        StringBuilder selSql = new StringBuilder();
        String userId= (String) searchParams.get("userId");
        List<Object> queryParams = new ArrayList<>();
        selSql.append("select t1.*, " +
                " t2.user_name commentator, " +
                " t2.photo commentator_url, " +
                " case when exists(select 1 from scon_schoolmate_like where user_id = '" + userId + "' and t1.id = head_id) then 1 else 0 end is_like, " +
                " case when exists(select 1 from scon_circle_schoolmate where user_id = '" + userId + "' and t1.schoolmate_circle_id = id) then 1 else 0 end is_mine, " +
                " (select count(1) from scon_schoolmate_comment where parent_comment_id = t1.id) second_count " +
                " from scon_schoolmate_comment t1 " +
                " left join tb_user t2 on t1.comment_user_id = t2.id " +
                " where t1.parent_comment_id is null ");
        String schoolmateCircleId = (String) searchParams.get("schoolmateCircleId");
        if (StringUtils.isNotBlank(schoolmateCircleId)) {
            selSql.append(" and t1.schoolmate_circle_id = ?");
            queryParams.add(schoolmateCircleId);
        }
        String maxCreateTime = (String) searchParams.get("maxCreateTime");
        if (StringUtils.isNotBlank(maxCreateTime)) {
            selSql.append(" and t1.create_time <= ?");
            queryParams.add(maxCreateTime);
        }
        selSql.append(" order by t1.create_time desc ");
        return dao.findPage(selSql.toString(), queryParams.toArray(), pageable);
    }

    @Override
    public Page<Map<String, Object>> findCommentByPage(Map<String, Object> searchParams, Pageable pageable) {
        StringBuilder selSql = new StringBuilder();
        String userId= (String) searchParams.get("userId");
        List<Object> queryParams = new ArrayList<>();
        publicCommentSql(selSql, userId);
        String commentId = (String) searchParams.get("commentId");
        //用来查询二级评论
        if (StringUtils.isNotBlank(commentId)) {
            selSql.append(" and t1.parent_comment_id = ?");
            queryParams.add(commentId);
        }
        //分享使用（不分一级二级）
        String schoolmateCircleId = (String) searchParams.get("schoolmateCircleId");
        if (StringUtils.isNotBlank(schoolmateCircleId)) {
            selSql.append(" and t1.schoolmate_circle_id = ?");
            queryParams.add(schoolmateCircleId);
        }
        String maxCreateTime = (String) searchParams.get("maxCreateTime");
        if (StringUtils.isNotBlank(maxCreateTime)) {
            selSql.append(" and t1.create_time <= ?");
            queryParams.add(maxCreateTime);
        }
        selSql.append(" order by t1.create_time desc ");
        return dao.findPage(selSql.toString(), queryParams.toArray(), pageable);
    }

    private void publicCommentSql(StringBuilder selSql, String userId) {
        selSql.append("select t1.*, " +
                " t2.id commentator_id," +
                " t2.user_name commentator, " +
                " t2.photo commentator_url, " +
                " t3.user_name be_commented_name," +
                " t4.content be_commented_content, " +
                " case when exists(select 1 from scon_schoolmate_like where user_id = '" + userId + "' and t1.id = head_id) then 1 else 0 end is_like " +
                " from scon_schoolmate_comment t1 " +
                " left join tb_user t2 on t1.comment_user_id = t2.id " +
                " left join tb_user t3 on t1.be_commented_user_id = t3.id " +
                " left join scon_schoolmate_comment t4 on t1.parent_comment_id = t4.id" +
                " where 1=1 ");
    }

    @Override
    public List<Map<String, Object>> findByUserId(String userId) {
        StringBuilder selSql = new StringBuilder();
        List<Object> queryParams = new ArrayList<>();
        selSql.append("select t1.*, " +
                " t2.user_name, " +
                " t2.photo photo_url " +
                " from scon_schoolmate_message t1 " +
                " left join tb_user t2 on t1.operate_user_id = t2.id " +
                " where 1=1 ");
        selSql.append(" and t1.user_id = ?");
        queryParams.add(userId);
        selSql.append(" order by t1.create_time desc ");
        return dao.findMap(selSql.toString(),queryParams.toArray());
    }

    @Override
    public List<Map<String, Object>> findRankingList(int type, int time, int limit) {
        StringBuilder sb = new StringBuilder();
        sb.append("select t1.rank, t1.user_id, t1.count count, t2.wx_name name, t2.photo photo from scon_schoolmate_circle_ranking t1")
                .append(" left join tb_user t2 on t1.user_id=t2.id where type = ? and time = ? order by rank limit ?");
        List<Object> queryParams = new ArrayList<>();
        queryParams.add(type);
        queryParams.add(time);
        queryParams.add(limit);
        return dao.findMap(sb.toString(), queryParams.toArray());
    }

    @Override
    public List<Map<String, Object>> queryLikeCountList(String beginTime, String endTime, int limit) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select user_id, count(1) count from scon_schoolmate_like where create_time BETWEEN ? and ? group by user_id order by count desc limit ?");
        List<Object> queryParams = new ArrayList<>();
        queryParams.add(beginTime);
        queryParams.add(endTime);
        queryParams.add(limit);
        return dao.findMap(sb.toString(), queryParams.toArray());
    }

    @Override
    public List<Map<String, Object>> queryAnswerCountList(String beginTime, String endTime, int limit) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select t1.comment_user_id user_id, count(*) count from scon_schoolmate_comment t1 ")
                .append(" left join scon_circle_schoolmate t2 on t1.schoolmate_circle_id=t2.id and t2.is_delete = 0")
                .append(" where t2.type=2 and t1.parent_comment_id is null or t1.parent_comment_id='' and t1.create_time BETWEEN ")
                .append(" ? and ? order by count desc LIMIT ? ");
        List<Object> queryParams = new ArrayList<>();
        queryParams.add(beginTime);
        queryParams.add(endTime);
        queryParams.add(limit);
        return dao.findMap(sb.toString(), queryParams.toArray());
    }

    @Override
    public List<Map<String, Object>> queryActivityCountList(int time, int limit) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select user_id, sum(score) count from temp_scon_ranking_activity where time=? group by user_id order by count desc limit ?");
        List<Object> queryParams = new ArrayList<>();
        queryParams.add(time);
        queryParams.add(limit);
        return dao.findMap(sb.toString(), queryParams.toArray());
    }

    @Override
    @Modifying
    public void insertLikeScore2Temp(String beginTime, String endTime, int base, int time) {
        StringBuilder sb = new StringBuilder();
        sb.append(" insert into temp_scon_ranking_activity (user_id, score, type, time)")
                .append(" select user_id, count(1)*").append(base).append(" count, 1,").append(time)
                .append(" from scon_schoolmate_like where create_time BETWEEN '").append(beginTime).append("' and '")
                .append(endTime).append("' group by user_id");
        dao.createSQLQuery(sb.toString()).executeUpdate();
    }

    @Override
    @Modifying
    public void insertBeLikeScore2Temp(String beginTime, String endTime, int base, int time) {
        StringBuilder sb = new StringBuilder();
        sb.append(" insert into temp_scon_ranking_activity (user_id, score, type, time)")
                .append(" select user_id, count(1)*").append(base).append(" count, 2,").append(time)
                .append(" from  (select t2.comment_user_id user_id from scon_schoolmate_like t1")
                .append(" left join scon_schoolmate_comment t2 on t1.head_id=t2.id  where t1.type = 2 and t1.create_time BETWEEN '")
                .append(beginTime).append("' and '").append(endTime).append("'")
                .append(" union ")
                .append(" select t4.user_id from scon_schoolmate_like t3 left join scon_circle_schoolmate t4 ")
                .append(" on t3.head_id=t4.id where t3.type = 1 and t3.create_time BETWEEN '")
                .append(beginTime).append("' and '").append(endTime).append("'")
                .append(" ) t5 group by user_id");
        dao.createSQLQuery(sb.toString()).executeUpdate();
    }

    @Override
    @Modifying
    public void insertPushCircleScore2Temp(String beginTime, String endTime, int base, int time) {
        StringBuilder sb = new StringBuilder();
        sb.append(" insert into temp_scon_ranking_activity (user_id, score, type, time)")
                .append(" select user_id, count(1)*").append(base).append(" count, 3,").append(time).append(" from scon_circle_schoolmate ")
                .append(" where create_time BETWEEN '")
                .append(beginTime).append("' and '").append(endTime).append("'")
                .append(" group by user_id");
        dao.createSQLQuery(sb.toString()).executeUpdate();
    }

    @Override
    @Modifying
    public void insertCommentScore2Temp(String beginTime, String endTime, int base, int time) {
        StringBuilder sb = new StringBuilder();
        sb.append(" insert into temp_scon_ranking_activity (user_id, score, type, time)")
                .append(" select comment_user_id user_id, count(1)*").append(base).append(" count, 4,").append(time)
                .append(" from scon_schoolmate_comment")
                .append(" where create_time BETWEEN '")
                .append(beginTime).append("' and '").append(endTime).append("'")
                .append(" group by comment_user_id");
        dao.createSQLQuery(sb.toString()).executeUpdate();
    }

    @Override
    @Modifying
    public void insertAcceptScore2Temp(String beginTime, String endTime, int base, int time) {
        StringBuilder sb = new StringBuilder();
        sb.append(" insert into temp_scon_ranking_activity (user_id, score, type, time)")
                .append(" select comment_user_id user_id, count(1)*").append(base).append(" count, 5,").append(time)
                .append(" from scon_schoolmate_comment where is_accept = 1 and create_time between '")
                .append(beginTime).append("' and '").append(endTime).append("'")
                .append(" group by comment_user_id");
        dao.createSQLQuery(sb.toString()).executeUpdate();
    }

    @Override
    @Modifying
    public void deleteAllInTempTable() {
        StringBuilder sb = new StringBuilder();
        sb.append(" delete from temp_scon_ranking_activity");
        dao.createSQLQuery(sb.toString()).executeUpdate();
    }
}
