/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workofficechange.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.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.workofficechange.entity.WorkOfficeChangeUser;
import com.jeeplus.modules.workofficechange.service.WorkOfficeChangeUserService;

/**
 * 调转成员Controller
 * @author chenyuping
 * @version 2018-08-01
 */
@Controller
@RequestMapping(value = "${adminPath}/workofficechange/workOfficeChangeUser")
public class WorkOfficeChangeUserController extends BaseController {

	@Autowired
	private WorkOfficeChangeUserService workOfficeChangeUserService;
    @Autowired
    private WorkStaffAchivesDao workStaffAchivesDao;
    @Autowired
    private WorkJobGradeDao workJobGradeDao;
	@ModelAttribute
	public WorkOfficeChangeUser get(@RequestParam(required=false) String id) {
		WorkOfficeChangeUser entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workOfficeChangeUserService.get(id);
		}
		if (entity == null){
			entity = new WorkOfficeChangeUser();
		}
		return entity;
	}
	
	/**
	 * 调转成员列表页面
	 */
	@RequiresPermissions("workofficechange:workOfficeChangeUser:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkOfficeChangeUser workOfficeChangeUser, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkOfficeChangeUser> page = workOfficeChangeUserService.findPage(new Page<WorkOfficeChangeUser>(request, response), workOfficeChangeUser); 
		model.addAttribute("page", page);
		return "modules/workofficechange/workOfficeChangeUserList";
	}

	/**
	 * 查看，增加，编辑调转成员表单页面
	 */
	@RequiresPermissions(value={"workofficechange:workOfficeChangeUser:view","workofficechange:workOfficeChangeUser:add","workofficechange:workOfficeChangeUser:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkOfficeChangeUser workOfficeChangeUser, Model model) {
		model.addAttribute("workOfficeChangeUser", workOfficeChangeUser);
		return "modules/workofficechange/workOfficeChangeUserForm";
	}

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

	/**
	 * 导入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<WorkOfficeChangeUser> list = ei.getDataList(WorkOfficeChangeUser.class);

            StringBuilder stringBuilder=new StringBuilder();
			for (WorkOfficeChangeUser workOfficeChangeUser : list){
				try{
                    WorkStaffBasicInfo workStaffBasicInfo=new WorkStaffBasicInfo();
                    workStaffBasicInfo.setNo(workOfficeChangeUser.getNo());
                    workStaffBasicInfo.setName(workOfficeChangeUser.getName());
                    WorkStaffBasicInfo basicInfo=workStaffAchivesDao.findUserInfoExcel(workStaffBasicInfo);
                    Boolean flat=false;
                    if(basicInfo!=null){
                        flat=true;
                        if(StringUtils.isNotBlank(workOfficeChangeUser.getNewJob())){
                            WorkJobGrade jobGrade=new WorkJobGrade();
                            jobGrade.setName(workOfficeChangeUser.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("员工:"+workOfficeChangeUser.getName()+"的新职级！["+workOfficeChangeUser.getNewJob()+"]在系统中未定义请联系管理员！");
                            }
                        }
                        if(flat){
                            successNum++;
                            workStaffBasicInfos.add(basicInfo);
                        }
                    }else{
                        stringBuilder.append("员工:["+workOfficeChangeUser.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("workofficechange:workOfficeChangeUser:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "调转成员数据导入模板.xlsx";
    		List<WorkOfficeChangeUser> list = Lists.newArrayList(); 
    		new ExportExcel("调转成员数据", WorkOfficeChangeUser.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workofficechange/workOfficeChangeUser/?repage";
    }
	
	
	

}