/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.progress.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.progress.entity.PlanningStatistics;
import com.jeeplus.modules.sg.progress.entity.ShowStatistics;
import com.jeeplus.modules.sg.progress.entity.YearProgress;
import com.jeeplus.modules.sg.progress.service.YearProgressService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 车辆Controller
 *
 * @author lgf
 * @version 2018-06-12
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/progress")
public class YearProgressController extends BaseController {

    @Autowired
    private YearProgressService yearProgressService;

    @ModelAttribute
    public YearProgress get(@RequestParam(required = false) String id) {
        YearProgress entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = yearProgressService.get(id);
        }
        if (entity == null) {
            entity = new YearProgress();
        }
        return entity;
    }


    @RequiresPermissions("test:progress:list")
    @RequestMapping(value = "list")
    public String list(YearProgress yearProgress, Model model) {
        model.addAttribute("yearProgress", yearProgress);
        return "modules/sg/progress/yearProgressList";
    }


    @RequiresPermissions("test:progress:list")
    @RequestMapping(value = "statisticsList")
    public String statisticsList(YearProgress yearProgress, Model model, HttpServletRequest request, HttpServletResponse response, PlanningStatistics planningStatistics) {
        model.addAttribute("yearProgress", yearProgress);
        List<PlanningStatistics> yearStatistic = yearProgressService.findYearStatistic();
        List<ShowStatistics> showStatistics = yearProgressService.showAllYear();
        for (ShowStatistics s : showStatistics) {
            String projectYear = s.getProjectYear();
            for (PlanningStatistics p : yearStatistic) {
                String projectYear1 = p.getProjectYear();
                if (projectYear.equals(projectYear1)) {
                    s.setPlanningStatisticsYear(p);
                }
            }
        }
        List<PlanningStatistics> statisticPage = yearProgressService.findStatisticPage(planningStatistics);
        for (ShowStatistics s : showStatistics) {
            String projectYear = s.getProjectYear();
            List<PlanningStatistics> showList = new ArrayList<>();
            for (PlanningStatistics p : statisticPage) {
                String projectYear1 = p.getProjectYear();
                if (projectYear.equals(projectYear1)) {
                    showList.add(p);
                }
            }
            s.setPlanningStatistics(showList);
        }



        model.addAttribute("PageList", showStatistics);
        return "modules/sg/progress/statisticsList";
    }

    @ResponseBody
    @RequiresPermissions("test:progress:list")
    @RequestMapping(value = "statisticsData")
    public Map<String, Object> statisticsData(PlanningStatistics planningStatistics, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<PlanningStatistics> page = yearProgressService.findStatisticPage(new Page<PlanningStatistics>(request, response), planningStatistics);
/*
        List<PlanningStatistics> list = page.getList();
        HashMap<String, List<PlanningStatistics>> map = new HashMap<>();
        for (PlanningStatistics y : list) {
            if (map.containsKey(y.getProjectYear())) {
                map.get(y.getProjectYear()).add(y);
            } else {
                List<PlanningStatistics> mapList = new ArrayList<>();
                mapList.add(y);
                map.put(y.getProjectYear(), mapList);
            }
        }
        List<PlanningStatistics> yearStatistic = yearProgressService.findYearStatistic();
        for (PlanningStatistics p : yearStatistic) {
            p.setConstructionUnit("合计");
            if (map.containsKey(p.getProjectYear())) {
                map.get(p.getProjectYear()).add(p);
            }
        }
        Iterator<Map.Entry<String, List<PlanningStatistics>>> iterator = map.entrySet().iterator();
        List<PlanningStatistics> showList = new ArrayList<>();
        while (iterator.hasNext()) {
            Map.Entry<String, List<PlanningStatistics>> next = iterator.next();
            List<PlanningStatistics> value = next.getValue();
            showList.addAll(value);
        }
        page.setList(showList);*/
        model.addAttribute("PageList", page.getList());
        return getBootstrapData(page);
    }

    /**
     * 车辆列表数据
     */
    @ResponseBody
    @RequiresPermissions("test:progress:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(YearProgress yearProgress, HttpServletRequest request, HttpServletResponse response, Model model) {
        String projectId = yearProgress.getProjectId();
        if (projectId!=null && !"".equals(projectId)) {
            String[] split = projectId.split("\\s+");
            yearProgress.setAttrs(split);
        }
        Page<YearProgress> page = yearProgressService.findPage(new Page<YearProgress>(request, response), yearProgress);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑车辆表单页面
     */
    @RequiresPermissions(value = {"test:progress:view", "test:progress:add", "test:progress:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(YearProgress yearProgress, Model model) {
        model.addAttribute("yearProgress", yearProgress);
        return "modules/sg/progress/yearProgressForm";
    }

    @RequiresPermissions(value = {"test:progress:view", "test:progress:add", "test:progress:edit"}, logical = Logical.OR)
    @RequestMapping(value = "edit")
    public String edit(YearProgress yearProgress, Model model) {
        model.addAttribute("yearProgress", yearProgress);
        return "modules/sg/progress/yearProgressEdit";
    }


    @ResponseBody
    @RequiresPermissions(value = {"test:progress:add", "test:progress:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(YearProgress yearProgress, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(yearProgress);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        //新增或编辑表单保存
        YearProgress yearProgress1 = yearProgressService.getByName(yearProgress.getProjectName());
        if (yearProgress1 != null) {
            j.setSuccess(false);
            j.setMsg("项目已存在");
            return j;
        }
        yearProgressService.save(yearProgress);//保存
        j.setSuccess(true);
        j.setMsg("项目信息保存成功");
        return j;
    }

    @ResponseBody
    @RequiresPermissions(value = {"test:progress:add", "test:progress:edit"}, logical = Logical.OR)
    @RequestMapping(value = "editSave")
    public AjaxJson editSave(YearProgress yearProgress, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(yearProgress);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        int update = yearProgressService.update(yearProgress);//保存
        if (update > 0) {
            j.setSuccess(true);
            j.setMsg("项目信息修改成功");
        } else {
            j.setSuccess(true);
            j.setMsg("项目信息修改失败");
        }

        return j;
    }

    /**
     * 删除车辆
     */
    @ResponseBody
    @RequiresPermissions("test:progress:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(YearProgress yearProgress) {
        AjaxJson j = new AjaxJson();
        yearProgressService.delete(yearProgress);
        j.setMsg("删除项目信息成功");
        return j;
    }

    /**
     * 批量删除车辆
     */
    @ResponseBody
    @RequiresPermissions("test:progress:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            yearProgressService.delete(yearProgressService.get(id));
        }
        j.setMsg("删除项目信息成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("test:progress:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(YearProgress yearProgress, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "镇江本部历年项目建设进度统计表" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<YearProgress> page = yearProgressService.findPage(new Page<YearProgress>(request, response, -1), yearProgress);
            List<YearProgress> list = page.getList();
            int i = 1;
            for (YearProgress yearProgress1 : list
            ) {
                yearProgress1.setImportNo(String.valueOf(i));
                i += 1;
            }
            new ExportExcel("", YearProgress.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出镇江本部历年项目建设进度记录失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("test:progress:import")
    @RequestMapping(value = "import")
    public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<YearProgress> insertList = new ArrayList<>();
            List<YearProgress> list = ei.getDataList(YearProgress.class);
            for (YearProgress yearProgress : list) {
                if (null != yearProgress.getProjectName() && !"".equals(yearProgress.getProjectName())) {
                    insertList.add(yearProgress);
                } else {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，有 " + failureNum + " 条记录没有项目名称，请核实。");
            }
            yearProgressService.replaceAll(insertList);
            j.setMsg("已成功导入 " + list.size() + " 条记录" + failureMsg);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 下载导入车辆数据模板
     */
    @ResponseBody
    @RequiresPermissions("test:progress:import")
    @RequestMapping(value = "template")
    public AjaxJson importFileTemplate(HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "镇江本部历年项目建设进度统计表导入模板.xlsx";
            List<YearProgress> list = Lists.newArrayList();
            new ExportExcel("", YearProgress.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入模板下载失败！失败信息：" + e.getMessage());
        }
        return j;
    }


    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<String> list = yearProgressService.findAllYear();
        for (int i = 0; i < list.size(); i++) {
            String e = list.get(i);
            if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(e))) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e);
                map.put("text", e);
                mapList.add(map);
            }
        }
        return mapList;
    }
}