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

import java.util.List;

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

import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.modules.activityassignment.dao.ActivityAssignmentDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.utils.UserUtils;
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.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.workcontent.entity.WorkContentType;
import com.jeeplus.modules.workcontent.service.WorkContentTypeService;

/**
 * 工作内容类型Controller
 * @author ssrh
 * @version 2018-06-01
 */
@Controller
@RequestMapping(value = "${adminPath}/workcontent/workContentType")
public class WorkContentTypeController extends BaseController {

    private static WorkContentTypeService workContentTypeService = SpringContextHolder.getBean(WorkContentTypeService.class);

	@ModelAttribute
	public WorkContentType get(@RequestParam(required=false) String id) {
		WorkContentType entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workContentTypeService.get(id);
		}
		if (entity == null){
			entity = new WorkContentType();
		}
		return entity;
	}
	
	/**
	 * 工作内容类型列表页面
	 */
	@RequiresPermissions("workcontent:workContentType:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkContentType workContentType, HttpServletRequest request, HttpServletResponse response, Model model) {
        Office company = UserUtils.getSelectCompany();
        workContentType.setCompany(company);
        List<WorkContentType> list = workContentTypeService.findList(workContentType);
		model.addAttribute("list", list);
		return "modules/workcontent/workContentTypeList";
	}

	/**
	 * 查看，增加，编辑工作内容类型表单页面
	 */
	@RequiresPermissions(value={"workcontent:workContentType:view","workcontent:workContentType:add","workcontent:workContentType:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkContentType workContentType, Model model) {
		model.addAttribute("workContentType", workContentType);
		return "modules/workcontent/workContentTypeForm";
	}

	/**
	 * 保存工作内容类型
	 */
	@RequiresPermissions(value={"workcontent:workContentType:add","workcontent:workContentType:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkContentType workContentType, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workContentType)){
			return form(workContentType, model);
		}
		if(!workContentType.getIsNewRecord()){//编辑表单保存
			WorkContentType t = workContentTypeService.get(workContentType.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workContentType, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workContentTypeService.save(t);//保存
		}else{//新增表单保存
			workContentTypeService.save(workContentType);//保存
		}
		addMessage(redirectAttributes, "保存工作内容类型成功");
		return "redirect:"+Global.getAdminPath()+"/workcontent/workContentType/?repage";
	}
	
	/**
	 * 删除工作内容类型
	 */
	@RequiresPermissions("workcontent:workContentType:del")
	@RequestMapping(value = "delete")
	public String delete(WorkContentType workContentType, RedirectAttributes redirectAttributes) {
		workContentTypeService.delete(workContentType);
		addMessage(redirectAttributes, "删除工作内容类型成功");
		return "redirect:"+Global.getAdminPath()+"/workcontent/workContentType/?repage";
	}

	/**
	 * 启用、禁用工作内容类型
	 */
	@RequiresPermissions("workcontent:workContentType:edit")
	@RequestMapping(value = "change")
	public String changeStatus(WorkContentType workContentType, RedirectAttributes redirectAttributes) {
        Office company = UserUtils.getSelectCompany();
        workContentType.setCompany(company);
        String msg = workContentTypeService.changeStatus(workContentType);
        addMessage(redirectAttributes, msg+"工作内容类型成功");
		return "redirect:"+Global.getAdminPath()+"/workcontent/workContentType/?repage";
	}
	
	/**
	 * 批量删除工作内容类型
	 */
	@RequiresPermissions("workcontent:workContentType:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workContentTypeService.delete(workContentTypeService.get(id));
		}
		addMessage(redirectAttributes, "删除工作内容类型成功");
		return "redirect:"+Global.getAdminPath()+"/workcontent/workContentType/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workcontent:workContentType:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkContentType workContentType, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工作内容类型"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkContentType> page = workContentTypeService.findPage(new Page<WorkContentType>(request, response, -1), workContentType);
    		new ExportExcel("工作内容类型", WorkContentType.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出工作内容类型记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcontent/workContentType/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workcontent:workContentType: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<WorkContentType> list = ei.getDataList(WorkContentType.class);
			for (WorkContentType workContentType : list){
				try{
					workContentTypeService.save(workContentType);
					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()+"/workcontent/workContentType/?repage";
    }
	
	/**
	 * 下载导入工作内容类型数据模板
	 */
	@RequiresPermissions("workcontent:workContentType:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工作内容类型数据导入模板.xlsx";
    		List<WorkContentType> list = Lists.newArrayList(); 
    		new ExportExcel("工作内容类型数据", WorkContentType.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcontent/workContentType/?repage";
    }
	
	
	public static List<WorkContentType> getContentType(String parentId){
	    WorkContentType workContentType = new WorkContentType();
        Office company = UserUtils.getSelectCompany();
        workContentType.setCompany(company);
        workContentType.setParentId(parentId);
        workContentType.setDelFlag(WorkContentType.DEL_FLAG_NORMAL);
		List<WorkContentType> list = workContentTypeService.findList(workContentType);
		if("4".equals(parentId)){
			WorkContentType workContentType1 = new WorkContentType();
			workContentType1.setTypeId("400");
			workContentType1.setTypeName("合同动态汇总");
			workContentType1.setParentId("4");
			workContentType1.setParentIds("0,4");
			list.add(workContentType1);
		}
        return list;
    }
	public static List<WorkContentType> getProjectContentType(String parentId,String projectId){
		WorkContentType workContentType = new WorkContentType();
		Office company = UserUtils.getSelectCompany();
		workContentType.setCompany(company);
		workContentType.setParentId(parentId);
		workContentType.setProjectId(projectId);
		workContentType.setDelFlag(WorkContentType.DEL_FLAG_NORMAL);
		return workContentTypeService.findProjectList(workContentType);
	}
    public static String getContentTypeName(String typeId,String defaultVal){
	    if (StringUtils.isNotBlank(typeId)) {
            WorkContentType contentType = workContentTypeService.findUniqueByProperty("type_id", typeId);
            if (contentType != null) {
                return contentType.getTypeName();
            }
        }
        return defaultVal;
    }
}