package com.viettel.campaign.service.impl;

import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.model.acd_full.Agents;
import com.viettel.campaign.model.ccms_full.TimeRangeDialMode;
import com.viettel.campaign.model.ccms_full.TimeZoneDialMode;
import com.viettel.campaign.repository.acd_full.AgentsRepository;
import com.viettel.campaign.repository.ccms_full.*;
import com.viettel.campaign.service.CampaignExecuteService;
import com.viettel.campaign.utils.BundleUtils;
import com.viettel.campaign.utils.Constants;
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.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CampaignExecuteServiceImp implements CampaignExecuteService {

    private static final Logger logger = LoggerFactory.getLogger(CampaignExecuteServiceImp.class);
    private SimpleDateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT.FOMART_DATE_TYPE_1);

    @Autowired
    CampaignRepositoryCustom campaignRepositoryCustom;

    @Autowired
    CampaignExecuteRepository campaignExecuteRepository;

    @Autowired
    AgentsRepository agentsRepository;

    @Autowired
    CampaignAgentRepository campaignAgentRepository;

    @Autowired
    TimeZoneDialModeRepository zoneDialModeRepository;

    @Autowired
    TimeRangeDialModeRepository rangeDialModeRepository;

    //<editor-fold: hungtt>
    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public ResultDTO getComboBoxStatus(String companySiteId, String completeType) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<ApParamDTO> lst = campaignExecuteRepository.getComboBoxStatus(companySiteId, completeType);
            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
            resultDTO.setData(lst);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return resultDTO;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public ResultDTO getComboCampaignType(String companySiteId) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            List<ApParamDTO> lst = campaignExecuteRepository.getComboCampaignType(companySiteId);
            resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
            resultDTO.setData(lst);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return resultDTO;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public ResultDTO searchInteractiveResult(CampaignRequestDTO dto) {
        ResultDTO resultDTO = new ResultDTO();
        try {
            resultDTO = campaignExecuteRepository.getInteractiveResult(dto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return resultDTO;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public XSSFWorkbook exportInteractiveResult(CampaignRequestDTO dto) {
        Locale locale = Locale.forLanguageTag("vi");
        List<ContactCustResultDTO> list = campaignExecuteRepository.getExcelInteractiveResult(dto);

        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet;

        // create font style
        Font defaultFont = workbook.createFont();
        defaultFont.setFontHeightInPoints((short) 13);
        defaultFont.setFontName("Times New Roman");
        defaultFont.setColor(IndexedColors.BLACK.getIndex());

        Font titleFont = workbook.createFont();
        titleFont.setFontHeightInPoints((short) 18);
        titleFont.setFontName("Times New Roman");
        titleFont.setColor(IndexedColors.BLACK.getIndex());
        titleFont.setBold(true);

        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 13);
        headerFont.setFontName("Times New Roman");
        headerFont.setColor(IndexedColors.BLACK.getIndex());
        headerFont.setBold(true);

        CellStyle styleTitle = workbook.createCellStyle();
        styleTitle.setFont(titleFont);
        styleTitle.setAlignment(HorizontalAlignment.CENTER);

        CellStyle styleRowHeader = workbook.createCellStyle();
        styleRowHeader.setFont(headerFont);
        styleRowHeader.setAlignment(HorizontalAlignment.CENTER);
        styleRowHeader.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        styleRowHeader.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        styleRowHeader.setBorderRight(BorderStyle.THIN);
        styleRowHeader.setRightBorderColor(IndexedColors.BLACK.getIndex());
        styleRowHeader.setBorderBottom(BorderStyle.THIN);
        styleRowHeader.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        styleRowHeader.setBorderLeft(BorderStyle.THIN);
        styleRowHeader.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        styleRowHeader.setBorderTop(BorderStyle.THIN);
        styleRowHeader.setTopBorderColor(IndexedColors.BLACK.getIndex());

        CellStyle styleRow = workbook.createCellStyle();
        styleRow.setFont(defaultFont);

        // list header
        List<String> headerList = new ArrayList<>();
        headerList.add(BundleUtils.getLangString("stt", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.campaignCode", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.campaignName", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.agentId", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.phoneNumber", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.customerId", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.customerName", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.createTime", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.contactStatus", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.surveyStatus", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.status", locale));
        headerList.add(BundleUtils.getLangString("campaign.execute.interactive.recordStatus", locale));

        //
        String sheetName = BundleUtils.getLangString("detail", locale);
        sheet = workbook.createSheet(sheetName);

        // Title
        String title = BundleUtils.getLangString("campaign.execute.interactive.title", locale);
        int rowTitleStart = 3;
        Row rowTitle = sheet.createRow(rowTitleStart);
        rowTitle.setHeight((short) 800);
        writeCellContent(rowTitle, styleTitle, 3, title);
        sheet.addMergedRegion(new CellRangeAddress(rowTitleStart, rowTitleStart, 3, 8));
        // Header
        int startRowTable = 5;
        int count = 1;
        Row rowHeader = sheet.createRow(startRowTable);
        for (int i = 0; i < headerList.size(); i++) {
            writeCellContent(rowHeader, styleRowHeader, i, headerList.get(i));
        }
        // Content
        for (int i = 0, rowIndex = 1; i < list.size(); i++) {
            Row row = sheet.createRow(startRowTable + count);
            int col = 0;
            writeCellContent(row, styleRow, col++, rowIndex);
            writeCellContent(row, styleRow, col++, list.get(i).getCampaignCode());
            writeCellContent(row, styleRow, col++, list.get(i).getCampaignName());
            writeCellContent(row, styleRow, col++, list.get(i).getAgentId());
            writeCellContent(row, styleRow, col++, list.get(i).getPhoneNumber());
            writeCellContent(row, styleRow, col++, list.get(i).getCustomerId());
            writeCellContent(row, styleRow, col++, list.get(i).getCustomerName());
            writeCellContent(row, styleRow, col++, formatter.format(list.get(i).getCreateTime()));
            writeCellContent(row, styleRow, col++, list.get(i).getContactStatus());
            writeCellContent(row, styleRow, col++, list.get(i).getSurveyStatus());
            writeCellContent(row, styleRow, col++, list.get(i).getStatus());
            writeCellContent(row, styleRow, col++, list.get(i).getRecordStatus());
            ++rowIndex;
            ++count;
        }
        return workbook;
    }

    @Override
    @Transactional(DataSourceQualify.CCMS_FULL)
    public List<ContactCustResultDTO> getContactCustById(CampaignRequestDTO dto) {
        return campaignExecuteRepository.getContactCustById(dto);
    }

    private void writeCellContent(Row row, CellStyle rowStyle, int colNo, Object content) {
        Cell cell = row.createCell(colNo);
        if (content == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(String.valueOf(content));
        }
        cell.setCellStyle(rowStyle);
    }
    //</editor-fold: hungtt>

    @Override
    public ResultDTO searchCampaignExecute(CampaignRequestDTO requestDto) {
        ResultDTO result = new ResultDTO();
        Map data = new HashMap();

        Integer count = campaignExecuteRepository.searchCampaignExecute(requestDto, null).size();

        if (count > 0) {
            result.setErrorCode(Constants.ApiErrorCode.SUCCESS);
            result.setDescription(Constants.ApiErrorDesc.SUCCESS);
            result.setTotalRow(count);
            result.setListData(campaignExecuteRepository.searchCampaignExecute(requestDto, SQLBuilder.buildPageable(requestDto)));

            Agents agents = agentsRepository.findByAgentId(requestDto.getAgentId());
            //TimeZoneDialMode zoneDialMode = zoneDialModeRepository.findDialModeAtCurrent(Long.parseLong(requestDto.getCampaignId()), Long.parseLong(requestDto.getCompanySiteId()));
            //TimeRangeDialMode rangeDialMode = rangeDialModeRepository.findDialModeAtCurrent(Long.parseLong(requestDto.getCampaignId()), Long.parseLong(requestDto.getCompanySiteId()));

            if (agents.getUserStatus() != null && agents.getCampaignSystemStatus() != null) {
                if (agents.getUserStatus().equalsIgnoreCase("CALLOUT") && agents.getCampaignSystemStatus().equalsIgnoreCase("AVAILABLE")) {
                    //if (zoneDialMode != null && zoneDialMode.getDialMode().equals(0) || rangeDialMode != null && rangeDialMode.getDialMode().equals(0))
                    data.put("dialModeManual", "1");
                }
            }
            result.setData(data);
        } else {
            result.setErrorCode(Constants.ApiErrorCode.ERROR);
            result.setDescription(Constants.ApiErrorDesc.ERROR);
        }

        return result;
    }

    @Override
    public ResultDTO getExecuteCampaign(CampaignRequestDTO requestDto) {
        ResultDTO result = new ResultDTO();

        try {
            Agents agents = agentsRepository.findByAgentId(requestDto.getAgentId());
            //TimeZoneDialMode zoneDialMode = zoneDialModeRepository.findDialModeAtCurrent(Long.parseLong(requestDto.getCampaignId()), Long.parseLong(requestDto.getCompanySiteId()));
            //TimeRangeDialMode rangeDialMode = rangeDialModeRepository.findDialModeAtCurrent(Long.parseLong(requestDto.getCampaignId()), Long.parseLong(requestDto.getCompanySiteId()));
            if (agents.getUserStatus().equalsIgnoreCase("CALLOUT") && agents.getCampaignSystemStatus().equalsIgnoreCase("LOGOUT")) {
                //if (zoneDialMode != null && zoneDialMode.getDialMode().equals(0) || rangeDialMode != null && rangeDialMode.getDialMode().equals(0))
                // update acd_full.agents table
                Agents a = new Agents();
                a.setAgentId(requestDto.getAgentId());
                a.setCampaignSystemStatus("AVAILABLE");
                a.setCurrentCampaignId(Long.parseLong(requestDto.getCampaignId()));
                agentsRepository.save(a);
                // update ccms_full.campaign_agent table
                campaignAgentRepository.updateCampaignAgentSetStatus(Long.parseLong(requestDto.getAgentId()), Long.parseLong(requestDto.getCampaignId()), 1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public ResultDTO getCall(CampaignRequestDTO dto) {
        ResultDTO result = new ResultDTO();
        Map data = new HashMap();
        data.put("campaignId", dto.getCampaignId());

        Agents agents = agentsRepository.findByAgentId(dto.getAgentId());
        TimeZoneDialMode zoneDialMode = zoneDialModeRepository.findDialModeAtCurrent(Long.parseLong(dto.getCampaignId()), Long.parseLong(dto.getCompanySiteId()));
        TimeRangeDialMode rangeDialMode = rangeDialModeRepository.findDialModeAtCurrent(Long.parseLong(dto.getCampaignId()), Long.parseLong(dto.getCompanySiteId()));

        return result;
    }
}
