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

import java.beans.PropertyEditorSupport;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

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

import com.google.common.collect.Maps;
import com.jeeplus.modules.workreview.entity.WorkReviewStandard;
import org.apache.commons.lang3.StringEscapeUtils;
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.WebDataBinder;
import org.springframework.web.bind.annotation.*;
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.workjobgrade.entity.WorkJobGrade;
import com.jeeplus.modules.workjobgrade.service.WorkJobGradeService;

/**
 * 职级类型Controller
 * @author ssrh
 * @version 2018-08-02
 */
@Controller
@RequestMapping(value = "${adminPath}/workjobgrade/workJobGrade")
public class WorkJobGradeController extends BaseController {

	@Autowired
	private WorkJobGradeService workJobGradeService;
	
	@ModelAttribute
	public WorkJobGrade get(@RequestParam(required=false) String id) {
		WorkJobGrade entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workJobGradeService.get(id);
		}
		if (entity == null){
			entity = new WorkJobGrade();
		}
		return entity;
	}
	
	/**
	 * 职级类型列表页面
	 */
	@RequiresPermissions("workjobgrade:workJobGrade:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkJobGrade workJobGrade, HttpServletRequest request, HttpServletResponse response, Model model) {
        List<WorkJobGrade> list = workJobGradeService.findList(workJobGrade);
        model.addAttribute("list", list);
		return "modules/workjobgrade/workJobGradeList";
	}

	/**
	 * 查看，增加，编辑职级类型表单页面
	 */
	@RequiresPermissions(value={"workjobgrade:workJobGrade:add","workjobgrade:workJobGrade:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkJobGrade workJobGrade, Model model) {
	    if(workJobGrade.getIsNewRecord()){
	        workJobGrade.setIsLeaf("是");
	        workJobGrade.setState("启用");
        }
		model.addAttribute("workJobGrade", workJobGrade);
		return "modules/workjobgrade/workJobGradeForm";
	}
	/**
	 * 查看，增加，编辑职级类型表单页面
	 */
	@RequestMapping(value = "view")
	public String view(WorkJobGrade workJobGrade, Model model) {
	    if(workJobGrade.getIsNewRecord()){
	        workJobGrade.setIsLeaf("是");
	        workJobGrade.setState("启用");
        }
		model.addAttribute("workJobGrade", workJobGrade);
		return "modules/workjobgrade/workJobGradeView";
	}

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

	/**
	 * 导入Excel数据

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

    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        WorkJobGrade workJobGrade = new WorkJobGrade();
        workJobGrade.setState("启用");
        List<WorkJobGrade> list = workJobGradeService.findList(workJobGrade);
        for (int i = 0; i < list.size(); i++) {
            WorkJobGrade e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1)) ) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getName());
                map.put("no", e.getNo());
                map.put("salary", e.getPay());
                mapList.add(map);
            }
        }
        return mapList;
    }
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
        // 数字类型转换
        binder.registerCustomEditor(Double.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                DecimalFormat df =   new DecimalFormat("###,##0.00");
                try {
                    if(StringUtils.isNotBlank(text)) {
                        setValue(df.parse(text).doubleValue());
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 启用、禁用工作内容类型
     */
    @RequiresPermissions("workjobgrade:workJobGrade:edit")
    @RequestMapping(value = "change")
    public String changeStatus(WorkJobGrade workJobGrade, RedirectAttributes redirectAttributes) {
        String msg = workJobGradeService.changeState(workJobGrade);
        addMessage(redirectAttributes, msg+"工作内容类型成功");
        return "redirect:"+Global.getAdminPath()+"/workjobgrade/workJobGrade/?repage";
    }
}