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


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.domain.common.jdbc.BaseNPJdbcTemplate;
import com.crunii.micro.domain.entitysql.main.TCallLogS;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

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

@Repository
@Slf4j
public class LogJdbcDao {

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

    @Resource(name = "mainNPJT")
    protected BaseNPJdbcTemplate baseNpJdbcTemplate;

    public int cleanLog() {
        String sql = "delete from T_CALL_LOG where create_time < ADD_DAYS(SYSDATE(),-7)";
        HashMap<String, Object> params = Maps.newHashMap();
        return baseNpJdbcTemplate.update(sql, params);
    }

    public int getLogCount() {
        String sql = "select count(*) from T_CALL_LOG";
        HashMap<String, Object> params = Maps.newHashMap();
        return baseNpJdbcTemplate.queryForInt(sql, params);
    }

    public PageRsp<TCallLogS> pageListLogs(PageReq req) {
        StringBuilder sql = new StringBuilder("select * from T_CALL_LOG a");
        StringBuilder countSql = new StringBuilder("select count(*) from T_CALL_LOG a");
        Map<String, Object> params = new HashMap<>(16);
        int total = baseNpJdbcTemplate.queryForInt(countSql.toString(), params);
        List<TCallLogS> result;
        String dbType = baseNpJdbcTemplate.getDbType();
        if (total > 0) {
            //根据数据库类型设置limit
            SqlUtil.appendLimit(dbType, params, sql, req);
            result = baseNpJdbcTemplate.queryForBeans(TCallLogS.class, sql.toString(), params);
        } else {
            result = new ArrayList<>(0);
        }
        PageRsp<TCallLogS> page = new PageRsp<>();
        page.setPageNo(req.getPageNo());
        page.setPageSize(req.getPageSize());
        page.setTotalNum(total);
        page.setResult(result);
        // 为手机计算是否由下一页
        page.next();

        return page;
    }
}
