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.service.sysmgr.api.domain.dto.YcqMessageQueryKeywordDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqPageUserMessageRecordDTO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqPageMessageRecordVO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqPageUserMessageRecordVO;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

@Repository
public class YcqMessageRecordDao {

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

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

    private static final String PAGE_BASE_QUERY = "select\n" +
            "\tymr.*,\n" +
            "\ttw.worker_name userName,\n" +
            "\ttw.position userType,\n" +
            "\t(case\n" +
            "\t\twhen tw.sex = 1 then '男'\n" +
            "\t\telse '女'\n" +
            "\tend)  as gender\n" +
            "from\n" +
            "\tYCQ_MESSAGE_RECORD ymr\n" +
            "left join TSM_WORKER tw on\n" +
            "\tymr.login_id = tw.login_id where 1=1 ";
    private static final String PAGE_BASE_COUNT_QUERY = "select count(*) from YCQ_MESSAGE_RECORD ymr left join TSM_WORKER tw on ymr.login_id = tw.login_id  where 1=1 ";

    public PageRsp<YcqPageMessageRecordVO> pageQuery(PageReq<YcqMessageQueryKeywordDTO> pageRequest) {
        StringBuilder base = new StringBuilder(PAGE_BASE_QUERY);
        StringBuilder countStr = new StringBuilder(PAGE_BASE_COUNT_QUERY);
        YcqMessageQueryKeywordDTO query = pageRequest.getQuery();
        List<Object> params = new ArrayList<>();
        if (query != null){
            String keyword = query.getKeyword();
            if (StringUtils.isNotBlank(keyword)){
                base.append(" and tw.worker_name like concat('%',?,'%') ");
                countStr.append(" and tw.worker_name like concat('%',?,'%') ");
                params.add(keyword);
            }
            String loginIdStr = query.getLoginIdStr();
            if (StringUtils.isNotBlank(loginIdStr)){
                base.append(" and ymr.login_id like concat('%',?,'%') ");
                countStr.append(" and ymr.login_id like concat('%',?,'%') ");
                params.add(loginIdStr);
            }
            String sendId = query.getSendId();
            if (StringUtils.isNotBlank(sendId)){
                base.append(" and send_id = ? ");
                countStr.append(" and send_id = ? ");
                params.add(sendId);
            }
        }
        int total = JT.queryForInt(countStr.toString(), params.toArray());
        List<YcqPageMessageRecordVO> values = new ArrayList<>(pageRequest.getPageSize());
        String dbType = JT.getDbType();
        if (total > 0) {
            base.append(" order by ymr.push_time desc ");
            //根据数据库类型设置limit
            SqlUtil.appendLimit(dbType, params, base, pageRequest);
            values = JT.queryForBeans(YcqPageMessageRecordVO.class, base.toString(), params.toArray());
        }
        PageRsp<YcqPageMessageRecordVO> page = new PageRsp<>();
        page.setPageNo(pageRequest.getPageNo());
        page.setPageSize(pageRequest.getPageSize());
        page.setTotalNum(total);
        page.setResult(values);
        page.next();
        return page;
    }

    public List<YcqPageMessageRecordVO> list(YcqMessageQueryKeywordDTO req) {
        StringBuilder base = new StringBuilder(PAGE_BASE_QUERY);
        List<Object> params = new ArrayList<>();
        String keyword = req.getKeyword();
        if (StringUtils.isNotBlank(keyword)){
            base.append(" and ymr.user_name like concat('%',?,'%') ");
            params.add(keyword);
        }
        String loginIdStr = req.getLoginIdStr();
        if (StringUtils.isNotBlank(loginIdStr)){
            base.append(" and ymr.login_id like concat('%',?,'%') ");
            params.add(loginIdStr);
        }
        String sendId = req.getSendId();
        if (StringUtils.isNotBlank(sendId)){
            base.append(" and send_id = ? ");
            params.add(sendId);
        }
        base.append(" order by ymr.push_time desc ");
        return JT.queryForBeans(YcqPageMessageRecordVO.class, base.toString(), params.toArray());
    }

    public PageRsp<YcqPageUserMessageRecordVO> pageUserMessage(PageReq<YcqPageUserMessageRecordDTO> req, Integer loginId) {
        String base = "select ymr.id, tm.worker_name sendName, ymr.data_title, ymr.message_content, ymr.push_time, ymr.is_read ,  ymr.path_and_json from ycq_message_record ymr left join TSM_WORKER tm on ymr.send_login_id = tm.login_id where ymr.login_id = ? ";
        String count = "select count(0) c from ycq_message_record ymr left join TSM_WORKER tm on ymr.login_id = tm.login_id where  ymr.login_id = ?  ";
        StringBuilder baseBuilder = new StringBuilder(base);
        StringBuilder countBuilder = new StringBuilder(count);
        List<Object> params = new ArrayList<>();
        params.add(loginId);
        YcqPageUserMessageRecordDTO query = req.getQuery();
//        String pushType = query.getPushType();
//        if (StringUtils.isNotBlank(pushType)){
//            baseBuilder.append(" and ymr.send_way = ? ");
//            countBuilder.append(" and ymr.send_way = ? ");
//            params.add(pushType);
//        }
//        String pushEndpoint = query.getPushEndpoint();
//        if (StringUtils.isNotBlank(pushEndpoint)){
//            baseBuilder.append(" and ymr.message_type = ? ");
//            countBuilder.append(" and ymr.message_type = ? ");
//            params.add(pushEndpoint);
//        }
        String messageContent = query.getMessageContent();
        if (StringUtils.isNotBlank(messageContent)){
            baseBuilder.append(" and ymr.message_content like concat('%',?,'%') ");
            countBuilder.append(" and ymr.message_content like concat('%',?,'%') ");
            params.add(messageContent);
        }
        String dataTitle = query.getDataTitle();
        if (StringUtils.isNotBlank(dataTitle)){
            baseBuilder.append(" and ymr.data_title like concat('%',?,'%') ");
            countBuilder.append(" and ymr.data_title like concat('%',?,'%') ");
            params.add(dataTitle);
        }
        String sendName = query.getSendName();
        if (StringUtils.isNotBlank(sendName)){
            baseBuilder.append(" and tm.worker_name like concat('%',?,'%') ");
            countBuilder.append(" and tm.worker_name like concat('%',?,'%') ");
            params.add(sendName);
        }
        Integer isRead = query.getIsRead();
        if (null != isRead){
            baseBuilder.append(" and ymr.is_read = ? ");
            countBuilder.append(" and ymr.is_read = ? ");
            params.add(isRead);
        }
        String startTime = query.getStartTime();
        if (StringUtils.isNotBlank(startTime)){
            baseBuilder.append(" and ymr.push_time >= ? ");
            countBuilder.append(" and ymr.push_time >= ? ");
            params.add(startTime);
        }

        String endTime = query.getEndTime();
        if (StringUtils.isNotBlank(endTime)){
            baseBuilder.append(" and ymr.push_time <= ? ");
            countBuilder.append(" and ymr.push_time <= ? ");
            params.add(endTime);
        }
        int total = JT.queryForInt(countBuilder.toString(), params.toArray());
        List<YcqPageUserMessageRecordVO> values = new ArrayList<>(req.getPageSize());
        String dbType = JT.getDbType();
        if (total > 0) {
            //根据数据库类型设置limit
            baseBuilder.append(" order by ymr.is_read ");
            SqlUtil.appendLimit(dbType, params, baseBuilder, req);
            values = JT.queryForBeans(YcqPageUserMessageRecordVO.class, baseBuilder.toString(), params.toArray());
        }
        PageRsp<YcqPageUserMessageRecordVO> page = new PageRsp<>();
        page.setPageNo(req.getPageNo());
        page.setPageSize(req.getPageSize());
        page.setTotalNum(total);
        page.setResult(values);
        page.next();
        return page;
    }

    public void batchRead(List<Long> ids, Integer loginId) {
        String sql = "update YCQ_MESSAGE_RECORD set is_read = 1 where login_id = ? and id in(";
        String str = ids.stream().map(item -> item + "").collect(Collectors.joining(","));
        sql = sql + str + ")";
        JT.update(sql, loginId);
    }
}
