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

import java.util.ArrayList;
import java.util.HashMap;
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.sys.entity.Office;
import com.jeeplus.modules.workreview.entity.WorkReviewAudit;
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.workreview.entity.WorkReviewStandard;
import com.jeeplus.modules.workreview.service.WorkReviewStandardService;

/**
 * 复核标准Controller
 * @author ssrh
 * @version 2018-06-01
 */
@Controller
@RequestMapping(value = "${adminPath}/workreview/workReviewStandard")
public class WorkReviewStandardController extends BaseController {

	@Autowired
	private WorkReviewStandardService workReviewStandardService;
	
	@ModelAttribute
	public WorkReviewStandard get(@RequestParam(required=false) String id) {
		WorkReviewStandard entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workReviewStandardService.get(id);
		}
		if (entity == null){
			entity = new WorkReviewStandard();
		}
		return entity;
	}
	
	/**
	 * 复核标准列表页面
	 */
	@RequiresPermissions("workreview:workReviewStandard:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkReviewStandard workReviewStandard, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<WorkReviewStandard> list = workReviewStandardService.findList(workReviewStandard);
		workReviewStandardService.queryProofread(list);
		model.addAttribute("list", list);
		return "modules/workreview/workReviewStandardList";
	}

	/**
	 * 查看，增加，编辑复核标准表单页面
	 */
	@RequiresPermissions(value={"workreview:workReviewStandard:view","workreview:workReviewStandard:add","workreview:workReviewStandard:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkReviewStandard workReviewStandard, Model model) {
	    if(workReviewStandard!=null&&workReviewStandard.getParent()!=null&&StringUtils.isNotBlank(workReviewStandard.getParent().getId())){
            WorkReviewStandard parent = workReviewStandardService.get(workReviewStandard.getParent().getId());
            workReviewStandard.setParent(parent);
            List<WorkReviewStandard> list = new ArrayList<>();
            list.add(workReviewStandard);
            workReviewStandardService.queryProofread(list);
        }
		model.addAttribute("workReviewStandard", workReviewStandard);
		return "modules/workreview/workReviewStandardForm";
	}

    /**
     * 查看，增加，编辑复核标准表单页面
     */
    @RequiresPermissions(value={"workreview:workReviewStandard:view","workreview:workReviewStandard:add","workreview:workReviewStandard:edit"},logical=Logical.OR)
    @RequestMapping(value = "view")
    public String view(WorkReviewStandard workReviewStandard, Model model) {
        if(workReviewStandard!=null&&workReviewStandard.getParent()!=null&&StringUtils.isNotBlank(workReviewStandard.getParent().getId())){
            WorkReviewStandard parent = workReviewStandardService.get(workReviewStandard.getParent().getId());
            workReviewStandard.setParent(parent);
            List<WorkReviewStandard> list = new ArrayList<>();
            list.add(workReviewStandard);
            workReviewStandardService.queryProofread(list);
        }
        model.addAttribute("workReviewStandard", workReviewStandard);
        return "modules/workreview/workReviewStandardView";
    }

	/**
	 * 保存复核标准
	 */
	@RequiresPermissions(value={"workreview:workReviewStandard:add","workreview:workReviewStandard:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkReviewStandard workReviewStandard, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workReviewStandard)){
			return form(workReviewStandard, model);
		}
		if(!workReviewStandard.getIsNewRecord()){//编辑表单保存
			WorkReviewStandard t = workReviewStandardService.get(workReviewStandard.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workReviewStandard, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workReviewStandardService.save(t);//保存
		}else{//新增表单保存
			workReviewStandardService.save(workReviewStandard);//保存
		}
		addMessage(redirectAttributes, "保存复核标准成功");
		return "redirect:"+Global.getAdminPath()+"/workreview/workReviewStandard/?repage";
	}
	
	/**
	 * 删除复核标准
	 */
	@RequiresPermissions("workreview:workReviewStandard:del")
	@RequestMapping(value = "delete")
	public String delete(WorkReviewStandard workReviewStandard, RedirectAttributes redirectAttributes) {
		workReviewStandardService.delete(workReviewStandard);
		addMessage(redirectAttributes, "删除复核标准成功");
		return "redirect:"+Global.getAdminPath()+"/workreview/workReviewStandard/?repage";
	}
	
	/**
	 * 批量删除复核标准
	 */
	@RequiresPermissions("workreview:workReviewStandard:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workReviewStandardService.delete(workReviewStandardService.get(id));
		}
		addMessage(redirectAttributes, "删除复核标准成功");
		return "redirect:"+Global.getAdminPath()+"/workreview/workReviewStandard/?repage";
	}
	/**
	 * 批量删除复核标准
	 */
	@RequestMapping(value = "reviewAudit")
	@ResponseBody
	public Map<String,Object> reviewAudit(String auditId, RedirectAttributes redirectAttributes) {
		Map<String,Object> map = new HashMap<>();
		try {
			WorkReviewAudit audit = workReviewStandardService.getAudit(auditId);
			audit.setRemarks("确认");
			workReviewStandardService.updateAudit(audit);
			map.put("status",true);
		}catch (Exception e){
			map.put("status",false);
		}
		return map;
	}
	/**
	 * 批量删除复核标准
	 */
	@RequestMapping(value = "reportMaxDeduct")
	@ResponseBody
	public Map<String,Object> reportMaxDeduct(String id,String maxDeduct, RedirectAttributes redirectAttributes) {
		Map<String,Object> map = new HashMap<>();
		try {
			workReviewStandardService.reportMaxDeduct(id,maxDeduct);
			map.put("status",true);
		}catch (Exception e){
			map.put("status",false);
		}
		return map;
	}
	/**
	 * 批量删除复核标准
	 */
	@RequestMapping(value = "reviewData")
	@ResponseBody
	public Map<String,Object> reviewData(String auditId,String content, RedirectAttributes redirectAttributes) {
		Map<String,Object> map = new HashMap<>();
		try {
			WorkReviewAudit workReviewAudit = workReviewStandardService.getAudit(auditId);
			WorkReviewAudit value = new WorkReviewAudit();
			value.setStandardDetail(content);
			value.setParent(workReviewAudit);
			value.setParentIds(workReviewAudit.getParentIds()+workReviewAudit.getId()+"");
			String orderNum = workReviewStandardService.selectOrderNumAudit(workReviewAudit.getId());
			if (StringUtils.isBlank(orderNum)) {
				value.setOrderNum(workReviewAudit.getOrderNum() + "01");
			} else {
				value.setOrderNum(String.valueOf(Integer.valueOf(orderNum) + 1));
			}
			value.setType("6");
			value.preInsert();
			value.setCompanyId(workReviewAudit.getCompanyId());
			value.setReportId(workReviewAudit.getReportId());
			workReviewStandardService.saveAudit(value);
			map.put("status",true);
			map.put("id",value.getId());
		}catch (Exception e){
			logger.error("Exception e"+e);
			map.put("status",false);
		}
		return map;
	}
	@RequestMapping(value = "deleteData")
	@ResponseBody
	public Map<String,Object> deleteData(String id, RedirectAttributes redirectAttributes) {
		Map<String,Object> map = new HashMap<>();
		try {
			workReviewStandardService.deleteAuditById(id);
			map.put("status",true);
		}catch (Exception e){
			logger.error("Exception e"+e);
			map.put("status",false);
		}
		return map;
	}

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

	/**
	 * 导入Excel数据

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


    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param response
     * @return
     */
    @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();
        List<WorkReviewStandard> list = workReviewStandardService.findTreeList(new WorkReviewStandard());
        for (int i = 0; i < list.size(); i++) {
            WorkReviewStandard 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.getStandardDetail());
                map.put("grade", e.getGrade());
                mapList.add(map);
            }
        }
        return mapList;
    }


    @ResponseBody
    @RequestMapping(value = "jsonData")
    public WorkReviewStandard jsonData(@RequestParam(required = false) String id, HttpServletResponse response) {
        WorkReviewStandard entity = null;
        if (StringUtils.isNotBlank(id)){
            entity = workReviewStandardService.get(id);
        }
        if (entity == null){
            entity = new WorkReviewStandard();
        }
        List<WorkReviewStandard> list = new ArrayList<>();
        list.add(entity);
        workReviewStandardService.queryProofread(list);
        return entity;
    }
}