package com.viettel.campaign.repository.impl;

import com.viettel.campaign.repository.CampaignExecuteRepository;
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.ApParamDTO;
import com.viettel.campaign.web.dto.ContactCustResultDTO;
import com.viettel.campaign.web.dto.ResultDTO;
import com.viettel.campaign.web.dto.request_dto.CampaignRequestDTO;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hibernate.type.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {

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

    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    EntityManager entityManager;

    @Override
    public List<ApParamDTO> getComboBoxStatus(String companySiteId, String completeType) {
        List<ApParamDTO> list = new ArrayList<>();
        Map<String, String> params = new HashMap<>();
        String sql = SQLBuilder.getSqlQueryById(Constants.SQL_MODULES.MODULE_EXECUTE, "get-combo-connect-status");
        try {
            params.put("p_company_site_id", companySiteId);
            params.put("p_complete_type", completeType);
            list = namedParameterJdbcTemplate.query(sql, params, BeanPropertyRowMapper.newInstance(ApParamDTO.class));
//            list = namedParameterJdbcTemplate.getJdbcTemplate().query(sql, (PreparedStatementSetter) params, BeanPropertyRowMapper.newInstance(ComboBoxDTO.class));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return list;
    }

    @Override
    public List<ApParamDTO> getComboCampaignType(String companySiteId) {
        List<ApParamDTO> list = new ArrayList<>();
        Map<String, String> params = new HashMap<>();
        String sql = SQLBuilder.getSqlQueryById(Constants.SQL_MODULES.MODULE_EXECUTE, "get-combo-campaign-type");
        try {
            params.put("p_company_site_id", companySiteId);
            list = namedParameterJdbcTemplate.query(sql, params, BeanPropertyRowMapper.newInstance(ApParamDTO.class));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return list;
    }

    @Override
    public ResultDTO getInteractiveResult(CampaignRequestDTO dto) {
        ResultDTO resultDTO = new ResultDTO();
        List<ContactCustResultDTO> list = new ArrayList<>();
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        StringBuilder sqlBuilder = new StringBuilder();
        try {
            String sql = SQLBuilder.getSqlQueryById(Constants.SQL_MODULES.MODULE_EXECUTE, "get-execute-interactive");
            sqlBuilder.append(sql);

            if (!DataUtil.isNullOrEmpty(dto.getCampaignName().trim())) {
                sqlBuilder.append(" and upper(campaignName) like upper(:p_campaign_name)");
            }
            if (!DataUtil.isNullOrEmpty(dto.getAgentId().trim())) {
                sqlBuilder.append(" and upper(userName) like upper(:p_user_name)");
            }

            SQLQuery query = session.createSQLQuery(sqlBuilder.toString());

            query.setParameterList("p_list_campaign_id", dto.getCampaignId().trim().split(","));
            query.setParameter("p_customer_id", dto.getCustomerId().trim());
            query.setParameter("p_date_from", dto.getFromDate().trim());
            query.setParameter("p_date_to", dto.getToDate().trim());
            query.setParameterList("p_list_contact_status", dto.getContactStatus().trim().split(","));
            query.setParameterList("p_list_survey_status", dto.getSurveyStatus().trim().split(","));
            query.setParameterList("p_list_record_status", dto.getRecordStatus().trim().split(","));
            query.setParameter("p_phone_number", dto.getPhoneNumber().trim());
            query.setParameter("p_call_time_from", dto.getCallTimeFrom().trim());
            query.setParameter("p_call_time_to", dto.getCallTimeTo().trim());

            if (!DataUtil.isNullOrEmpty(dto.getCampaignName().trim())) {
                query.setParameter("p_campaign_name", dto.getCampaignName().trim());
            }
            if (!DataUtil.isNullOrEmpty(dto.getAgentId().trim())) {
                query.setParameter("p_user_name", dto.getAgentId().trim());
            }

            query.addScalar("campaignCode", new StringType());
            query.addScalar("campaignName", new StringType());
            query.addScalar("userName", new StringType());
            query.addScalar("phoneNumber", new LongType());
            query.addScalar("customerName", new StringType());
            query.addScalar("createTime", new DateType());
            query.addScalar("contactStatus", new StringType());
            query.addScalar("surveyStatus", new StringType());
            query.addScalar("status", new ShortType());
            query.addScalar("recordStatus", new ShortType());

            query.setResultTransformer(Transformers.aliasToBean(ContactCustResultDTO.class));

            int count = 0;
            list = query.list();
            if (list.size() > 0) {
                count = list.size();
            }
            Pageable pageable = SQLBuilder.buildPageable(dto);
            if (pageable != null) {
                query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
                query.setMaxResults(pageable.getPageSize());
            }
            List<ContactCustResultDTO> data = query.list();
            for (ContactCustResultDTO contactCustResultDTO: data) {
                if (!"AGENT".equals(dto.getRoleUser())) {
                    contactCustResultDTO.setEnableEdit(true);
                } else {
                    if (contactCustResultDTO.getRecordStatus() == 2) {
                        contactCustResultDTO.setEnableEdit(true);
                    } else if (contactCustResultDTO.getRecordStatus() == 1){
                        /**
                         * Hoi chi linh xac dinh thoi gian 24h ke tu khi da luu kieu gi??????
                         */
                    } else {
                        contactCustResultDTO.setEnableEdit(false);
                    }
                }
            }
            Page<ContactCustResultDTO> dataPage = new PageImpl<>(data, pageable, count);
            resultDTO.setData(dataPage);
            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
        } catch (Exception e) {
            resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
            resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
            logger.error(e.getMessage(), e);
        } finally {
            session.close();
        }
        return resultDTO;
    }
}
