package com.viettel.campaign.service.impl;

import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.model.ccms_full.CampaignLog;
import com.viettel.campaign.model.ccms_full.Scenario;
import com.viettel.campaign.model.ccms_full.ScenarioAnswer;
import com.viettel.campaign.model.ccms_full.ScenarioQuestion;
import com.viettel.campaign.repository.ccms_full.CampaignLogRepository;
import com.viettel.campaign.repository.ccms_full.ScenarioAnswerRepository;
import com.viettel.campaign.repository.ccms_full.ScenarioQuestionRepository;
import com.viettel.campaign.service.ScenarioQuestionService;
import com.viettel.campaign.utils.Constants;
import com.viettel.campaign.web.dto.ResultDTO;
import com.viettel.campaign.web.dto.ScenarioAnswerDTO;
import com.viettel.campaign.web.dto.ScenarioQuestionDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author anhvd_itsol
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class ScenarioQuestionServiceImpl implements ScenarioQuestionService {
    private static final Logger logger = LogManager.getLogger(ScenarioQuestionServiceImpl.class);

    @Autowired
    ScenarioQuestionRepository scenarioQuestionRepository;

    @Autowired
    CampaignLogRepository campaignLogRepository;

    @Autowired
    ScenarioAnswerRepository scenarioAnswerRepository;

    @Autowired
    ModelMapper modelMapper;

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public ResultDTO findByScenarioIdAndCampaignIdAndCompanySiteId(Long scenarioId, Long campaignId, Long companySiteId) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<ScenarioQuestion> lst = scenarioQuestionRepository.findScenarioQuestionsByScenarioIdAndCampaignIdAndCompanySiteIdAndStatusOrderByOrderIndex(scenarioId, campaignId, companySiteId, (short)1);
            resultDTO.setData(lst);
            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
            resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
        }
        return resultDTO;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public ResultDTO add(ScenarioQuestionDTO scenarioQuestionDTO) {
        ResultDTO resultDTO = new ResultDTO();
        List<ScenarioAnswerDTO> lstAnswers = new ArrayList<>();
        List<ScenarioAnswer> lstAnswersToInsert = new ArrayList<>();
        try {
            ScenarioQuestion scenarioQuestion = modelMapper.map(scenarioQuestionDTO, ScenarioQuestion.class);
            scenarioQuestion.setCreateTime(new Date());
            scenarioQuestion.setStatus((short) 1);
            scenarioQuestionRepository.save(scenarioQuestion);

            if (scenarioQuestionDTO.getLstAnswers().size() > 0) {
                lstAnswers = scenarioQuestionDTO.getLstAnswers();
                lstAnswers.forEach(item -> {
                    item.setCode(scenarioQuestion.getScenarioQuestionId() + "_" + item.getOrderIndex());
                    item.setScenarioQuestionId(scenarioQuestion.getScenarioQuestionId());
                    item.setCreateTime(new Date());
                    item.setStatus((short) 1);
                    ScenarioAnswer answer = modelMapper.map(item, ScenarioAnswer.class);
                    lstAnswersToInsert.add(answer);
                });
                scenarioAnswerRepository.saveAll(lstAnswersToInsert);
                CampaignLog campaignLogAnswer = new CampaignLog();
                campaignLogAnswer.setCompanySiteId(scenarioQuestion.getCompanySiteId());
                campaignLogAnswer.setCreateTime(new Date());
                campaignLogAnswer.setAgentId(null);
                campaignLogAnswer.setTableName("SCENARIO_ANSWER");
                campaignLogAnswer.setColumnName(null);
                campaignLogAnswer.setPreValue(null);
                campaignLogAnswer.setPostValue(null);
                campaignLogAnswer.setDescription("Them moi cau tra loi rieng le");
                campaignLogAnswer.setCampaignId(scenarioQuestion.getCampaignId());
                campaignLogAnswer.setCustomerId(scenarioQuestion.getScenarioQuestionId());
                campaignLogRepository.save(campaignLogAnswer);
            }

            CampaignLog campaignLog = new CampaignLog();
            campaignLog.setCompanySiteId(scenarioQuestion.getCompanySiteId());
            campaignLog.setCreateTime(new Date());
            campaignLog.setAgentId(null);
            campaignLog.setTableName("SCENARIO_QUESTION");
            campaignLog.setColumnName(null);
            campaignLog.setPreValue(null);
            campaignLog.setPostValue(null);
            campaignLog.setDescription("Them moi cau hoi rieng le");
            campaignLog.setCampaignId(scenarioQuestion.getCampaignId());
            campaignLog.setCustomerId(scenarioQuestion.getScenarioQuestionId());
            campaignLogRepository.save(campaignLog);
            resultDTO.setData(scenarioQuestion);
            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
            resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
        }
        return resultDTO;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public Long getMaxOrderId(Long scenarioId, Long campaignId, Long companySiteId) {
        try {
            return scenarioQuestionRepository.getMaxOrderId(scenarioId, campaignId, companySiteId);
        }catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public Integer countDuplicateQuestionCode(String code, Long scenarioId, Long campaignId, Long companySiteId) {
        try {
            return scenarioQuestionRepository.countDuplicateQuestionCode(code, scenarioId, campaignId, companySiteId);
        }catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

}
