/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workbidingproject.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.sys.entity.Role;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workbidingproject.entity.WorkBidingProject;
import com.jeeplus.modules.workbidingproject.service.WorkBidingProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
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.*;
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.List;

/**
 * 招标项目Controller
 * @author 杨帆
 * @version 2017-12-25
 */
@Controller
@RequestMapping(value = "${adminPath}/workbidingproject/workBidingProject")
public class WorkBidingProjectController extends BaseController {

	@Autowired
	private WorkBidingProjectService workBidingProjectService;
	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private WorkClientInfoService workClientInfoService;

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

	/**
	 * 招标项目信息列表页面
	 */
	@RequiresPermissions("workbidingproject:workBidingProject:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkBidingProject workBidingProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getSelectOffice().getName().contains("招标")){
			workBidingProject.setBiddingType("-1");
			model.addAttribute("status", "1");
		}else {
			model.addAttribute("status", "2");
		}
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workBidingProject.setQueryCon(id);
		}
		Page<WorkBidingProject> page = workBidingProjectService.findPage(new Page<WorkBidingProject>(request, response), workBidingProject);
		model.addAttribute("page", page);
		return "modules/workbidingproject/workBidingProjectList";
	}

	/**
	 * 查看，增加，编辑招标项目信息表单页面
	 */
	@RequiresPermissions(value={"workbidingproject:workBidingProject:view","workbidingproject:workBidingProject:add","workbidingproject:workBidingProject:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkBidingProject workBidingProject, Model model) {

		String linkmanList = "";
		if(workBidingProject.getClient()!=null){
			WorkClientInfo workClientInfo = workClientInfoService.get(workBidingProject.getClient().getId());
			linkmanList = workBidingProjectService.parseList2Json(workClientInfo);
		}
		model.addAttribute("linkmanList",linkmanList);
		model.addAttribute("workBidingProject", workBidingProject);
		if (StringUtils.isNotBlank(workBidingProject.getName()) && workBidingProject.getName().equals("view")){
			return "modules/workbidingproject/workBidingProjectView";
		}
		return "modules/workbidingproject/workBidingProjectForm";
	}

	/**
	 * 获取客户信息
	 * @return
	 */
	@RequestMapping(value = "getWorkClientInfo")
	@ResponseBody
	public String getWorkClientInfo(HttpServletRequest request){
		String obj = request.getParameter("obj");
		WorkClientInfo workClientInfo = workClientInfoService.get(obj);
		String resultJsonStr = workBidingProjectService.parseList2Json(workClientInfo);
		return resultJsonStr;
	}


	/**
	 * 保存招标项目信息
	 */
	@RequiresPermissions(value={"workbidingproject:workBidingProject:add","workbidingproject:workBidingProject:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkBidingProject workBidingProject, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workBidingProject)){
			return form(workBidingProject, model);
		}
		if(!workBidingProject.getIsNewRecord()){//编辑表单保存
			WorkBidingProject t = workBidingProjectService.get(workBidingProject.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBidingProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			String masters = workBidingProject.getProjectMasterIds();
			String members = workBidingProject.getProjectMemberIds();
			String inventorUserIds = workBidingProject.getInventorUserIds();
			if (StringUtils.isNotBlank(masters)) {
				t.setProjectMaster(masters);
			}
			if (StringUtils.isNotBlank(members)) {
				t.setProjectMember(members);
			}
			if (StringUtils.isNotBlank(inventorUserIds)) {
				t.setInventorUser(inventorUserIds);
			}

			WorkProject workProject = workProjectService.get(t.getWorkProject().getId());
			workProject.setName(t.getProjectName());
			workProject.setUpdateBy(t.getUpdateBy());
			workProject.setUpdateDate(t.getUpdateDate());
			workProjectService.update(workProject);//保存项目总表
			workBidingProjectService.save(t);//保存
		}else{//新增表单保存
			workBidingProject.setCompanyId(UserUtils.getSelectCompany().getId());
			workBidingProject.setOffice(UserUtils.getSelectOffice());
			workBidingProject.setStatus("1");
			String masters = workBidingProject.getProjectMasterIds();
			String members = workBidingProject.getProjectMemberIds();
			String inventorUserIds = workBidingProject.getInventorUserIds();
			workBidingProject.setProjectMember(members);
			workBidingProject.setProjectMaster(masters);
			workBidingProject.setInventorUser(inventorUserIds);


			WorkProject w = new WorkProject();
			w.setNumber(workBidingProject.getProjectNumber());
			w.setName(workBidingProject.getProjectName());
			w.setContractId(workBidingProject.getContract());
			w.setCreateBy(workBidingProject.getCreateBy());
			w.setCreateDate(workBidingProject.getCreateDate());
			w.setDelFlag(workBidingProject.getDelFlag());
			w.setUpdateBy(workBidingProject.getUpdateBy());
			w.setUpdateDate(workBidingProject.getUpdateDate());
			w.setCompanyId(UserUtils.getSelectCompany().getId());
			w.setRemarks(workBidingProject.getRemarks());
			w.setOfficeId(workBidingProject.getOffice()==null?"":workBidingProject.getOffice().getId());
			w.setSort("招标代理");
			workProjectService.save(w);//保存总项目表
			workBidingProject.setWorkProject(w);
			workBidingProjectService.save(workBidingProject);//保存

		}
		addMessage(redirectAttributes, "保存招标项目信息成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingproject/workBidingProject/?repage";
	}

	/**
	 * 删除招标项目信息
	 */
	@RequiresPermissions("workbidingproject:workBidingProject:del")
	@RequestMapping(value = "delete")
	public String delete(WorkBidingProject workBidingProject, RedirectAttributes redirectAttributes) {
		workBidingProjectService.delete(workBidingProject);
		addMessage(redirectAttributes, "删除招标项目信息成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingproject/workBidingProject/?repage";
	}

	/**
	 * 批量删除招标项目信息
	 */
	@RequiresPermissions("workbidingproject:workBidingProject:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workBidingProjectService.delete(workBidingProjectService.get(id));
		}
		addMessage(redirectAttributes, "删除招标项目信息成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingproject/workBidingProject/?repage";
	}

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

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workbidingproject:workBidingProject: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<WorkBidingProject> list = ei.getDataList(WorkBidingProject.class);
			for (WorkBidingProject workBidingProject : list){
				try{
					workBidingProjectService.save(workBidingProject);
					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()+"/workbidingproject/workBidingProject/?repage";
	}

	/**
	 * 下载导入招标项目信息数据模板
	 */
	@RequiresPermissions("workbidingproject:workBidingProject:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "招标项目信息数据导入模板.xlsx";
			List<WorkBidingProject> list = Lists.newArrayList();
			new ExportExcel("招标项目信息数据", WorkBidingProject.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workbidingproject/workBidingProject/?repage";
	}




}