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.DateUtil;
import com.crunii.micro.common.utils.DateUtils;
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.dto.Worker;
import com.crunii.micro.domain.entity.main.YcqMessageTemplate;
import com.crunii.micro.domain.entity.main.YcqRollPic;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqMessageTemplateDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqPageMessageTemplate;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqPageMessageTemplateDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqPageRollPicDTO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqMessageTemplateVO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqRollPicVO;
import com.crunii.micro.service.sysmgr.api.enums.PushTerminalEnum;
import com.crunii.micro.service.sysmgr.api.enums.PushTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Repository
public class YcqMessageTemplateDao {

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

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

    private static final String PAGE_BASE_QUERY = "select ymt.*,tw.worker_name createName, tog.org_name  from YCQ_MESSAGE_TEMPLATE ymt inner join tsm_worker_org_all twoa on ymt.org_id=twoa.org_id left join TSM_WORKER tw on ymt.create_id = tw.login_id left join tsm_org tog on tw.org_id = tog.org_id where twoa.worker_id= ?  and ymt.del_flag = 0 ";
    private static final String PAGE_BASE_COUNT_QUERY = "select count(*) from YCQ_MESSAGE_TEMPLATE ymt inner join tsm_worker_org_all twoa on ymt.org_id=twoa.org_id where twoa.worker_id= ?  and ymt.del_flag = 0 ";

    private static final String QUERY_BY_APP = "select * from YCQ_MESSAGE_TEMPLATE where del_flag = 0 and app_id = ?";

    private static final String DELETE_BATCH = "update YCQ_MESSAGE_TEMPLATE set del_flag = 1 , update_id = ? , update_time = ? where template_id in(";


    public PageRsp<YcqMessageTemplateVO> pageQuery(PageReq<YcqPageMessageTemplateDTO> pageRequest, Integer loginId) {
        StringBuilder base = new StringBuilder(PAGE_BASE_QUERY);
        StringBuilder countStr = new StringBuilder(PAGE_BASE_COUNT_QUERY);
        YcqPageMessageTemplateDTO query = pageRequest.getQuery();
        List<Object> params = new ArrayList<>();
        params.add(loginId);
        String title = query.getTitle();
        if (StringUtils.isNotBlank(title)){
            base.append(" and ymt.title like concat('%',?,'%') ");
            countStr.append(" and ymt.title like concat('%',?,'%') ");
            params.add(title);
        }
        String sceneName = query.getSceneName();
        if (StringUtils.isNotBlank(sceneName)){
            base.append(" and ymt.scene_name like concat('%',?,'%') ");
            countStr.append(" and ymt.scene_name like concat('%',?,'%') ");
            params.add(sceneName);
        }
        Long appId = query.getAppId();
        if (null != appId){
            base.append(" and ymt.app_id = ? ");
            countStr.append(" and ymt.app_id = ? ");
            params.add(appId);
        }
        Byte templateType = query.getTemplateType();
        if (null != templateType){
            base.append(" and ymt.template_type = ? ");
            countStr.append(" and ymt.template_type = ? ");
            params.add(templateType);
        }
        Byte status = query.getStatus();
        if (Objects.equals((byte)1, status) || Objects.equals((byte)2 ,status)){
            base.append(" and ymt.status = ? ");
            countStr.append(" and ymt.status = ? ");
            params.add(status);
        }
        Byte pushType = query.getPushType();
        if (Objects.equals(pushType, PushTypeEnum.STATION_MESSAGE.getType()) || Objects.equals(pushType, PushTypeEnum.MOBILE_PHONE_MESSAGE.getType())){
            base.append(" and ymt.push_type like concat('%',?,'%') ");
            countStr.append(" and ymt.push_type like concat('%',?,'%') ");
            params.add(pushType);
        }

        String startTime = query.getStartTime();
        if (StringUtils.isNotBlank(startTime)){
            base.append(" and ymt.create_time >= ? ");
            countStr.append(" and ymt.create_time >= ? ");
            params.add(startTime);
        }

        String endTime = query.getEndTime();
        if (StringUtils.isNotBlank(endTime)){
            base.append(" and ymt.create_time <= ? ");
            countStr.append(" and ymt.create_time <= ? ");
            params.add(endTime);
        }
        int total = JT.queryForInt(countStr.toString(), params.toArray());
        List<YcqMessageTemplateVO> values = new ArrayList<>(pageRequest.getPageSize());
        String dbType = JT.getDbType();
        if (total > 0) {
            //根据数据库类型设置limit
            base.append(" order by ymt.create_time desc ");
            SqlUtil.appendLimit(dbType, params, base, pageRequest);
            List<YcqPageMessageTemplate> ycqRollPicList = JT.queryForBeans(YcqPageMessageTemplate.class, base.toString(), params.toArray());
            ycqRollPicList.forEach(item -> {
                YcqMessageTemplateVO vo = new YcqMessageTemplateVO();
                BeanUtils.copyProperties(item, vo);
                // 转换推送方式和推送终端
                String endpointStr = PushTerminalEnum.convert(item.getPushEndpoint());
                String pushTypeStr = PushTypeEnum.convert(item.getPushType());
                vo.setPushEndpointStr(endpointStr);
                vo.setPushTypeStr(pushTypeStr);
                vo.setCreateTimeStr(DateUtil.format(vo.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                values.add(vo);
            });
        }
        PageRsp<YcqMessageTemplateVO> page = new PageRsp<>();
        page.setPageNo(pageRequest.getPageNo());
        page.setPageSize(pageRequest.getPageSize());
        page.setTotalNum(total);
        page.setResult(values);
        page.next();
        return page;
    }

    public List<YcqMessageTemplate> queryByAppId(Long appId){
        return JT.queryForBeans(YcqMessageTemplate.class, QUERY_BY_APP, appId);
    }

    public Boolean deleteBatch(List<Long> templateIds, Integer loginId){
        String join = templateIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        String s = DELETE_BATCH + join + ");";
        JT.update(s, loginId, new Date());
        return true;
    }
}
