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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.project.entity.Projectgeneral;
import com.jeeplus.modules.project.entity.ProjectEvaluationRecord;
import com.jeeplus.modules.project.entity.Workprojectgroup;
import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.project.entity.Project;
import com.jeeplus.modules.project.service.ProjectService;

/**
 * 项目表Controller
 * @author fgy
 * @version 2017-10-12
 */
@Controller
@RequestMapping(value = "${adminPath}/project/project")
public class ProjectController extends BaseController {

	@Autowired
	private WorkContractInfoService workContractInfoService;
	@Autowired
	private ProjectService projectService;
	
	@ModelAttribute
	public Project get(@RequestParam(required=false) String id) {
		Project entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectService.get(id);
		}
		if (entity == null){
			entity = new Project();
		}
		return entity;
	}
	
	/**
	 * 项目列表页面
	 */
	@RequiresPermissions("project:project:list")
	@RequestMapping(value = {"list", ""})
	public String list(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Project> page = projectService.findPage(new Page<Project>(request, response), project); 
		model.addAttribute("page", page);
		return "modules/project/projectList";
	}

	/**
	 * 查看，增加，编辑项目表单页面
	 */
	@RequiresPermissions(value={"project:project:view","project:project:add","project:project:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Project project, Model model,@RequestParam(value = "readAttr",required = false)String readAttr) {
		model.addAttribute("disabled",readAttr==null||"".equals(readAttr)?"":"disabled");
		model.addAttribute("project", project);
		return "modules/project/projectForm";
	}

	/**
	 * 保存项目
	 */
	@RequiresPermissions(value={"project:project:add","project:project:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Project project, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, project)){
			return form(project, model,"");
		}
		if(!project.getIsNewRecord()){//编辑表单保存
			Project t = projectService.get(project.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(project, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			projectService.save(t);//保存
		}else{//新增表单保存
			projectService.save(project);//保存
		}
		addMessage(redirectAttributes, "保存项目成功");
		return "redirect:"+Global.getAdminPath()+"/project/project/?repage";
	}
	
	/**
	 * 删除项目
	 */
	@RequiresPermissions("project:project:del")
	@RequestMapping(value = "delete")
	public String delete(Project project, RedirectAttributes redirectAttributes) {
		projectService.delete(project);
		addMessage(redirectAttributes, "删除项目成功");
		return "redirect:"+Global.getAdminPath()+"/project/project/?repage";
	}
	
	/**
	 * 批量删除项目
	 */
	@RequiresPermissions("project:project:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			projectService.delete(projectService.get(id));
		}
		addMessage(redirectAttributes, "删除项目成功");
		return "redirect:"+Global.getAdminPath()+"/project/project/?repage";
	}

	/**
	 * 选择项目
	 */
	@RequestMapping(value = "selectProject")
	public String selectbiddingCompany(Project project, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Project> page = projectService.findPage(new Page<Project>(request, response),  project);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", project);
		model.addAttribute("page", page);
		return "modules/sys/gridselectproject";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("project:project:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Project project, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Project> page = projectService.findPage(new Page<Project>(request, response, -1), project);
    		new ExportExcel("项目", Project.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出项目记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/project/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("project:project: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<Project> list = ei.getDataList(Project.class);
			for (Project project : list){
				try{
					projectService.save(project);
					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()+"/project/project/?repage";
    }
	
	/**
	 * 下载导入项目数据模板
	 */
	@RequiresPermissions("project:project:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目数据导入模板.xlsx";
    		List<Project> list = Lists.newArrayList(); 
    		new ExportExcel("项目数据", Project.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/project/?repage";
    }
	
	
	/**
	 * 选择委托单位
	 */
	@RequestMapping(value = "selectentrustCompany")
	public String selectentrustCompany(WorkClientLinkman entrustCompany, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkClientLinkman> page = projectService.findPageByentrustCompany(new Page<WorkClientLinkman>(request, response),  entrustCompany);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", entrustCompany);
		model.addAttribute("page", page);
		return "modules/sys/gridselectproject";
	}
	/**
	 * 选择合同信息
	 */
	@RequestMapping(value = "selectcontractInfo")
	public String selectcontractInfo(WorkContractInfo contractInfo, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkContractInfo> page = projectService.findPageBycontractInfo(new Page<WorkContractInfo>(request, response),  contractInfo);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", contractInfo);
		model.addAttribute("page", page);
		return "modules/sys/project_contractSelect";
	}

	/**
	 * 根据 合同信息 的id，查询该条合同的具体数据
	 * @param contractInfoId
	 * @return
	 */
	@RequestMapping("/getSelectedContractInfoById")
	public String getSelectedContractInfoById(String contractInfoId,Model model){
		WorkContractInfo workContractInfo = workContractInfoService.get(contractInfoId);
		model.addAttribute("selectedContractInfoId",workContractInfo.getId()) ;
		return "modules/project/projectForm";
	}
	/**
	 * 选择项目概况
	 */
	@RequestMapping(value = "selectprojectGeneral")
	public String selectprojectGeneral(Projectgeneral projectGeneral, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Projectgeneral> page = projectService.findPageByprojectGeneral(new Page<Projectgeneral>(request, response),  projectGeneral);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", projectGeneral);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	/**
	 * 选择投标单位
	 */
	@RequestMapping(value = "selectworkClientLinkman")
	public String selectworkClientLinkman(WorkClientLinkman workClientLinkman, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkClientLinkman> page = projectService.findPageByworkClientLinkman(new Page<WorkClientLinkman>(request, response),  workClientLinkman);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", workClientLinkman);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	/**
	 * 选择评标记录
	 */
	@RequestMapping(value = "selectprojectEvaluationRecord")
	public String selectprojectEvaluationRecord(ProjectEvaluationRecord projectEvaluationRecord, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProjectEvaluationRecord> page = projectService.findPageByprojectEvaluationRecord(new Page<ProjectEvaluationRecord>(request, response),  projectEvaluationRecord);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", projectEvaluationRecord);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	/**
	 * 选择项目组信息
	 */
	@RequestMapping(value = "selectworkprojectgroup")
	public String selectworkprojectgroup(Workprojectgroup workprojectgroup, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Workprojectgroup> page = projectService.findPageByworkprojectgroup(new Page<Workprojectgroup>(request, response),  workprojectgroup);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", workprojectgroup);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	

}