package com.viettel.campaign.service.impl;

import com.viettel.campaign.repository.CampaignExecuteRepository;
import com.viettel.campaign.service.CampaignExecuteService;
import com.viettel.campaign.utils.BundleUtils;
import com.viettel.campaign.utils.Constants;
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.commons.collections4.BagUtils;
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 java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@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
    CampaignExecuteRepository campaignExecuteRepository;

    //<editor-fold: hungtt>
    @Override
    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
    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
    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
    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;
    }

    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>
}
