package com.jeeplus.modules.sg.managementcenter.projectPlanArrage.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.entity.ProjectActProclnsAss;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.entity.ProjectDailyPlan;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.entity.ProjectPlanArrage;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.service.ProjectDailyPlanService;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.service.ProjectPlanArrageService;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.util.BookStrapTreeUtil;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.util.ImportUtil;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.util.PackagingUtil;
import com.jeeplus.modules.sg.managementcenter.projectPlanArrage.util.Result;
import com.jeeplus.modules.sys.utils.UserUtils;
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.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.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.jeeplus.core.service.BaseService.dataRuleFilter;

/**
 * 日计划
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/managementCenter/projectDailyPlan")
public class ProjectDailyPlanController extends BaseController {

    @Autowired
    private ProjectPlanArrageService projectPlanArrageService;

    @Autowired
    private ProjectDailyPlanService projectDailyPlanService;
    //主页面 list
    @RequestMapping(value = {"list", ""})
    @RequiresPermissions("sg:managementcenter:dayplan:list")
    public String list(ProjectDailyPlan projectDailyPlan, Model model) {
        model.addAttribute("projectDailyPlan", projectDailyPlan);
        return "modules/sg/managementcenter/projectPlanArrage/dailyPlan/projectDailyPlanList";
    }

    //新增页面
    @RequestMapping(value = "formProject")
    public String List(ProjectDailyPlan projectDailyPlan,Model model){
        return "modules/sg/managementcenter/projectPlanArrage/dailyPlan/projectDailyDateForm";
    }

    @ResponseBody
//	@RequiresPermissions("managementcenter:materialproject:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(ProjectDailyPlan projectDailyPlan, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<ProjectDailyPlan> page = projectDailyPlanService.findPage(new Page<ProjectDailyPlan>(request, response), projectDailyPlan);
        return getBootstrapData(page);
    }

    //删除操作
    @ResponseBody
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(ProjectDailyPlan projectDailyPlan,String ids,String projectNames,HttpServletRequest request){
        AjaxJson ajaxJson = new AjaxJson();
        ProjectDailyPlan dailyPlan = null;
        try {
            String comment = URLDecoder.decode(projectNames, "UTF-8");
            List<String> list = new ArrayList<>();
            if (ids.contains(",")){
                String[] split = ids.split(",");
                String[] names = comment.split(",");
                for (String name:names){
                    list.add(name);
                }
                projectDailyPlanService.updateNoMartailDaily(list);
                for (String str : split){
                    dailyPlan = new ProjectDailyPlan();
                    dailyPlan.setId(str);
                    projectDailyPlanService.delete(dailyPlan);
                }
            }else {
                dailyPlan = new ProjectDailyPlan();
                dailyPlan.setId(ids);
                list.add(comment);
                projectDailyPlanService.updateNoMartailDaily(list);
                projectDailyPlanService.delete(dailyPlan);
            }
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("删除成功");
            return ajaxJson;
        }catch (Exception e){
            e.printStackTrace();
        }
        ajaxJson.setSuccess(false);
        ajaxJson.setMsg("删除失败");
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(value = "export")
    public AjaxJson exportFile(ProjectDailyPlan projectDailyPlan, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "日计划安排表"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProjectDailyPlan> page = projectDailyPlanService.findPage(new Page<ProjectDailyPlan>(request, response, -1), projectDailyPlan);
            new ExportExcel("日计划安排表", ProjectDailyPlan.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;
    }

    //下载导入模板
    @ResponseBody
    @RequestMapping(value = "exportTim")
    public AjaxJson exportTim(ProjectDailyPlan projectDailyPlan, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "日计划安排表模板.xlsx";
            List<ProjectDailyPlan> projectDailyPlans = new ArrayList<ProjectDailyPlan>();
            new ExportExcel("日计划安排表", ProjectDailyPlan.class).setDataList(projectDailyPlans).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出日计划安排记录失败！失败信息："+e.getMessage());
        }
        return j;
    }

    //新增日计划选择项目定义号，或者项目名称后走的方法（可不选）
    @RequestMapping(value = "initAddDailyPlan")
    public String getInitAddDailyPlan(ProjectDailyPlan projectDailyPlan,String year,Model model, HttpServletRequest request){
        try {
            String comment1 = URLDecoder.decode(projectDailyPlan.getProjectName(), "UTF-8");
            projectDailyPlan.setProjectName(comment1);
            //获取所有未安排的日计划
            List<ProjectDailyPlan> projectDailyPlans = projectDailyPlanService.getProjectDailyPlan(year);
            List<ProjectDailyPlan> sxDailyPlan = projectDailyPlanService.getSxDailyPlan(projectDailyPlans, projectDailyPlan);
            for (ProjectDailyPlan plan:sxDailyPlan){
                plan.preInsert();
            }
            request.getSession().setAttribute("sxDailyPlan",sxDailyPlan);
        }catch (Exception e){
           e.printStackTrace();
        }
        return "modules/sg/managementcenter/projectPlanArrage/dailyPlan/projectDailyArrageForm";
    }
    //初始安排的计划项目--操作列表
    @ResponseBody
    @RequestMapping(value = "dailyPlanProject")
    public Map<String, Object> initArragePlanProject(ProjectDailyPlan projectDailyPlan,Model model,HttpServletRequest request,HttpServletResponse response){
        projectDailyPlan.setArrangeDailyPlan("1");
        List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
        Page<ProjectDailyPlan> page = findPageList(new Page<ProjectDailyPlan>(request, response),projectDailyPlan,projectPlans);
        return getBootstrapData(page);
    }
    public Page<ProjectDailyPlan> findPageList(Page<ProjectDailyPlan> page, ProjectDailyPlan entity,List<ProjectDailyPlan> list) {
        dataRuleFilter(entity);
        entity.setPage(page);
        List<ProjectDailyPlan> planArrages = new ArrayList<ProjectDailyPlan>();
        if (null!=list){
            for (ProjectDailyPlan projectDailyPlan:list){
                if (entity.getArrangeDailyPlan().equals(projectDailyPlan.getArrangeDailyPlan())){
                    planArrages.add(projectDailyPlan);
                }
            }
        }
        page.setList(planArrages);
        return page;
    }

    //所有未安排的计划-树形表格展示
    @ResponseBody
    @RequestMapping(value = "bootstrapTreeTable")
    public List<Map<String,Object>> getArrageNoPlan(ProjectDailyPlan projectDailyPlan,HttpServletRequest request){
        //创建树形表格
        List<Map<String,Object>> objects = Lists.newArrayList();
        List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
        List<Map<String, Object>> dailyBookStrapTree = BookStrapTreeUtil.getDailyBookStrapTree(objects, projectPlans);
        return dailyBookStrapTree;
    }

    //安排日计划
    @ResponseBody
    @RequestMapping(value = "unDailyPlanned")
    public Result getUnplanned(ProjectDailyPlan projectDailyPlan, String ids, HttpServletRequest request){
        Result j = new Result();
        List<String> strings = PackagingUtil.getString(ids);
        try {
            //获取项目信息
            List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
            if (!projectPlans.isEmpty()&&!strings.isEmpty()){
                projectDailyPlanService.addPlanDaily(projectPlans,strings);
            }
            //判断书否二次涉电
            boolean flag = false;
            for (ProjectDailyPlan plans:projectPlans){
                for (String s:strings){
                    if (plans.getId().equals(s)){
                        if (plans.getFlagYesElectricity().equals("1")){
                            flag = true;
                            break;
                        }
                        break;
                    }
                }
                if (flag){
                    break;
                }
            }
            List<Map<String,Object>> objects = Lists.newArrayList();
            List<Map<String, Object>> bookStrapTree = BookStrapTreeUtil.getDailyBookStrapTree(objects, projectPlans);
            j.setMapListTree(bookStrapTree);
            j.setSuccess(true);
            if (flag){
                j.setMessage("安排日计划成功:您所安排的项目中有二次涉电项目，列表已标红");
            }else {
                j.setMessage("安排日计划成功");
            }
            return j;
        }catch (Exception e){
            e.printStackTrace();
        }
        j.setSuccess(false);
        j.setMessage("安排日计划失败");
        return j;
    }

    //取消日计划
    @ResponseBody
    @RequestMapping(value = "cancelPackage")
    public Result getCancelPackage(ProjectDailyPlan projectDailyPlan,String ids,HttpServletRequest request){
        Result j = new Result();
        List<String> strings = PackagingUtil.getString(ids);
        try {
            //获取项目信息
            List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
            if (!projectPlans.isEmpty()&&!strings.isEmpty()){
                projectDailyPlanService.cancelPlanDaily(projectPlans,strings);
            }
            List<Map<String,Object>> objects = Lists.newArrayList();
            List<Map<String, Object>> bookStrapTree = BookStrapTreeUtil.getDailyBookStrapTree(objects, projectPlans);
            j.setMapListTree(bookStrapTree);
            j.setSuccess(true);
            j.setMessage("取消计划成功");
            return j;
        }catch (Exception e){
            e.printStackTrace();
        }
        j.setSuccess(false);
        j.setMessage("取消计划失败");
        return j;
    }

    //安排停电开关和具体时间页面
    @RequestMapping(value = "planDateAndOut")
    public String planDateAndOut(ProjectDailyPlan projectDailyPlan){
        return "modules/sg/managementcenter/projectPlanArrage/dailyPlan/dailyDateList";
    }

    //安排停电开关和具体时间列表页面
    //初始安排的计划项目--操作列表
    @ResponseBody
    @RequestMapping(value = "initdailyPlanProject")
    public Map<String, Object> initdailyPlanProject(ProjectDailyPlan projectDailyPlan,Model model,HttpServletRequest request,HttpServletResponse response){
        projectDailyPlan.setArrangeDailyPlan("1");
        List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
        Page<ProjectDailyPlan> page = findPageList(new Page<ProjectDailyPlan>(request, response),projectDailyPlan,projectPlans);
        return getBootstrapData(page);
    }

    //安排停电开关和具体时间列表页面
    //安排时间
    @ResponseBody
    @RequestMapping(value = "addtimeNet")
    public AjaxJson getAddtimeNet(ProjectDailyPlan projectDailyPlan,HttpServletRequest request){
        AjaxJson ajaxJson = new AjaxJson();
        List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
        try {
            for (ProjectDailyPlan plan:projectPlans){
                if (plan.getId().equals(projectDailyPlan.getId())){
                    plan.setProjectDate(projectDailyPlan.getProjectDate());
                    break;
                }
            }
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("安排时间成功");
            return ajaxJson;
        }catch (Exception e){
            e.printStackTrace();
        }
        ajaxJson.setSuccess(false);
        ajaxJson.setMsg("安排时间失败");
        return ajaxJson;
    }

    //新增日计划备注按钮
    @ResponseBody
    @RequestMapping(value = "remarksBack")
    public Result remarksBack(String ids,String remarks,HttpServletRequest request){
        Result j = new Result();
        List<String> strings = PackagingUtil.getString(ids);
        try {
            String comment = URLDecoder.decode(remarks, "UTF-8");
            List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
            for (ProjectDailyPlan plan:projectPlans){
                for (String s:strings){
                    if (plan.getId().equals(s)){
                        plan.setRemarks(comment);
                    }
                }
            }
            List<Map<String,Object>> objects = Lists.newArrayList();
            List<Map<String, Object>> bookStrapTree = BookStrapTreeUtil.getDailyBookStrapTree(objects, projectPlans);
            j.setMapListTree(bookStrapTree);
            j.setSuccess(true);
            j.setMessage("取消计划成功");
            j.setSuccess(true);
            j.setMessage("备注成功");
            return j;
        }catch (Exception e){
            e.printStackTrace();
        }
        j.setSuccess(false);
        j.setMessage("备注失败");
        return j;
    }

    @ResponseBody
    @RequestMapping(value = "sureInspection")
    public AjaxJson sureInspection(String ids,ProjectDailyPlan projectDailyPlan,Model model,HttpServletRequest request,HttpServletResponse response){
        AjaxJson j = new AjaxJson();
        try {
            List<ProjectDailyPlan> projectPlans = (List<ProjectDailyPlan>)request.getSession().getAttribute("sxDailyPlan");
            List<ProjectDailyPlan> idsList = projectDailyPlanService.getInspectionFunction(ids);
            projectDailyPlanService.getPlanDaily(projectPlans,idsList);
            j.setSuccess(true);
            j.setMsg("安排日计划成功");
            request.getSession().setAttribute("sxDailyPlan","");
            return j;
        }catch (Exception e){
            e.printStackTrace();
        }
        j.setSuccess(false);
        j.setMsg("安排日计划失败");
        return j;
    }

    @ResponseBody
    @RequestMapping(value = "import")
    public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            StringBuilder failureMsg = new StringBuilder();
            ImportUtil importUtil = new ImportUtil(file,0,0);
            List<ProjectDailyPlan> materProUtil = projectDailyPlanService.getMaterProUtil(importUtil);
            projectDailyPlanService.insertList(materProUtil);
            j.setMsg( "已成功导入项目"+materProUtil.size()+"条计划安排记录记录");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息："+e.getMessage());
        }
        return j;
    }

    //修改查看功能
    @RequestMapping(value = "updateAndView")
    public String updateAndView(ProjectDailyPlan projectDailyPlan,Model model){
        ProjectDailyPlan projectDaily = null;
        if (null!=projectDailyPlan.getId()&&!projectDailyPlan.getId().equals("")){
           projectDaily = projectDailyPlanService.get(projectDailyPlan.getId());
        }
        model.addAttribute("projectDailyPlan",projectDaily);
        return "modules/sg/managementcenter/projectPlanArrage/dailyPlan/projectDailyPlanForm";
    }

    //保存
    @ResponseBody
    @RequestMapping(value = "update")
    public AjaxJson update(ProjectDailyPlan projectDailyPlan){
        AjaxJson j = new AjaxJson();
        try {
            projectDailyPlanService.update(projectDailyPlan);
            j.setSuccess(true);
            j.setMsg("修改成功");
            return j;
        }catch (Exception e){
            e.printStackTrace();
        }
        j.setSuccess(false);
        j.setMsg("修改失败");
        return j;
    }
}
