package com.crunii.micro.service.sysmgr.jdbc;

import com.crunii.micro.common.constants.CommonConstants;
import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.dto.PageRsp;
import com.crunii.micro.common.utils.SqlUtil;
import com.crunii.micro.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.service.sysmgr.constants.SysmgrConstants;
import com.crunii.micro.service.sysmgr.dto.sysmgr.MessagePageDto;
import com.crunii.micro.service.sysmgr.dto.sysmgr.MessagePageVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author baoxy
 * @date 2023-07-17
 */
@Repository
public class MessageNoticeJdbcDao {

    @Resource(name = "mainJT")
    protected BaseJdbcTemplate jt;

    public static final String PAGE_SEARCH_SQL = "select * from (select notice_id, title, content, create_time, type from ycq_message_notice " +
            "where state = ? and type = ? union all select notice_id, title, content, create_time, type from ycq_message_notice " +
            "where state = ? and type = ? and worker_id = ?) a where 1=1 ";

    public static final String PAGE_SEARCH_COUNT_SQL = "select count(*) from (select notice_id, title, content, create_time, type " +
            "from ycq_message_notice where state = ? and type = ? union all select notice_id, title, content, create_time, type from " +
            "ycq_message_notice where state = ? and type = ? and worker_id = ?) a where 1=1 ";

    public PageRsp<MessagePageVo> pageSearch(PageReq<MessagePageDto> req, int loginId) {
        StringBuilder sql = new StringBuilder(PAGE_SEARCH_SQL);
        StringBuilder countSql = new StringBuilder(PAGE_SEARCH_COUNT_SQL);
        List<Object> param = new ArrayList<>();
        param.add(CommonConstants.STATE_VALID);
        param.add(SysmgrConstants.TYPE_COMMON);
        param.add(CommonConstants.STATE_VALID);
        param.add(SysmgrConstants.TYPE_WORKER);
        param.add(loginId);
        if (StringUtils.isNotBlank(req.getQuery().getSearchContent())) {
            sql.append(" and title like ? ");
            countSql.append(" and title like ? ");
            param.add("%" + req.getQuery().getSearchContent() + "%");
        }
        int total = jt.queryForInt(countSql.toString(), param.toArray());
        List<MessagePageVo> result;
        String dbType = jt.getDbType();
        if (total > 0) {
            sql.append(" order by create_time desc ");
            SqlUtil.appendLimit(dbType, param, sql, req);
            result = jt.queryForBeans(MessagePageVo.class, sql.toString(), param.toArray());
        } else {
            result = new ArrayList<>();
        }
        PageRsp<MessagePageVo> rsp = new PageRsp<>();
        rsp.setResult(result);
        rsp.setTotalNum(total);
        rsp.setPageNo(req.getPageNo());
        rsp.setPageSize(req.getPageSize());
        return rsp;
    }
}
