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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectContentData;
import com.jeeplus.modules.projectcontroltable.entity.ProjectControlTable;
import com.jeeplus.modules.projectcontroltable.service.ProjectControlTableService;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcommunicaterecord.entity.WorkCommunicateContent;
import com.jeeplus.modules.workcommunicaterecord.entity.WorkCommunicateRecord;
import com.jeeplus.modules.workcommunicaterecord.service.WorkCommunicateContentService;
import com.jeeplus.modules.workcommunicaterecord.service.WorkCommunicateRecordService;
import com.jeeplus.modules.workdevicerecord.entity.WorkDeviceRecord;
import com.jeeplus.modules.workdevicerecord.entity.WorkDeviceXjRecord;
import com.jeeplus.modules.workdevicerecord.service.WorkDeviceRecordService;
import com.jeeplus.modules.workdevicerecord.service.WorkDeviceXjRecordService;
import com.jeeplus.modules.workexplore.entity.WorkExplore;
import com.jeeplus.modules.workexplore.service.WorkExploreService;
import com.jeeplus.modules.workhandbill.entity.WorkHandBill;
import com.jeeplus.modules.workhandbill.entity.WorkHandBillDetail;
import com.jeeplus.modules.workhandbill.service.WorkHandBillDetailService;
import com.jeeplus.modules.workhandbill.service.WorkHandBillService;
import com.jeeplus.modules.workinfolist.entity.WorkInfoList;
import com.jeeplus.modules.workinfolist.service.WorkInfoListService;
import com.jeeplus.modules.workprojectcalc.entity.WorkProjectCalcBuild;
import com.jeeplus.modules.workprojectcalc.entity.WorkProjectCalcDecor;
import com.jeeplus.modules.workprojectcalc.service.WorkProjectCalcBuildService;
import com.jeeplus.modules.workprojectcalc.service.WorkProjectCalcDecorService;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 过程控制表Controller
 * @author 马鹏波
 * @version 2018-06-08
 */
@Controller
@RequestMapping(value = "${adminPath}/projectcontroltable/projectControlTable")
public class ProjectControlTableController extends BaseController {

	@Autowired
	private ProjectControlTableService projectControlTableService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private ProjectRecordsService projectRecordsService;

	@ModelAttribute
	public ProjectControlTable get(@RequestParam(required=false) String id) {
		ProjectControlTable entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectControlTableService.get(id);
		}
		if (entity == null){
			entity = new ProjectControlTable();
		}
		return entity;
	}
	
	/**
	 * 过程控制表列表页面
	 */
//	@RequiresPermissions("projectcontroltable:projectControlTable:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProjectControlTable projectControlTable, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProjectControlTable> page = projectControlTableService.findPage(new Page<ProjectControlTable>(request, response), projectControlTable); 
		model.addAttribute("page", page);
		return "modules/projectcontroltable/projectControlTableList";
	}

	/**
	 * 查看，增加，编辑过程控制表表单页面
	 */
//	@RequiresPermissions(value={"projectcontroltable:projectControlTable:view","projectcontroltable:projectControlTable:add","projectcontroltable:projectControlTable:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ProjectControlTable projectControlTable, HttpServletRequest request,Model model) {
		String view = request.getParameter("view");
		if("view".equals(view)){
			view = "modules/projectcontroltable/projectControlTableFormView";
		}else{
			view = "modules/projectcontroltable/projectControlTableForm";
			if(projectControlTable.getPfId()!= null){
				ProjectRecords projectRecords = projectRecordsService.get(projectControlTable.getPfId());
				Area area = projectRecords.getArea();
				String city = projectRecords.getCity();
				model.addAttribute("city",city);
				model.addAttribute("area", area);
			}
		}
		if(!projectControlTable.getIsNewRecord()){
            String flag = projectControlTableService.getDetailInfo(projectControlTable);
			List<Workattachment> listByAttachmentIdAndFlag = workattachmentService.getListByAttachmentIdAndFlag(projectControlTable.getId(), flag);
			projectControlTable.setWorkAttachments(listByAttachmentIdAndFlag);
		}

		model.addAttribute("projectControlTable", projectControlTable);
		return view;
	}

	/**
	 * 保存过程控制表
	 */
//	@RequiresPermissions(value={"projectcontroltable:projectControlTable:add","projectcontroltable:projectControlTable:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(ProjectControlTable projectControlTable, HttpServletRequest request,Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, projectControlTable)){
			return form(projectControlTable, request,model);
		}
		if(!projectControlTable.getIsNewRecord()){//编辑表单保存
			ProjectControlTable t = projectControlTableService.get(projectControlTable.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(projectControlTable, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			projectControlTableService.save(t);//保存
		}else{//新增表单保存
			String id = UserUtils.getSelectCompany().getId();
			String userId = UserUtils.getUser().getId(); //当前登陆人
			String projectId = id + userId + projectControlTable.getPfId();	//项目编号
			projectControlTable.setPfId(projectId);
			projectControlTableService.save(projectControlTable);//保存
		}
		addMessage(redirectAttributes, "保存过程控制表成功");
		return projectControlTable.getId();
	}
	
	/**
	 * 删除过程控制表
	 */
//	@RequiresPermissions("projectcontroltable:projectControlTable:del")
	@RequestMapping(value = "delete")
	public String delete(ProjectControlTable projectControlTable, RedirectAttributes redirectAttributes) {
		projectControlTableService.delete(projectControlTable);
		addMessage(redirectAttributes, "删除过程控制表成功");
		return "redirect:"+Global.getAdminPath()+"/projectcontroltable/projectControlTable/?repage";
	}
	
	/**
	 * 批量删除过程控制表
	 */
//	@RequiresPermissions("projectcontroltable:projectControlTable:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			projectControlTableService.delete(projectControlTableService.get(id));
		}
		addMessage(redirectAttributes, "删除过程控制表成功");
		return "redirect:"+Global.getAdminPath()+"/projectcontroltable/projectControlTable/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("projectcontroltable:projectControlTable:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ProjectControlTable projectControlTable, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "过程控制表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProjectControlTable> page = projectControlTableService.findPage(new Page<ProjectControlTable>(request, response, -1), projectControlTable);
    		new ExportExcel("过程控制表", ProjectControlTable.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出过程控制表记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/projectcontroltable/projectControlTable/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("projectcontroltable:projectControlTable:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProjectControlTable> list = ei.getDataList(ProjectControlTable.class);
			for (ProjectControlTable projectControlTable : list){
				try{
					projectControlTableService.save(projectControlTable);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条过程控制表记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条过程控制表记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入过程控制表失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/projectcontroltable/projectControlTable/?repage";
    }
	
	/**
	 * 下载导入过程控制表数据模板
	 */
	@RequiresPermissions("projectcontroltable:projectControlTable:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "过程控制表数据导入模板.xlsx";
    		List<ProjectControlTable> list = Lists.newArrayList(); 
    		new ExportExcel("过程控制表数据", ProjectControlTable.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/projectcontroltable/projectControlTable/?repage";
    }

    @RequestMapping("getControlData")
    @ResponseBody
	public Map<Object,Object> getControlData(HttpServletRequest request){
		Map<Object,Object> map = new HashMap<>();
		String projectId = request.getParameter("projectId");
		String projectContentId = request.getParameter("proId");
		String id = UserUtils.getSelectCompany().getId();
		String userId = UserUtils.getUser().getId();
		projectId = id+userId+projectId;
		List<ProjectControlTable> controlData = projectControlTableService.getControlData(projectId,projectContentId);
		ProjectContentData projectContentData = new ProjectContentData();
		projectContentData.setProjectControlTableList(controlData);
		map.put("list",projectContentData);
		return map;
	}


	/**
	 * 删除所有数据
	 * @param request
	 * @return
	 */
	@RequestMapping("delControlData")
	@ResponseBody
	public Map<Object,Object> delControlData(HttpServletRequest request){
		Map<Object,Object> map = new HashMap<>();
		String projectId = request.getParameter("projectId");
		String flag = request.getParameter("flag");
		String projectContentId = request.getParameter("projectContentId");
		String id = UserUtils.getSelectCompany().getId();
		String userId = UserUtils.getUser().getId();
		projectId = id+userId+projectId;
		//点击删除 ，不是初始化删除时
		boolean b = false;
		if(!"del".equals(flag)){
			b = projectControlTableService.deleteAllData(projectId,"");
		}else{
			b = projectControlTableService.deleteAllData(projectId,projectContentId);
		}
		map.put("flag",b);
		return map;
	}
}