package com.house365.web.controller;

import com.alibaba.dubbo.common.json.JSON;
import com.house365.beans.entity.CustomerRemindEntity;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.StatisticEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.commons.system.FastDFSUtil;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.ExcelUtil;
import com.house365.web.util.SessionConstants;
import com.house365.ws.beans.request.DepartmentListRequest;
import com.house365.ws.beans.request.StatisticListRequest;
import com.house365.ws.beans.request.StatisticRequest;
import com.house365.ws.beans.response.DepartmentListResponse;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.NoticeListResponse;
import com.house365.ws.beans.response.StatisticListResponse;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.INotice;
import com.house365.ws.interfaces.server.IStatistic;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.house365.web.util.SessionConstants.SESSION_CURRNET_DEPT_KEY;

/**
 * @author 登录、登出、首页等
 */
@Controller
@RequestMapping
public class IndexController extends BaseController {
    Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());

    @Autowired
    IDepartment department;

    @Autowired
    ICustomer iCustomer;

    @Autowired
    INotice notice;

    @Autowired
    IStatistic statistic;

    /**
     * home page
     *
     * @param response
     * @param request
     * @return
     */
    @SuppressWarnings("all")
    @RequestMapping(value = {"", "/", "index"}, method = {RequestMethod.GET})
    public String index(HttpServletResponse response, HttpServletRequest request, Model model) {
        Subject subject = SecurityUtils.getSubject();
        if (null == request.getSession().getAttribute("cityList")) {
            Map<String, Object> searchParams = new HashMap<>();
            Page page = new Page(1000);
            DepartmentListRequest listRequest = new DepartmentListRequest();
            searchParams.put("EQ_parentId", 1);
            listRequest.setOrderColumn("orderNum");
            listRequest.setOrderMode("asc");
            listRequest.setSearchParams(searchParams);
            listRequest.setPaging(page);
            DepartmentListResponse listResponse = department.getDepartmentList(listRequest);

            DepartmentEntity rootDept = department.getDepartmentById(1).getEntity();
            List<DepartmentEntity> deptList = new LinkedList<>();
            deptList.add(rootDept);
            deptList.addAll(listResponse.getObjectList());
            request.getSession().setAttribute("deptList", deptList);
        }

       /* request.getSession().getAttribute(SessionConstants.THREAD_DEPT_KEY);
        if (null == request.getSession().getAttribute("city")) {
            request.getSession().setAttribute("city", "2");
        }*/
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        //V3.3.0界面展示元素
        Map<String, String> summaryParams = new HashMap();
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        summaryParams.put("cityCode", cityCode);
        summaryParams.put("isDelete", "0");
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        summaryParams.put("userId", userEntity.getId().toString());
        //类型过滤
        StringBuilder typeFilter = new StringBuilder();
        typeFilter.append("isWaitCall = 1");
        summaryParams.put("typeFilter", typeFilter.toString());
        summaryParams.put("timeType", "3");
        summaryParams.put("managerId", request.getParameter("managerId"));

        //获取开始时间
        long startTime = System.currentTimeMillis();
//        CustomerListRequest listRequest = new CustomerListRequest();
//        listRequest.setSearchParams(summaryParams);
        Map<String, Object> returnMap = iCustomer.getNewSummary(summaryParams);
        long endTime = System.currentTimeMillis();
        logger.info("------------------------getNewSummary程序运行时间： " + (endTime - startTime) + "ms");
        model.addAttribute("call400Customer", returnMap.get("call400Customer"));
        model.addAttribute("waitVisitCustomer", returnMap.get("waitVisitCustomer"));
        model.addAttribute("last7ReVisit", returnMap.get("last7ReVisit"));
        //客户统计数据
        House365RestResponse<Map<String, Object>> rest = iCustomer.getSummary(String.valueOf(request.getSession().getAttribute(SessionConstants.THREAD_USERID_KEY)));
        long endTime1 = System.currentTimeMillis();
        logger.info("------------------------getSummary程序运行时间： " + (endTime1 - endTime) + "ms");
        model.addAttribute("summary", rest.getData().getEntity());

        //公告
        NoticeListResponse noticeListResponse = notice.getNoticeListForIndexPage(departmentEntity.getCityID());
        long endTime2 = System.currentTimeMillis();
        logger.info("------------------------getNoticeListForIndexPage程序运行时间： " + (endTime2 - endTime1) + "ms");
        model.addAttribute("notices", noticeListResponse.getObjectList());
        //设置概览报表数据
        setIndexReportData(model, departmentEntity);
        long endTime3 = System.currentTimeMillis();
        logger.info("------------------------setIndexReportData程序运行时间： " + (endTime3 - endTime2) + "ms");
        Map<String, Object> map = new HashMap<>(10);
        return getAutoUrl();
    }

    /**
     * 设置概览报表数据
     *
     * @param model
     * @param departmentEntity
     */
    private void setIndexReportData(Model model, DepartmentEntity departmentEntity) {

        HashMap map = statistic.getIndexReport(departmentEntity.getCityID());

        HashMap<String, List<String>> report1Map = (HashMap<String, List<String>>) map.get("report1");
        HashMap<String, List<String>> report2Map = (HashMap<String, List<String>>) map.get("report2");
        HashMap<String, List<String>> report3Map = (HashMap<String, List<String>>) map.get("report3");
        HashMap<String, List<String>> report4Map = (HashMap<String, List<String>>) map.get("report4");

        List<String> report1Title = report1Map.get("title") == null ? new ArrayList<String>() : report1Map.get("title");
        List<String> report1Names = report1Map.get("names") == null ? new ArrayList<String>() : report1Map.get("names");
        List<String> report1Performances = report1Map.get(
                "performance") == null ? new ArrayList<String>() : report1Map.get("performance");
        List<String> report1BuyNums = report1Map.get("buyNum") == null ? new ArrayList<String>() : report1Map.get(
                "buyNum");

        List<String> report2Title = report2Map.get("title") == null ? new ArrayList<String>() : report2Map.get("title");
        List<String> report2Names = report2Map.get("names") == null ? new ArrayList<String>() : report2Map.get("names");
        List<String> report2Performances = report2Map.get(
                "performance") == null ? new ArrayList<String>() : report2Map.get("performance");
        List<String> report2BuyNums = report2Map.get("buyNum") == null ? new ArrayList<String>() : report2Map.get(
                "buyNum");

        List<String> report3Title = report3Map.get("title") == null ? new ArrayList<String>() : report3Map.get("title");
        List<String> report3Names = report3Map.get("names") == null ? new ArrayList<String>() : report3Map.get("names");
        List<String> report3Performances = report3Map.get(
                "performance") == null ? new ArrayList<String>() : report3Map.get("performance");
        List<String> report3BuyNums = report3Map.get("buyNum") == null ? new ArrayList<String>() : report3Map.get(
                "buyNum");

        List<String> report4Title = report4Map.get("title") == null ? new ArrayList<String>() : report4Map.get("title");
        List<String> report4Names = report4Map.get("names") == null ? new ArrayList<String>() : report4Map.get("names");
        List<String> report4Performances = report4Map.get(
                "performance") == null ? new ArrayList<String>() : report4Map.get("performance");
        List<String> report4BuyNums = report4Map.get("buyNum") == null ? new ArrayList<String>() : report4Map.get(
                "buyNum");
        try {
            model.addAttribute("report1Title", report1Title.isEmpty() ? "" : report1Title.get(0));
            model.addAttribute("report1Names", JSON.json(report1Names));
            model.addAttribute("report1Performances", JSON.json(report1Performances));
            model.addAttribute("report1BuyNums", JSON.json(report1BuyNums));

            model.addAttribute("report2Title", report2Title.isEmpty() ? "" : report2Title.get(0));
            model.addAttribute("report2Names", JSON.json(report2Names));
            model.addAttribute("report2Performances", JSON.json(report2Performances));
            model.addAttribute("report2BuyNums", JSON.json(report2BuyNums));

            model.addAttribute("report3Title", report3Title.isEmpty() ? "" : report3Title.get(0));
            model.addAttribute("report3Names", JSON.json(report3Names));
            model.addAttribute("report3Performances", JSON.json(report3Performances));
            model.addAttribute("report3BuyNums", JSON.json(report3BuyNums));

            model.addAttribute("report4Title", report4Title.isEmpty() ? "" : report4Title.get(0));
            model.addAttribute("report4Names", JSON.json(report4Names));
            model.addAttribute("report4Performances", JSON.json(report4Performances));
            model.addAttribute("report4BuyNums", JSON.json(report4BuyNums));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    @SuppressWarnings("all")
    @RequestMapping(value = {"report"}, method = {RequestMethod.GET})
    public String report(HttpServletResponse response, HttpServletRequest request, Model model) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();

        House365RestResponse statisticListResponse = statistic.getDistinctReportName(String.valueOf(city.getId()));
        List<HashMap<String, String>> list = (List<HashMap<String, String>>) statisticListResponse.getData().getList();
        for (HashMap map : list) {
            if (map.containsKey("sort")) {
                if ("1".equalsIgnoreCase(String.valueOf(map.get("sort")))) {
                    model.addAttribute("reportFirst", map.get("report_name") == null ? "" : map.get("report_name"));
                    model.addAttribute("fileOne", map.get("file_path") == null ? "" : map.get("file_path"));
                    model.addAttribute("nameOne", map.get("file_name") == null ? "" : map.get("file_name"));
                } else if ("2".equalsIgnoreCase(String.valueOf(map.get("sort")))) {
                    model.addAttribute("reportSec", map.get("report_name") == null ? "" : map.get("report_name"));
                    model.addAttribute("fileTwo", map.get("file_path") == null ? "" : map.get("file_path"));
                    model.addAttribute("nameTwo", map.get("file_name") == null ? "" : map.get("file_name"));
                } else if ("3".equalsIgnoreCase(String.valueOf(map.get("sort")))) {
                    model.addAttribute("reportThd", map.get("report_name") == null ? "" : map.get("report_name"));
                    model.addAttribute("fileThree", map.get("file_path") == null ? "" : map.get("file_path"));
                    model.addAttribute("nameThree", map.get("file_name") == null ? "" : map.get("file_name"));
                } else if ("4".equalsIgnoreCase(String.valueOf(map.get("sort")))) {
                    model.addAttribute("reportFour", map.get("report_name") == null ? "" : map.get("report_name"));
                    model.addAttribute("fileFour", map.get("file_path") == null ? "" : map.get("file_path"));
                    model.addAttribute("nameFour", map.get("file_name") == null ? "" : map.get("file_name"));
                }
            }
        }

        return getAutoUrl();
    }

    @RequestMapping(value = "uploadReport")
    @ResponseBody
    public Map<String, Object> uploadReport(MultipartHttpServletRequest request, Model model) {
        Map<String, Object> resultMap = new HashMap<>(10);
        try {
            String index = request.getParameter("reportIndex");
            String value = request.getParameter("reportName");

            DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);

            StatisticListRequest statisticListRequest = new StatisticListRequest();
            Map<String, Object> searchParams = new HashMap<>(10);
            searchParams.put("EQ_sort", index);
            searchParams.put("EQ_deptCityId", departmentEntity.getCityID());
            statisticListRequest.setSearchParams(searchParams);
            StatisticListResponse statisticListResponse = statistic.getStatisticList(statisticListRequest);
            for (StatisticEntity statisticEntity : statisticListResponse.getObjectList()) {
                statistic.deleteStatisticById(statisticEntity.getId());
            }

            // build an iterator
            Iterator<String> itr = request.getFileNames();
            MultipartFile multipartFile = null;
            // get each file
            if (!itr.hasNext()) {
                resultMap.put("success", false);
                return resultMap;
            }
            multipartFile = request.getFile(itr.next());

            DepartmentEntity department = (DepartmentEntity) request.getSession().getAttribute(
                    SESSION_CURRNET_DEPT_KEY);

            List<StatisticEntity> statisticEntities = new ArrayList<>();
            //fdfs file url
            String fileUrl = FastDFSUtil.uploadFileByStream(multipartFile.getInputStream(),
                    multipartFile.getOriginalFilename());
            String fileName = multipartFile.getOriginalFilename();
            List<List<Object>> importExcel = ExcelUtil.importExcelSecond(multipartFile.getInputStream());
            for (int i = 1; i < importExcel.size(); i++) {
                if (importExcel.get(i) == null || importExcel.get(i).isEmpty()) {
                    continue;
                }
                StatisticEntity statisticEntity = new StatisticEntity();
                statisticEntity.setBuyNum(importExcel.get(i).get(1) == null ? 0 : Integer.parseInt(
                        String.valueOf(importExcel.get(i).get(1))));
                statisticEntity.setCreater(
                        String.valueOf(request.getSession().getAttribute(SessionConstants.THREAD_USERNAME_KEY)));
                statisticEntity.setCreateTime(new Date());
                statisticEntity.setGroup(String.valueOf(importExcel.get(i).get(3) == null ? "" : importExcel.get(i).get(
                        3)));
                statisticEntity.setName(String.valueOf(importExcel.get(i).get(0) == null ? "" : importExcel.get(i).get(
                        0)));

                if (importExcel.get(i).get(2) == null) {
                    statisticEntity.setPerformance(new BigDecimal(0));
                } else {
                    statisticEntity.setPerformance(new BigDecimal(String.valueOf(importExcel.get(i).get(2))));
                }
                statisticEntity.setReportName(value);
                statisticEntity.setSort(Integer.valueOf(index));
                statisticEntity.setDeptCityId(department.getCityID());
                statisticEntity.setFilePath(fileUrl);
                statisticEntity.setFileName(fileName);
                StatisticRequest statisticRequest = new StatisticRequest();
                statisticRequest.setEntity(statisticEntity);
                statistic.addStatistic(statisticRequest);

            }
            resultMap.put("success", true);
            resultMap.put("fileName", value);
        } catch (Exception se) {
            logger.error(se.getMessage(), se);
            resultMap.put("success", false);
        }
        return resultMap;
    }

    @RequestMapping(value = "changeDept/{deptId}", method = RequestMethod.GET)
    @ResponseBody
    private String changeDept(@PathVariable Integer deptId, HttpServletRequest httpRequest, Model model) {
        DepartmentEntity dept = department.getDepartmentById(deptId).getEntity();
        httpRequest.getSession().setAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY, dept);
        httpRequest.getSession().setAttribute(SessionConstants.SESSION_CITY_KEY, dept.getDescripition());
        return null;
    }

    /**
     * 切换城市
     *
     * @param session  用户会话
     * @param city     城市代码
     * @param cityName 城市名称
     * @author chengjianfang
     * @version [版本号, 2015年5月15日]
     *//*
    @RequestMapping(value = "changeCity", method = {RequestMethod.POST})
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public void changeCity(HttpSession session, String city, String cityName) {
        session.setAttribute(ServiceConstant.CITY_ID, city);
        session.setAttribute(ServiceConstant.CITY_NAME, cityName);
        session.setAttribute("city", city);
    }*/
}
