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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.workfullmanage.entity.WorkFullConstruct;
import com.jeeplus.modules.workfullmanage.service.WorkFullConstructService;
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;

/**
 * 施工单位联系人Controller
 * @author mapengbo
 * @version 2017-10-25
 */
@Controller
@RequestMapping(value = "${adminPath}/workfullmanage/workFullConstruct")
public class WorkFullConstructController extends BaseController {

	@Autowired
	private WorkFullConstructService workFullConstructService;

	@Autowired
	private HttpServletRequest request;
	@ModelAttribute
	public WorkFullConstruct get(@RequestParam(required=false) String id) {
		WorkFullConstruct entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFullConstructService.get(id);
		}
		if (entity == null){
			entity = new WorkFullConstruct();
		}
		return entity;
	}
	
	/**
	 * 施工单位联系人列表页面
	 */
//	@RequiresPermissions("workfullmanage:workFullConstruct:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkFullConstruct workFullConstruct, HttpServletRequest request, HttpServletResponse response, Model model) {
		String index = request.getParameter("index");
		Page<WorkFullConstruct> page = workFullConstructService.findPage(new Page<WorkFullConstruct>(request, response), workFullConstruct);
		model.addAttribute("page", page);
		model.addAttribute("indexf",index);
		return "modules/workfullmanage/workFullConstructList";
	}

	/**
	 * 查看，增加，编辑施工单位联系人表单页面
	 */
//	@RequiresPermissions(value={"workfullmanage:workFullConstruct:view","workfullmanage:workFullConstruct:add","workfullmanage:workFullConstruct:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkFullConstruct workFullConstruct, Model model) {
		String tabId = request.getParameter("tabId");
		String view = "workFullConstructForm";
		if("1".equals(tabId)){
			view = "workFullConstructFormDetail";
		}
		model.addAttribute("workFull", workFullConstruct);
		return "modules/workfullmanage/"+view;
	}

	/**
	 * 保存施工单位联系人
	 */
//	@RequiresPermissions(value={"workfullmanage:workFullConstruct:add","workfullmanage:workFullConstruct:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	@ResponseBody
	public HashMap<Object,Object> save(WorkFullConstruct workFullConstruct, Model model, RedirectAttributes redirectAttributes) throws Exception{
		HashMap<Object, Object> map = Maps.newHashMap();
		if(!workFullConstruct.getIsNewRecord()){//编辑表单保存
			WorkFullConstruct t = workFullConstructService.get(workFullConstruct.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullConstruct, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workFullConstructService.save(t);//保存
			map.put("str","修改成功");
		}else{//新增表单保存
			WorkFullConstruct unit_name = workFullConstructService.findUniqueByProperty("unit_name", workFullConstruct.getUnitName());
			if(unit_name != null){
				map.put("msg","cnounique");
				return map;
			}
			workFullConstructService.save(workFullConstruct);//保存
			map.put("str","新增成功");
		}
		map.put("id",workFullConstruct.getId());
		map.put("unitName",workFullConstruct.getUnitName());
		map.put("unitLinkMan",workFullConstruct.getUnitLinkMan());
		map.put("linkPhone",workFullConstruct.getLinkPhone());
		map.put("msg","cunique");
		return  map;
	}
	
	/**
	 * 删除施工单位联系人
	 */
//	@RequiresPermissions("workfullmanage:workFullConstruct:del")
	@RequestMapping(value = "delete")
	@ResponseBody
	public HashMap<Object, Object> delete(WorkFullConstruct workFullConstruct, RedirectAttributes redirectAttributes) {
		HashMap<Object, Object> map = Maps.newHashMap();
		workFullConstructService.delete(workFullConstruct);
		map.put("str","success");
		return map;
//		addMessage(redirectAttributes, "删除施工单位联系人成功");
//		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullConstruct/?repage";
	}
	
	/**
	 * 批量删除施工单位联系人
	 */
//	@RequiresPermissions("workfullmanage:workFullConstruct:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workFullConstructService.delete(workFullConstructService.get(id));
		}
		addMessage(redirectAttributes, "删除施工单位联系人成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullConstruct/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
//	@RequiresPermissions("workfullmanage:workFullConstruct:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkFullConstruct workFullConstruct, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "施工单位联系人"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkFullConstruct> page = workFullConstructService.findPage(new Page<WorkFullConstruct>(request, response, -1), workFullConstruct);
    		new ExportExcel("施工单位联系人", WorkFullConstruct.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出施工单位联系人记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullConstruct/?repage";
    }

	/**
	 * 导入Excel数据

	 */
//	@RequiresPermissions("workfullmanage:workFullConstruct: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<WorkFullConstruct> list = ei.getDataList(WorkFullConstruct.class);
			for (WorkFullConstruct workFullConstruct : list){
				try{
					workFullConstructService.save(workFullConstruct);
					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()+"/workfullmanage/workFullConstruct/?repage";
    }
	
	/**
	 * 下载导入施工单位联系人数据模板
	 */
//	@RequiresPermissions("workfullmanage:workFullConstruct:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "施工单位联系人数据导入模板.xlsx";
    		List<WorkFullConstruct> list = Lists.newArrayList();
    		new ExportExcel("施工单位联系人数据", WorkFullConstruct.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullConstruct/?repage";
    }
	
	
	

}