package com.viettel.campaign.web.rest;

import com.viettel.campaign.web.dto.*;
import com.viettel.campaign.service.CustomerService;
import com.viettel.campaign.web.dto.request_dto.SearchCustomerRequestDTO;
import com.viettel.campaign.web.dto.request_dto.CustomerRequestDTO;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/ipcc/customer")
@CrossOrigin(origins = "*")
public class CustomerController {

    private static final Logger LOGGER = Logger.getLogger(CustomerController.class);

    @Autowired(required=true)
    CustomerService customerService;

    @GetMapping("/findAll")
    @ResponseBody
    public ResponseEntity findAllCustomer(@RequestParam("page") int page, @RequestParam("pageSize") int pageSize, @RequestParam("sort") String sort, @RequestParam("customerListId") long customerListId, @RequestParam("companySiteId") long companySiteId) {
        ResultDTO result = customerService.getAllCustomer(page, pageSize, sort, customerListId, companySiteId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/findCustomerId")
    @ResponseBody
    public ResponseEntity<ResultDTO> findAllCustomerName(@RequestParam("customerId") Long customerId) {
        ResultDTO result = customerService.getCustomerId(customerId);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @GetMapping("/searchAllCustomerByParams")
    @ResponseBody
    public ResponseEntity findAllCustomerByParams(@RequestParam("page") int page, @RequestParam("pageSize") int pageSize, @RequestParam("sort") String sort, @RequestParam("customerListId") Long customerListId, @RequestParam("companySiteId") Long companySiteId, @RequestParam("name") String name, @RequestParam("mobileNumber") String mobileNumber, @RequestParam("email") String email) {
        ResultDTO result = customerService.searchAllCustomer(page, pageSize, sort, customerListId, companySiteId, name, mobileNumber, email);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @PostMapping(value = "/create")
    @ResponseBody
    public ResultDTO createCustomer(@RequestBody @Valid CustomerDTO customerDTO) {
        ResultDTO result = new ResultDTO();
        //LogUtil logUtil = new LogUtil();
        //logUtil.initKpiLog("createCust");
        try {
            //LOGGER.info("Returning createCustomer: start");
            result = customerService.createCustomer(customerDTO);
            //LOGGER.info("Returning createCustomer:" + result.getErrorCode());
            //logUtil.endKpiLog(customerDTO, 0, result.getErrorCode(), result.getDetail(), CustomerController.class, customerDTO.getAgentProcess(), this.serverPort);
        } catch (Exception e) {
            result.setErrorCode("-1");
            LOGGER.error(e);
            //logUtil.endKpiLog(customerDTO, 1, result.getErrorCode(), e.getMessage(), CustomerController.class, customerDTO.getAgentProcess(), this.serverPort);
        }
        return result;
    }

    @PostMapping("/delete")
    @ResponseBody
    public ResultDTO deleteCustomer(@RequestBody @Valid CustomerRequestDTO customerRequestDTO) {
        ResultDTO result = new ResultDTO();
        result = customerService.deleteCustomer(customerRequestDTO);
        return result;
    }

    @PostMapping("/deleteIds")
    @ResponseBody
    public ResultDTO deleteIds(@RequestBody @Valid CustomerRequestDTO customerRequestDTO) {
        ResultDTO result = new ResultDTO();
        result = customerService.deleteIds(customerRequestDTO);
        return result;
    }

    @GetMapping("/getInformation")
    @ResponseBody
    public ResponseEntity getAllInformation(@RequestParam("companySiteId") Long companySiteId, @RequestParam("customerListId") Long customerListId, @RequestParam("customerId") Long customerId) {
        ResultDTO result = customerService.getCustomerDetailById(companySiteId, customerListId, customerId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    // --------------- customer list table ----------------- //

    @GetMapping("/findAlls")
    @ResponseBody
    public ResponseEntity findAllCustomerList(@RequestParam("page") int page, @RequestParam("pageSize") int pageSize, @RequestParam("sort") String sort, @RequestParam("companySiteId") Long companySiteId) {
        ResultDTO result = customerService.getAllCustomerList(page, pageSize, sort, companySiteId);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/createCustomerList")
    @ResponseBody
    public ResultDTO createCustomerList(@RequestBody @Valid CustomerListDTO customerListDTO) {
        ResultDTO result = new ResultDTO();
        //LogUtil logUtil = new LogUtil();
        //logUtil.initKpiLog("createCust")
        try {
            //LOGGER.info("Returning createCustomer: start");
            result = customerService.createCustomerList(customerListDTO);
            //LOGGER.info("Returning createCustomer:" + result.getErrorCode());
            //logUtil.endKpiLog(customerDTO, 0, result.getErrorCode(), result.getDetail(), CustomerController.class, customerDTO.getAgentProcess(), this.serverPort);
        } catch (Exception e) {
            result.setErrorCode("-1");
//            LOGGER.error(e);
            //logUtil.endKpiLog(customerDTO, 1, result.getErrorCode(), e.getMessage(), CustomerController.class, customerDTO.getAgentProcess(), this.serverPort);
        }
        return result;
//        return new ResponseEntity<>("", HttpStatus.OK);
    }

    @PostMapping("/updateCustomerList")
    @ResponseBody
    public ResultDTO updateCustomerList(@RequestBody @Valid CustomerListDTO customerListDTO) {
        ResultDTO result = new ResultDTO();
        //LogUtil logUtil = new LogUtil();
        //logUtil.initKpiLog("createCust");
        try {
            //LOGGER.info("Returning createCustomer: start");
            result = customerService.updateCustomerList(customerListDTO);
            //LOGGER.info("Returning createCustomer:" + result.getErrorCode());
            //logUtil.endKpiLog(customerDTO, 0, result.getErrorCode(), result.getDetail(), CustomerController.class, customerDTO.getAgentProcess(), this.serverPort);
        } catch (Exception e) {
            result.setErrorCode("-1");
//            LOGGER.error(e);
            //logUtil.endKpiLog(customerDTO, 1, result.getErrorCode(), e.getMessage(), CustomerController.class, customerDTO.getAgentProcess(), this.serverPort);
        }
        return result;
    }

    @PostMapping("/deleteCustomerList")
    @ResponseBody
    public ResultDTO deleteCustomerList(@RequestBody @Valid CustomerListDTO customerListDTO) {
        ResultDTO result = new ResultDTO();
        result = customerService.deleteCustomerList(customerListDTO);
        return result;
    }

    @PostMapping("/deleteCustomerListIds")
    @ResponseBody
    public ResultDTO deleteCustomerListIds(@RequestBody @Valid CustomerRequestDTO customerRequestDTO) {
        ResultDTO result = new ResultDTO();
        result = customerService.deleteCustomerListIds(customerRequestDTO);
        return result;
    }

    @RequestMapping(value = "/searchCustomerList", method = RequestMethod.POST)
    public ResponseEntity searchCustomerList(@RequestBody SearchCustomerRequestDTO searchCustomerRequestDTO) {
        ResultDTO result = customerService.searchCustomerList(searchCustomerRequestDTO);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/latestCreated")
    @ResponseBody
    public ResponseEntity getLatestCreated(@RequestParam("companySiteId") Long companySiteId) {
        ResultDTO result = new ResultDTO();
        result.setData(customerService.getLatestCreated(companySiteId));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/findCustomerContact")
    @ResponseBody
    public ResponseEntity<ResultDTO> findAllCustomerContact(@RequestBody CustomerContactDTO customerContactDTO) {
        ResultDTO result = customerService.getCustomerContact(customerContactDTO);
        return new ResponseEntity(result, HttpStatus.OK);
    }

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

    //<editor-fold desc="Download and import excel" defaultState="collapsed">
    @GetMapping(value = "/downloadFileTemplate")
    public ResponseEntity<byte[]> downloadFileTemplate(@RequestParam("companySiteId") Long companySiteId) {
        LOGGER.debug("--------DOWNLOAD FILE TEMPLATE---------");
        try {
            customerService.buildTemplate(companySiteId);
            File file = ResourceUtils.getFile("classpath:templates/import_customer_template.xlsx");
            byte[] content = Files.readAllBytes(file.toPath());
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(content);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    @PostMapping(value = "/importFile")
    public ResponseEntity<byte[]> importFile(@RequestParam("file") MultipartFile file) {
        LOGGER.debug("--------IMPORT FILE TEMPLATE---------");
        try {
            List<CustomerDTO> listCustomer = new ArrayList<>();
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
                CustomerDTO customer = new CustomerDTO();
                XSSFRow row = sheet.getRow(i);
                customer.setCustomerId(Double.valueOf(row.getCell(0).getNumericCellValue()).longValue());
                customer.setCreateDate(row.getCell(1).getDateCellValue());
                customer.setName(row.getCell(2).getStringCellValue());
                listCustomer.add(customer);
            }
//            for (int i = 0; i < listCustomer.size(); i++) {
//                validate du lieu
//            }
//            if (okay) {
//                for (int i = 0; i < listCustomer.size(); i++) {
//                    customerService.createCustomer(listCustomer.get(i));
//                }
//                return ResponseEntity.ok()
//                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
//                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
//                        .body(file.getBytes());
//            } else {
//                return ResponseEntity.ok()
//                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
//                        .header("Message", "Validate failed!")
//                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
//                        .body(file.getBytes());
//            }
            return null;
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
    //</editor-fold>

    @PostMapping("/getCustomerListInfo")
    public ResponseEntity<?> getCustomerListInfo(@RequestBody CampaignCustomerDTO dto) {
        List<CustomerListDTO> customers = customerService.getCustomerListInfo(dto);
        return new ResponseEntity<>(customers, HttpStatus.OK);
    }

    @PostMapping("/getIndividualCustomerInfo")
    public ResponseEntity<?> getIndividualCustomerInfo(@RequestBody CampaignCustomerDTO dto) {
        List<CustomerDTO> customers = customerService.getIndividualCustomerInfo(dto);
        return new ResponseEntity<>(customers, HttpStatus.OK);
    }

    @PostMapping("/getCustomizeField")
    public ResponseEntity<?> getCustomizeField(@RequestBody Long customerId) {
        List<CustomizeFieldDTO> data = customerService.getCustomizeField(customerId);
        return new ResponseEntity<>(data, HttpStatus.OK);
    }
}
