package com.viettel.campaign.web.rest;

import com.viettel.campaign.model.ccms_full.ContactQuestResult;
import com.viettel.campaign.service.CampaignExecuteService;
import com.viettel.campaign.utils.RedisUtil;
import com.viettel.campaign.web.dto.*;
import com.viettel.campaign.web.dto.request_dto.CampaignRequestDTO;
import com.viettel.econtact.filter.UserSession;
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.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@RestController
@RequestMapping("/ipcc/campaign/execute")
@CrossOrigin
public class CampaignExecuteController {

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

    @Autowired
    CampaignExecuteService campaignExecuteService;

    @PostMapping("/searchCampaignExecute")
    @ResponseBody
    public ResponseEntity<ResultDTO> searchCampaignExecute(@RequestBody CampaignRequestDTO requestDto, HttpServletRequest request) {
        String xAuthToken = request.getHeader("X-Auth-Token");
        ResultDTO result = campaignExecuteService.searchCampaignExecute(requestDto, xAuthToken);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/getExecuteCampaign")
    @ResponseBody
    public ResponseEntity<ResultDTO> getExecuteCampaign(@RequestBody CampaignRequestDTO requestDto) {
        ResultDTO result = campaignExecuteService.getExecuteCampaign(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/getCustomer")
    @ResponseBody
    public ResponseEntity<ResultDTO> getCustomer(@RequestBody CampaignCustomerDTO requestDto) {
        ResultDTO result = campaignExecuteService.getCustomer(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/getCustomerComplete")
    @ResponseBody
    public ResponseEntity<ResultDTO> getCustomerComplete(@RequestBody ReceiveCustLogDTO requestDto) {
        ResultDTO result = campaignExecuteService.getCustomerComplete(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/getCallLog")
    @ResponseBody
    public ResponseEntity<ResultDTO> getCallLog(@RequestBody ReceiveCustLogDTO requestDto) {
        ResultDTO result = campaignExecuteService.getCallLog(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/getCallStatus")
    @ResponseBody
    public ResponseEntity<ResultDTO> getCallStatus(@RequestBody CampaignRequestDTO requestDto) {
        ResultDTO result = campaignExecuteService.getCallStatus(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/countRecallCustomer")
    @ResponseBody
    public ResponseEntity countRecallCustomer(@RequestParam("companySiteId") Long companySiteId, @RequestParam("agentId") Long agentId) {
        ResultDTO result = campaignExecuteService.countRecallCustomer(companySiteId, agentId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/getAgentLogout")
    @ResponseBody
    public ResponseEntity<ResultDTO> getAgentLogout(@RequestBody CampaignRequestDTO requestDto) {
        ResultDTO result = campaignExecuteService.getAgentLogout(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/searchInteractiveResult")
    @ResponseBody
    public ResponseEntity<ResultDTO> searchInteractiveResult(@RequestBody CampaignRequestDTO dto) throws Exception {
        ResultDTO result = campaignExecuteService.searchInteractiveResult(dto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/exportInteractiveResult")
    @ResponseBody
    public ResponseEntity<?> exportInteractiveResult(HttpServletResponse response, @RequestBody CampaignRequestDTO dto) {
        XSSFWorkbook workbook = null;
        byte[] contentReturn = null;
        try {
            String fileName = "report_campaign_exec_interactive_result.xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            OutputStream outputStream;
            workbook = campaignExecuteService.exportInteractiveResult(dto);
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            contentReturn = byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResponseEntity<byte[]>(null, null, HttpStatus.BAD_REQUEST);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
        return new ResponseEntity<byte[]>(contentReturn, headers, HttpStatus.OK);
    }

    @GetMapping("/getCustomerInfor")
    @ResponseBody
    public ResponseEntity getCustomerInfor(@RequestParam("companySiteId") Long companySiteId, @RequestParam("customerId") Long customerId, @RequestParam("campaignId") Long campaignId) {
        ResultDTO result = campaignExecuteService.getCustomerInfor(companySiteId, customerId, campaignId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/callCustomer")
    @ResponseBody
    public ResponseEntity<ResultDTO> callCustomer(@RequestBody ContactCustResultDTO requestDto, HttpServletRequest request) {
        String xAuthToken = request.getHeader("X-Auth-Token");
        UserSession userSession = (UserSession) RedisUtil.getInstance().get(xAuthToken);
        ResultDTO result = campaignExecuteService.callCustomer(requestDto, userSession);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/recallCustomer")
    @ResponseBody
    public ResponseEntity<ResultDTO> recallCustomer(@RequestBody ContactCustResultDTO requestDto) {
        ResultDTO result = campaignExecuteService.recallCustomer(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/callCustomerEnd")
    @ResponseBody
    public ResponseEntity<ResultDTO> callCustomerEnd(@RequestBody ContactCustResultDTO requestDto) {
        ResultDTO result = campaignExecuteService.callCustomerEnd(requestDto);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/getCustomerRecall")
    @ResponseBody
    public ResponseEntity getCustomerRecall(@RequestParam("campaignId") Long campaignId, @RequestParam("customerId") Long customerId) {
        ResultDTO result = campaignExecuteService.getCustomerRecall(campaignId, customerId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/createListContactQuestResult")
    @ResponseBody
    public ResponseEntity<ResultDTO> createListContactQuestResult(@RequestBody List<ContactQuestResultDTO> dtoList) {
        ResultDTO result = null;
        //ResultDTO result = campaignExecuteService.createListContacQuestResult(dtoList);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/getDialModeAtCurrent")
    @ResponseBody
    public ResponseEntity getDialModeAtCurrent(@RequestParam("companySiteId") Long companySiteId, @RequestParam("campaignId") Long campaignId) {
        String result = campaignExecuteService.getDialModeAtCurrent(companySiteId, campaignId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/getContactCustResultById")
    @ResponseBody
    public ResponseEntity getContactCustResultById(@RequestParam("contactCustResultId") Long contactCustResultId) {
        ResultDTO result = campaignExecuteService.getContactCustResultById(contactCustResultId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}
