package com.viettel.campaign.repository.ccms_full.impl;

import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.model.ccms_full.CampaignCustomer;
import com.viettel.campaign.repository.ccms_full.CampaignRepositoryCustom;
import com.viettel.campaign.utils.Constants;
import com.viettel.campaign.utils.DataUtil;
import com.viettel.campaign.utils.HibernateUtil;
import com.viettel.campaign.utils.SQLBuilder;
import com.viettel.campaign.web.dto.CampaignDTO;
import com.viettel.campaign.web.dto.CustomerCustomDTO;
import com.viettel.campaign.web.dto.ResultDTO;
import com.viettel.campaign.web.dto.request_dto.CampaignRequestDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hibernate.type.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.*;

@Repository
public class CampaignRepositoryImpl implements CampaignRepositoryCustom {

    private static final Logger logger = LogManager.getLogger(CampaignRepositoryImpl.class);

    @Autowired
    @PersistenceContext( unitName= DataSourceQualify.JPA_UNIT_NAME_CCMS_FULL)
    EntityManager entityManager;

    @Autowired
    @Qualifier(DataSourceQualify.NAMED_JDBC_PARAMETER_TEMPLATE_CCMS_FULL)
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public ResultDTO search(CampaignRequestDTO requestDto) {
        logger.info("Start search campaign::");

        ResultDTO result = new ResultDTO();
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        if (DataUtil.isNullOrEmpty(requestDto.getCompanySiteId())) {
            result.setErrorCode(Constants.ApiErrorCode.ERROR);
            result.setDescription(Constants.ApiErrorDesc.ERROR);
            return result;
        }
        try {
            StringBuilder sb = new StringBuilder();

            sb.append(" SELECT");
            sb.append("    a.CAMPAIGN_ID campaignId,");
            sb.append("    a.CAMPAIGN_CODE campaignCode,");
            sb.append("    a.CAMPAIGN_NAME campaignName,");
            sb.append("    a.CAMPAIGN_TYPE campaignType,");
            sb.append("    (SELECT PAR_NAME FROM AP_PARAM WHERE STATUS = 1 AND PAR_TYPE = 'CAMPAIGN_TYPE' AND PAR_VALUE = a.CAMPAIGN_TYPE) campaignTypeName,");
            sb.append("    a.CHANEL chanel,");
            sb.append("    a.START_TIME startTime,");
            sb.append("    a.END_TIME endTime,");
            sb.append("    a.CUSTOMER_NUMBER customerNumber,");
            sb.append("    a.STATUS status,");
            sb.append("    a.CUSTOMER_NUMBER cusNum,");
            sb.append("    b.SLKHThamgiaCD numOfJoinedCus,");
            sb.append("    e.SLKHDaTuongTac numOfInteractedCus,");
            sb.append("    c.SLKHChuaTuongTac numOfNotInteractedCus,");
            sb.append("    d.SLKHDoNotCall_Khoa numOfLockCus,");
            sb.append("    a.COMPANY_SITE_ID companySiteId,");
            sb.append("    a.CONTENT content,");
            sb.append("    a.MAX_RECALL maxRecall,");
            sb.append("    a.RECALL_TYPE recallType,");
            sb.append("    a.RECALL_DURATION recallDuration,");
            sb.append("    a.CURRENT_TIME_MODE currentTimeMode,");
            sb.append("    a.WRAPUP_TIME_CONNECT wrapupTimeConnect,");
            sb.append("    a.WRAPUP_TIME_DISCONNECT wrapupTimeDisconnect");
            sb.append(" FROM CAMPAIGN a");
            sb.append(" LEFT JOIN (SELECT campaign_id, COUNT (*) AS SLKHThamgiaCD");
            sb.append("                  FROM   campaign_customer cc INNER JOIN CUSTOMER cus ON cc.CUSTOMER_ID = cus.CUSTOMER_ID");
            sb.append("                  WHERE 1 = 1 AND cc.IN_CAMPAIGN_STATUS = 1 AND cus.STATUS = 1");
            sb.append("                  group by campaign_id) b");
            sb.append(" ON a.CAMPAIGN_ID = b.CAMPAIGN_ID");
            sb.append(" LEFT JOIN (SELECT campaign_id, COUNT (*) AS SLKHChuaTuongTac");
            sb.append("                  FROM   campaign_customer cc INNER JOIN CUSTOMER cus ON cc.CUSTOMER_ID = cus.CUSTOMER_ID");
            sb.append("                  WHERE 1 = 1 AND cc.STATUS = 0 AND cus.STATUS = 1");
            sb.append("                  group by campaign_id) c");
            sb.append(" ON c.CAMPAIGN_ID = a.CAMPAIGN_ID");
            sb.append(" LEFT JOIN (SELECT cc.campaign_id, count(*) AS SLKHDoNotCall_Khoa");
            sb.append("        FROM CAMPAIGN_CUSTOMER cc , CUSTOMER c");
            sb.append("        WHERE cc.CUSTOMER_ID = c.CUSTOMER_ID");
            sb.append("        AND (c.IPCC_STATUS = 'locked' or c.CALL_ALLOWED = 0) AND cc.STATUS = 1");
            sb.append("        GROUP BY cc.CAMPAIGN_ID) d");
            sb.append(" ON d.CAMPAIGN_ID = a.CAMPAIGN_ID");
            sb.append(" LEFT JOIN (SELECT campaign_id, COUNT (*) AS SLKHDaTuongTac");
            sb.append("                  FROM   campaign_customer cc INNER JOIN CUSTOMER cus ON cc.CUSTOMER_ID = cus.CUSTOMER_ID");
            sb.append("                  WHERE 1 = 1 AND cc.STATUS <> 0 AND cus.STATUS = 1");
            sb.append("                  group by campaign_id) e");
            sb.append(" ON e.CAMPAIGN_ID = a.CAMPAIGN_ID");
            sb.append(" WHERE 1 = 1");
            sb.append(" AND COMPANY_SITE_ID = :p_company_site_id");
            sb.append(" AND a.STATUS <> -1");


            if (!DataUtil.isNullOrEmpty(requestDto.getCampaignCode())) {
                sb.append(" AND a.CAMPAIGN_CODE IN (:p_code) ");
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getCampaignName())) {
                sb.append(" AND UPPER(a.CAMPAIGN_NAME) LIKE :p_name");
            }
            if (requestDto.getStatus() != null && requestDto.getStatus() >= 0) {
                sb.append(" AND a.STATUS = :p_status");
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getFromDateFr())) {
                sb.append(" AND TO_DATE(a.START_TIME, 'DD/MM/YYYY') >= :p_frDateFr");
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getToDateFr())) {
                sb.append(" AND TO_DATE(a.START_TIME, 'DD/MM/YYYY') <= :p_toDateFr");
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getFromDateTo())) {
                sb.append(" AND TO_DATE(a.END_TIME, 'DD/MM/YYYY') >= :p_frDateTo");
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getToDateTo())) {
                sb.append(" AND TO_DATE(a.END_TIME, 'DD/MM/YYYY') <= :p_toDateTo");
            }
            if (!DataUtil.isNullOrZero(requestDto.getNumOfCusFr())) {
                sb.append(" AND a.CUSTOMER_NUMBER >= :p_cusNumFr");
            }
            if (!DataUtil.isNullOrZero(requestDto.getNumOfCusTo())) {
                sb.append(" AND a.CUSTOMER_NUMBER <= :p_cusNumTo");
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getTypes())) {
                sb.append(" AND a.CAMPAIGN_TYPE IN (:p_type)");
            }
            if (requestDto.getChanel() != null && !DataUtil.isNullOrZero(requestDto.getChanel())) {
                sb.append(" AND a.CHANEL = :p_chanel");
            }
            if (!DataUtil.isNullOrZero(requestDto.getNumOfCusFr())) {
                sb.append(" AND a.CUSTOMER_NUMBER >= :p_cusNumFr");
            }
            if (!DataUtil.isNullOrZero(requestDto.getNumOfCusTo())) {
                sb.append(" AND a.CUSTOMER_NUMBER <= :p_cusNumTo");
            }

            sb.append(" ORDER BY a.START_TIME DESC ");

            SQLQuery query = session.createSQLQuery(sb.toString());
            if (!DataUtil.isNullOrEmpty(requestDto.getCampaignCode())) {
                String[] lstCode = requestDto.getCampaignCode().split(",");
                query.setParameterList("p_code", lstCode);
            }

            if (!DataUtil.isNullOrEmpty(requestDto.getCampaignName())) {
                query.setParameter("p_name", "%" +
                        requestDto.getCampaignName().toUpperCase()
                                .replace("\\", "\\\\")
                                .replaceAll("%", "\\\\%")
                                .replaceAll("_", "\\\\_")
                        + "%");
            }

            query.setParameter("p_company_site_id", requestDto.getCompanySiteId());

            if (requestDto.getStatus() != null && requestDto.getStatus() >= 0) {
                query.setParameter("p_status", requestDto.getStatus());
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getFromDateFr())) {
                query.setParameter("p_frDateFr", requestDto.getFromDateFr());
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getFromDateTo())) {
                query.setParameter("p_frDateTo", requestDto.getFromDateTo());
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getToDateFr())) {
                query.setParameter("p_toDateFr", requestDto.getToDateFr());
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getToDateTo())) {
                query.setParameter("p_toDateTo", requestDto.getToDateTo());
            }
            if (!DataUtil.isNullOrEmpty(requestDto.getTypes())) {
                String[] types = requestDto.getTypes().split(",");
                query.setParameterList("p_type", types);
            }
            if (requestDto.getChanel() != null && !DataUtil.isNullOrZero(requestDto.getChanel())) {
                query.setParameter("p_chanel", requestDto.getChanel());
            }
            if (!DataUtil.isNullOrZero(requestDto.getNumOfCusFr())) {
                query.setParameter("p_cusNumFr", requestDto.getNumOfCusFr() == 0 ? null : requestDto.getNumOfCusFr());
            }
            if (!DataUtil.isNullOrZero(requestDto.getNumOfCusTo())) {
                query.setParameter("p_cusNumTo", requestDto.getNumOfCusTo() == 0 ? null : requestDto.getNumOfCusTo());
            }

            query.addScalar("campaignId", new LongType());
            query.addScalar("campaignCode", new StringType());
            query.addScalar("campaignName", new StringType());
            query.addScalar("campaignType", new StringType());
            query.addScalar("campaignTypeName", new StringType());
            query.addScalar("chanel", new ShortType());
            query.addScalar("startTime", new DateType());
            query.addScalar("endTime", new DateType());
            query.addScalar("customerNumber", new LongType());
            query.addScalar("status", new ShortType());
            query.addScalar("numOfJoinedCus", new LongType());
            query.addScalar("numOfInteractedCus", new LongType());
            query.addScalar("numOfNotInteractedCus", new LongType());
            query.addScalar("numOfLockCus", new LongType());
            query.addScalar("companySiteId", new LongType());
            query.addScalar("content", new StringType());
            query.addScalar("maxRecall", new IntegerType());
            query.addScalar("recallType", new IntegerType());
            query.addScalar("recallDuration", new IntegerType());
            query.addScalar("currentTimeMode", new LongType());
            query.addScalar("wrapupTimeConnect", new LongType());
            query.addScalar("wrapupTimeDisconnect", new LongType());

            query.setResultTransformer(Transformers.aliasToBean(CampaignDTO.class));
            int count = 0;
            List<CampaignDTO> list = query.list();
            if (list.size() > 0) {
                count = query.list().size();
            }
            if (requestDto.getPage() != null && requestDto.getPageSize() != null) {
                Pageable pageable = SQLBuilder.buildPageable(requestDto);
                if (pageable != null) {
                    query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
                    query.setMaxResults(pageable.getPageSize());
                }
                List<CampaignDTO> data = query.list();
                Page<CampaignDTO> dataPage = new PageImpl<>(data, pageable, count);
                result.setData(dataPage);
            } else {
                List<CampaignDTO> dataExport = query.list();
                result.setData(dataExport);
            }
            result.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            result.setDescription(Constants.ApiErrorDesc.SUCCESS);
        } catch (Exception ex) {
            result.setErrorCode(Constants.ApiErrorCode.ERROR);
            result.setDescription(Constants.ApiErrorDesc.ERROR);
            logger.error(ex.getMessage(), ex);
        } finally {
            session.close();
        }
        return result;
    }

    @Override
    public ResultDTO findByCampaignCode(CampaignRequestDTO requestDto) {
        logger.info("Start search campaign by code::");
        ResultDTO result = new ResultDTO();
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        if (DataUtil.isNullOrEmpty(requestDto.getCompanySiteId())) {
            result.setErrorCode(Constants.ApiErrorCode.ERROR);
            result.setDescription(Constants.ApiErrorDesc.ERROR);
            return result;
        }
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(" SELECT CAMPAIGN_ID campaignId, " +
                    "       CAMPAIGN_CODE campaignCode, " +
                    "       CAMPAIGN_NAME campaignName, " +
                    "       START_TIME startTime," +
                    "       END_TIME endTime, " +
                    "       STATUS status " +
                    " FROM CAMPAIGN" +
                    " WHERE COMPANY_SITE_ID = :p_company_site_id AND STATUS <> -1 ");
            if (!DataUtil.isNullOrEmpty(requestDto.getCampaignCode())) {
                sb.append(" AND CAMPAIGN_CODE LIKE :p_code ");
            }
            sb.append(" ORDER BY START_TIME DESC ");
            SQLQuery query = session.createSQLQuery(sb.toString());
            query.setParameter("p_company_site_id", requestDto.getCompanySiteId());
            if (!DataUtil.isNullOrEmpty(requestDto.getCampaignCode())) {
                query.setParameter("p_code", "%" +
                        requestDto.getCampaignCode().toUpperCase()
                                .replace("\\", "\\\\")
                                .replaceAll("%", "\\\\%")
                                .replaceAll("_", "\\\\_")
                        + "%");
            }
            query.addScalar("campaignId", new LongType());
            query.addScalar("campaignCode", new StringType());
            query.addScalar("campaignName", new StringType());
            query.addScalar("startTime", new DateType());
            query.addScalar("endTime", new DateType());
            query.addScalar("status", new ShortType());

            query.setResultTransformer(Transformers.aliasToBean(CampaignDTO.class));
            int count = 0;
            List<CampaignDTO> list = query.list();
            if (list.size() > 0) {
                count = query.list().size();
            }
            Pageable pageable = SQLBuilder.buildPageable(requestDto);
            if (pageable != null) {
                query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
                query.setMaxResults(pageable.getPageSize());
            }
            List<CampaignDTO> data = query.list();
            Page<CampaignDTO> dataPage = new PageImpl<>(data, pageable, count);
            result.setData(dataPage);
            result.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            result.setDescription(Constants.ApiErrorDesc.SUCCESS);

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.setErrorCode(Constants.ApiErrorCode.ERROR);
            result.setDescription(Constants.ApiErrorDesc.ERROR);
        } finally {
            session.close();
        }
        return result;
    }

    @Override
    public String getMaxCampaignIndex() {
        logger.info("Start search max campaign code index::");
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        try {
            //StringBuilder sb = new StringBuilder();
            //sb.append(SQLBuilder.getSqlQueryById(SQLBuilder.SQL_MODULE_CAMPAIGN_MNG, "get-max-campaign-code-index"));
            StringBuilder sb = new StringBuilder();

            sb.append("SELECT CASE WHEN");
            sb.append("            (SELECT COUNT(1) FROM CAMPAIGN) > 0");
            sb.append("       THEN (SELECT SUBSTR((SELECT CAMPAIGN_CODE FROM CAMPAIGN WHERE CAMPAIGN_ID = (SELECT MAX(CAMPAIGN_ID) FROM CAMPAIGN)),");
            sb.append("                    INSTR((SELECT CAMPAIGN_CODE FROM CAMPAIGN WHERE CAMPAIGN_ID = (SELECT MAX(CAMPAIGN_ID) FROM CAMPAIGN)), '_', -1, 1 )+1) FROM DUAL)");
            sb.append("       ELSE '0'");
            sb.append("       END FROM DUAL");
            SQLQuery query = session.createSQLQuery(sb.toString());
            List<String> list = query.list();
            if (list.size() > 0) {
                return list.get(0);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    @Override
    public ResultDTO checkAllowStatusToPrepare(Long campaignId) {
        logger.info("Start check allow campaign status to prepare::");
        ResultDTO result = new ResultDTO();
        if (DataUtil.isNullOrZero(campaignId)) {
            result.setErrorCode(Constants.ApiErrorCode.ERROR);
            result.setDescription(Constants.ApiErrorDesc.ERROR);
            return result;
        }
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        try {
//            StringBuilder sb = new StringBuilder();
//            sb.append(SQLBuilder.getSqlQueryById(SQLBuilder.SQL_MODULE_CAMPAIGN_MNG, "check-allow-campaign-status-to-prepare"));
            StringBuilder sb = new StringBuilder();

            sb.append(" WITH COUNT_LIST AS (SELECT (SELECT COUNT(1) FROM CAMPAIGN_CUSTOMER WHERE CAMPAIGN_ID = :p_campaignId) countCamp,");
            sb.append("                           (SELECT COUNT(1) FROM CAMPAIGN_AGENT WHERE CAMPAIGN_ID = :p_campaignId)    countAgent,");
            sb.append("                           (select COUNT(1)");
            sb.append("                            FROM SCENARIO s");
            sb.append("                                     INNER JOIN SCENARIO_QUESTION sq ON s.SCENARIO_ID = sq.SCENARIO_ID");
            sb.append("                                     INNER JOIN SCENARIO_ANSWER sa ON sq.SCENARIO_QUESTION_ID = sa.SCENARIO_QUESTION_ID");
            sb.append("                            WHERE s.CAMPAIGN_ID = :p_campaignId)                                      countScenario");
            sb.append("                    FROM DUAL)");
            sb.append(" SELECT c.countCamp          countCamp,");
            sb.append("       c.countAgent         countAgent,");
            sb.append("       c.countScenario      countScenario,");
            sb.append("       CASE");
            sb.append("           WHEN (c.countCamp IS NOT NULL AND c.countAgent IS NOT NULL AND c.countScenario IS NOT NULL) THEN '00'");
            sb.append("           ELSE '01' END as code");
            sb.append(" FROM COUNT_LIST c");

            SQLQuery query = session.createSQLQuery(sb.toString());
            query.setParameter("p_campaignId", campaignId);
            List<Object[]> list = query.list();
            if (list.size() > 0) {
                result.setData(list.get(0));
                result.setErrorCode(Constants.ApiErrorCode.SUCCESS);
                result.setDescription(Constants.ApiErrorDesc.SUCCESS);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.setErrorCode(Constants.ApiErrorCode.ERROR);
            result.setDescription(Constants.ApiErrorDesc.ERROR);
        } finally {
            session.close();
        }
        return result;
    }

    @Override
    public ResultDTO findCustomerListReallocation(CampaignRequestDTO dto) {
        return null;
    }

    @Override
    public ResultDTO reallocationCustomer(CampaignRequestDTO dto) {
        return null;
    }

}
