package com.house365.web.controller;

import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.IExportExcelInterface;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author Created by Administrator on 2019/2/25.
 */
@Controller
@RequestMapping("/export")
public class ExportExcelController {

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

    @Autowired
    private IExportExcelInterface anInterface;

    private static final String CITY_CODE = "cityCode";

    @RequestMapping(value = "/exportCustomer")
    @ResponseBody
    public HResult exportCustomer(HttpServletResponse httpResponse) {
        HResult result = new HResult();
        List<Map<String, String>> exportList = new ArrayList<>();
        try {
            List<Map<String, Object>> list = anInterface.queryCount();
            if (CollectionUtils.isNotEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    Map<String, String> putMap = new HashMap<>(10);
                    String managerId = list.get(i).get("managerId").toString();
                    String managerName = list.get(i).get("managerName").toString();
                    String cityCode = list.get(i).get(CITY_CODE).toString();
                    int count = Integer.parseInt(list.get(i).get("count").toString());
                    if (count > 0) {
                        Map<String, Object> map = new HashMap<>(10);
                        map.put("managerId", managerId);
                        map.put(CITY_CODE, cityCode);
                        List<Map<String, Object>> list1 = anInterface.queryByManagerId(map);
                        if (CollectionUtils.isNotEmpty(list1)) {
                            list1 = removeDuplicate(list1);
                            int count1 = list1.size();
                            //获取客户城市
                            putMap.put(CITY_CODE, cityCode);
                            //获取客户总量
                            putMap.put("count", String.valueOf(count1));
                            //获取安家顾问姓名
                            putMap.put("managerName", managerName);
                        }
                        UserEntity user = anInterface.getById(Integer.parseInt(managerId));
                        if (user != null) {
                            String deptUrlPath = user.getDeptUrlPath();
                            String[] depts = deptUrlPath.split("/");
                            int length = depts.length;
                            StringBuilder deptName = new StringBuilder();
                            if (length <= 2 && length > 0) {
                                DepartmentEntity departmentEntity = anInterface.queryById(Integer.valueOf(depts[1]));
                                deptName = deptName.append(departmentEntity.getName());
                            } else if (length > 2) {
                                DepartmentEntity departmentEntity = anInterface.queryById(Integer.valueOf(depts[length - 2]));
                                DepartmentEntity departmentEntity2 = anInterface.queryById(Integer.valueOf(depts[length - 1]));
                                deptName = deptName.append(departmentEntity.getName());
                                deptName = deptName.append("-").append(departmentEntity2.getName());

                            }
                            //获取安家顾问部门名称
                            putMap.put("deptName", deptName.toString());
                        }
                        List<Map<String, Object>> callBackList = anInterface.queryCustomerLog(map);
                        if (CollectionUtils.isNotEmpty(callBackList)) {
                            Iterator<Map<String, Object>> iterator = callBackList.iterator();
                            while (iterator.hasNext()) {
                                Map<String, Object> iterMap = iterator.next();
                                if (null == iterMap.get("phone") || StringUtils.isBlank(iterMap.get("phone").toString())) {
                                    iterator.remove();
                                }
                            }
                            callBackList = removeDuplicateList(callBackList);
                            //获取回访数量
                            putMap.put("callBackCount", String.valueOf(callBackList.size()));
                        } else {
                            putMap.put("callBackCount", "");
                        }
                        map.put("type", "A");
                        List<Map<String, Object>> aList = anInterface.queryByManagerId(map);
                        if (CollectionUtils.isNotEmpty(aList)) {
                            aList = removeDuplicate(aList);
                            //获取ab类总数
                            putMap.put("abCount", String.valueOf(aList.size()));
                        } else {
                            putMap.put("abCount", "");
                        }
                        Map<String, Object> searchMap = new HashMap<>(10);
                        searchMap.put("managerId", managerId);
                        searchMap.put("status", 1);
                        List<Map<String, Object>> seeList = anInterface.queryCustomerByStatus(searchMap);
                        if (CollectionUtils.isNotEmpty(seeList)) {
                            //获取约看类总数
                            putMap.put("seeCount", String.valueOf(seeList.size()));
                        } else {
                            putMap.put("seeCount", "");
                        }
                        searchMap.put("status", 2);
                        List<Map<String, Object>> daoList = anInterface.queryCustomerByStatus(searchMap);
                        if (CollectionUtils.isNotEmpty(daoList)) {
                            //获取到访类总数
                            putMap.put("daoCount", String.valueOf(daoList.size()));
                        } else {
                            putMap.put("daoCount", "");
                        }
                        searchMap.put("status", 3);
                        List<Map<String, Object>> renList = anInterface.queryCustomerByStatus(searchMap);
                        if (CollectionUtils.isNotEmpty(renList)) {
                            //获取认筹类总数
                            putMap.put("renCount", String.valueOf(renList.size()));
                        } else {
                            putMap.put("renCount", "");
                        }
                        searchMap.put("status", 4);
                        List<Map<String, Object>> buyList = anInterface.queryCustomerByStatus(searchMap);
                        if (CollectionUtils.isNotEmpty(buyList)) {
                            //获取认购类总数
                            putMap.put("buyCount", String.valueOf(buyList.size()));
                        } else {
                            putMap.put("buyCount", "");
                        }
                        searchMap.put("status", 5);
                        List<Map<String, Object>> qianList = anInterface.queryCustomerByStatus(searchMap);
                        if (CollectionUtils.isNotEmpty(qianList)) {
                            //获取签约类总数
                            putMap.put("qianCount", String.valueOf(qianList.size()));
                        } else {
                            putMap.put("qianCount", "");
                        }
                        searchMap.put("status", 6);
                        List<Map<String, Object>> cancelList = anInterface.queryCustomerByStatus(searchMap);
                        if (CollectionUtils.isNotEmpty(cancelList)) {
                            //获取退房类总数
                            putMap.put("cancelCount", String.valueOf(cancelList.size()));
                        } else {
                            putMap.put("cancelCount", "");
                        }
                    }
                    exportList.add(putMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("导出excel失败");
            logger.error("导出excel失败");
        }
        if (CollectionUtils.isNotEmpty(exportList)) {
            result = exportExcel(exportList, httpResponse);
        }
        return result;
    }

    private static List removeDuplicate(List list) {
        Set h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }


    public HResult exportExcel(List<Map<String, String>> list, HttpServletResponse response) {
        HResult result = new HResult();
        try {
            String fileName = new String(("exportexcel").getBytes("gb2312"), "iso8859-1") + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setCharacterEncoding("utf-8");

            String[] titles = {"城市", "部门", "安家顾问", "客户总量", "已跟进量",
                    "AB类客户量", "约看", "到访", "认筹", "认购", "签约", "退房"};
            //设置格式
            ServletOutputStream outputStream = response.getOutputStream();

            exportCustomer(titles, list, outputStream);

        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("导出失败");
            logger.error("导出失败");
        }
        return result;
    }

    private void exportCustomer(String[] titles, List<Map<String, String>> list, ServletOutputStream outputStream) {
        // 创建一个workbook 对应一个excel应用文件
        XSSFWorkbook workBook = new XSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        //Sheet名称，可以自定义中文名称
        XSSFSheet sheet = workBook.createSheet("Sheet1");
        ExportInternalUtil exportUtil = new ExportInternalUtil(workBook, sheet);
        XSSFCellStyle headStyle = exportUtil.getHeadStyle();
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
        // 构建表头
        XSSFRow headRow = sheet.createRow(0);
        XSSFCell cell = null;
        // 输出标题
        for (int i = 0; i < titles.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellStyle(headStyle);
            cell.setCellValue(titles[i]);
        }
        // 构建表体数据
        for (int j = 0; j < list.size(); j++) {
            XSSFRow bodyRow = sheet.createRow(j + 1);
            Map<String, String> map = list.get(j);
            cell = bodyRow.createCell(0);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("cityCode"));

            cell = bodyRow.createCell(1);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("deptName"));

            cell = bodyRow.createCell(2);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("managerName"));

            cell = bodyRow.createCell(3);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("count"));

            cell = bodyRow.createCell(4);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("callBackCount"));

            cell = bodyRow.createCell(5);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("abCount"));

            cell = bodyRow.createCell(6);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("seeCount"));

            cell = bodyRow.createCell(7);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("daoCount"));

            cell = bodyRow.createCell(8);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("renCount"));

            cell = bodyRow.createCell(9);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("buyCount"));

            cell = bodyRow.createCell(10);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("qianCount"));

            cell = bodyRow.createCell(11);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("cancelCount"));
        }
        try {
            workBook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error("", e);
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.error("导出excel报表2失败", e);
            }
        }
    }

    /**
     * 客户来源转化分析表-小类
     *
     * @param httpResponse
     * @return
     */
    @RequestMapping(value = "/exportCustomerBySource")
    @ResponseBody
    public HResult exportCustomerBySource(HttpServletResponse httpResponse) {
        HResult result = new HResult();
        List<Map<String, String>> exportList = new ArrayList<>();
        List<Integer> idList = new ArrayList<>();
        try {
            List<Map<String, Object>> sourceList = anInterface.querySource();
            if (CollectionUtils.isNotEmpty(sourceList)) {
                for (int i = 0; i < sourceList.size(); i++) {
                    Map<String, Object> resultMap = sourceList.get(i);
                    Map<String, String> putMap = new HashMap<>(10);
                    String cityCode = resultMap.get("cityCode").toString();
                    String actSource = resultMap.get("actSource").toString();

                    //设置城市
                    putMap.put("cityCode", cityCode);
                    //设置活动来源
                    putMap.put("source", actSource);

                    Map<String, Object> searchMap = new HashMap<>(5);
                    searchMap.put("source", actSource);
                    searchMap.put("cityCode", cityCode);
                    List<Map<String, Object>> callList = anInterface.queryCustomerLogBySource(searchMap);
                    if (CollectionUtils.isNotEmpty(callList)) {
                        callList = removeDuplicate(callList);
                        //设置回访数量
                        putMap.put("callCount", String.valueOf(callList.size()));
                    } else {
                        putMap.put("callCount", "");
                    }
                    searchMap.put("status", 1);
                    List<Map<String, Object>> seeList = anInterface.queryByStatusAndSource(searchMap);
                    if (CollectionUtils.isNotEmpty(seeList)) {
                        seeList = removeDuplicate(seeList);
                        //设置约看数量
                        putMap.put("seeCount", String.valueOf(seeList.size()));
                    } else {
                        putMap.put("seeCount", "");
                    }
                    searchMap.put("status", 2);
                    List<Map<String, Object>> daoList = anInterface.queryByStatusAndSource(searchMap);
                    if (CollectionUtils.isNotEmpty(daoList)) {
                        daoList = removeDuplicate(daoList);
                        //设置约看数量
                        putMap.put("daoCount", String.valueOf(daoList.size()));
                    } else {
                        putMap.put("daoCount", "");
                    }
                    searchMap.put("status", 3);
                    List<Map<String, Object>> renList = anInterface.queryByStatusAndSource(searchMap);
                    if (CollectionUtils.isNotEmpty(renList)) {
                        renList = removeDuplicate(renList);
                        //设置约看数量
                        putMap.put("renCount", String.valueOf(renList.size()));
                    } else {
                        putMap.put("renCount", "");
                    }
                    searchMap.put("status", 4);
                    List<Map<String, Object>> buyList = anInterface.queryByStatusAndSource(searchMap);
                    if (CollectionUtils.isNotEmpty(buyList)) {
                        buyList = removeDuplicate(buyList);
                        //设置约看数量
                        putMap.put("buyCount", String.valueOf(buyList.size()));
                    } else {
                        putMap.put("buyCount", "");
                    }
                    searchMap.put("status", 5);
                    List<Map<String, Object>> qianList = anInterface.queryByStatusAndSource(searchMap);
                    if (CollectionUtils.isNotEmpty(qianList)) {
                        qianList = removeDuplicate(qianList);
                        //设置约看数量
                        putMap.put("qianCount", String.valueOf(qianList.size()));
                    } else {
                        putMap.put("qianCount", "");
                    }
                    searchMap.put("status", 6);
                    List<Map<String, Object>> cancelList = anInterface.queryByStatusAndSource(searchMap);
                    if (CollectionUtils.isNotEmpty(cancelList)) {
                        cancelList = removeDuplicate(cancelList);
                        //设置约看数量
                        putMap.put("cancelCount", String.valueOf(cancelList.size()));
                    } else {
                        putMap.put("cancelCount", "");
                    }
                    exportList.add(putMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("导出excel4失败");
            logger.error("导出excel4失败");
        }
        if (CollectionUtils.isNotEmpty(exportList)) {
            result = exportExcel2(exportList, httpResponse);
        }
        return result;
    }

    private static ArrayList<Map<String, Object>> removeDuplicateList(List<Map<String, Object>> list) {
        Set<Map<String, Object>> set = new TreeSet<>(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return o1.get("phone").toString().compareTo(o2.get("phone").toString());
            }
        });
        set.addAll(list);
        return new ArrayList<>(set);
    }

    private HResult exportExcel2(List<Map<String, String>> list, HttpServletResponse response) {
        HResult result = new HResult();
        try {
            String fileName = new String(("exportExcel").getBytes("gb2312"), "iso8859-1") + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setCharacterEncoding("utf-8");

            String[] titles = {"城市", "活动来源", "已跟进量",
                    "约看", "到访", "认筹", "认购", "签约", "退房"};
            //设置格式
            ServletOutputStream outputStream = response.getOutputStream();

            exportCustomer2(titles, list, outputStream);

        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("导出报表4失败");
            logger.error("导出报表4失败");
        }
        return result;
    }

    private void exportCustomer2(String[] titles, List<Map<String, String>> list, ServletOutputStream outputStream) {
        // 创建一个workbook 对应一个excel应用文件
        XSSFWorkbook workBook = new XSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        //Sheet名称，可以自定义中文名称
        XSSFSheet sheet = workBook.createSheet("Sheet1");
        ExportInternalUtil exportUtil = new ExportInternalUtil(workBook, sheet);
        XSSFCellStyle headStyle = exportUtil.getHeadStyle();
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
        // 构建表头
        XSSFRow headRow = sheet.createRow(0);
        XSSFCell cell;
        // 输出标题
        for (int i = 0; i < titles.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellStyle(headStyle);
            cell.setCellValue(titles[i]);
        }
        // 构建表体数据
        for (int j = 0; j < list.size(); j++) {
            XSSFRow bodyRow = sheet.createRow(j + 1);
            Map<String, String> map = list.get(j);
            cell = bodyRow.createCell(0);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("cityCode"));

            cell = bodyRow.createCell(1);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("source"));

            cell = bodyRow.createCell(2);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("callCount"));

            cell = bodyRow.createCell(3);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("seeCount"));

            cell = bodyRow.createCell(4);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("daoCount"));

            cell = bodyRow.createCell(5);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("renCount"));

            cell = bodyRow.createCell(6);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("buyCount"));

            cell = bodyRow.createCell(7);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("qianCount"));

            cell = bodyRow.createCell(8);
            cell.setCellStyle(bodyStyle);
            cell.setCellValue(map.get("cancelCount"));
        }
        try {
            workBook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error("导出excel报表4失败", e);
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.error("导出excel报表4失败", e);
            }
        }
    }


}
