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

import java.util.ArrayList;
import java.util.List;

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

import com.jeeplus.modules.workjobgrade.dao.WorkJobGradeDao;
import com.jeeplus.modules.workjobgrade.entity.WorkJobGrade;
import com.jeeplus.modules.workofficechange.entity.WorkOfficeChangeUser;
import com.jeeplus.modules.workreceiptsregister.entity.ResponseEntity;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
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 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.workchangejob.entity.WorkChangeJobUser;
import com.jeeplus.modules.workchangejob.service.WorkChangeJobUserService;

/**
 * 职级调整明细Controller
 * @author chenyuping
 * @version 2018-08-02
 */
@Controller
@RequestMapping(value = "${adminPath}/workchangejob/workChangeJobUser")
public class WorkChangeJobUserController extends BaseController {

	@Autowired
	private WorkChangeJobUserService workChangeJobUserService;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;
	@Autowired
	private WorkJobGradeDao workJobGradeDao;
	@ModelAttribute
	public WorkChangeJobUser get(@RequestParam(required=false) String id) {
		WorkChangeJobUser entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workChangeJobUserService.get(id);
		}
		if (entity == null){
			entity = new WorkChangeJobUser();
		}
		return entity;
	}
	
	/**
	 * 职级调整明细列表页面
	 */
	@RequiresPermissions("workchangejob:workChangeJobUser:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkChangeJobUser workChangeJobUser, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkChangeJobUser> page = workChangeJobUserService.findPage(new Page<WorkChangeJobUser>(request, response), workChangeJobUser); 
		model.addAttribute("page", page);
		return "modules/workchangejob/workChangeJobUserList";
	}

	/**
	 * 查看，增加，编辑职级调整明细表单页面
	 */
	@RequiresPermissions(value={"workchangejob:workChangeJobUser:view","workchangejob:workChangeJobUser:add","workchangejob:workChangeJobUser:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkChangeJobUser workChangeJobUser, Model model) {
		model.addAttribute("workChangeJobUser", workChangeJobUser);
		return "modules/workchangejob/workChangeJobUserForm";
	}

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

	/**
	 * 导入Excel数据

	 */
	/**
	 * 导入Excel数据

	 */
	//@RequiresPermissions("workofficechange:workOfficeChangeUser:import")
	@RequestMapping(value = "import")
	@ResponseBody
	public ResponseEntity importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		List<WorkStaffBasicInfo> workStaffBasicInfos=new ArrayList<>();
		ResponseEntity<WorkStaffBasicInfo> responseEntity = new ResponseEntity<>();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkChangeJobUser> list = ei.getDataList(WorkChangeJobUser.class);

			StringBuilder stringBuilder=new StringBuilder();
			for (WorkChangeJobUser workChangeJobUser : list){
				try{
					WorkStaffBasicInfo workStaffBasicInfo=new WorkStaffBasicInfo();
					workStaffBasicInfo.setNo(workChangeJobUser.getNo());
					workStaffBasicInfo.setName(workChangeJobUser.getName());
					WorkStaffBasicInfo basicInfo=workStaffAchivesDao.findUserInfoExcel(workStaffBasicInfo);
					Boolean flat=false;
					if(basicInfo!=null){
						flat=true;
						if(StringUtils.isNotBlank(workChangeJobUser.getNewJob())){
							WorkJobGrade jobGrade=new WorkJobGrade();
							jobGrade.setName(workChangeJobUser.getNewJob());
							jobGrade.setBranchOffice(basicInfo.getBranchOffice().getId());
							List<WorkJobGrade> workJobGrades=workJobGradeDao.findByBranchOffice(jobGrade);
							if(workJobGrades!=null&&workJobGrades.size()>0){
								basicInfo.setSqlStr(workJobGrades.get(0).getName());
								basicInfo.setBankName(workJobGrades.get(0).getId());
								workStaffBasicInfos.add(basicInfo);
								flat=false;
								successNum++;
							}else{
								stringBuilder.append("员工:"+workChangeJobUser.getName()+"的新职级！["+workChangeJobUser.getNewJob()+"]在系统中未定义请联系管理员！");
							}
						}
						if(flat){
							successNum++;
							workStaffBasicInfos.add(basicInfo);
						}
					}else{
						stringBuilder.append("员工:["+workChangeJobUser.getName()+"]在人员档案中未找到！");
					}
					responseEntity.setData(workStaffBasicInfos);
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条调转成员记录。");
			}
			//addMessage(redirectAttributes, "已成功导入 "+successNum+" 条调转成员记录"+failureMsg+stringBuilder.toString());
			responseEntity.setMessage("已成功导入 "+successNum+" 条调转成员记录"+failureMsg+stringBuilder.toString());
		} catch (Exception e) {
			//addMessage(redirectAttributes, "导入调转成员失败！失败信息："+e.getMessage());
			responseEntity.setMessage("导入调转成员失败！失败信息："+e.getMessage());
		}
		return responseEntity;
	}
	
	/**
	 * 下载导入职级调整明细数据模板
	 */
	//@RequiresPermissions("workchangejob:workChangeJobUser:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "职级调整明细数据导入模板.xlsx";
    		List<WorkChangeJobUser> list = Lists.newArrayList(); 
    		new ExportExcel("职级调整明细数据", WorkChangeJobUser.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workchangejob/workChangeJobUser/?repage";
    }
	
	
	

}