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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.iim.service.LayGroupService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.work.entity.report.WorkReport;
import com.jeeplus.modules.work.entity.report.WorkReportRecord;
import com.jeeplus.modules.work.entity.review.WorkReportReview;
import com.jeeplus.modules.work.service.report.WorkReportService;
import com.jeeplus.modules.work.service.review.WorkReportReviewService;
import com.jeeplus.modules.workborrowmangement.entity.WorkBorrowMangement;
import com.jeeplus.modules.workcalendar.entity.CalendarCountEntity;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

/**
 * 工作报告Controller
 * @author 许凯
 * @version 2017-04-21
 */
@Controller
@RequestMapping(value = "${adminPath}/work/report/workReport")
public class WorkReportController extends BaseController {

	@Autowired
	private WorkReportService workReportService;
	@Autowired
	private WorkReportReviewService workReportReviewService;
	@Autowired
	private LayGroupService layGroupService;

	
	@ModelAttribute
	public WorkReport get(@RequestParam(required=false) String id) {
		WorkReport entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workReportService.get(id);
		}
		if (entity == null){
			entity = new WorkReport();
		}
		return entity;
	}
	
	/**
	 * 工作报告列表页面(可以执行删除工作报告的操作；个人只能看到自己发布的，管理员可以看到全公司发布的；)
	 */
	@RequiresPermissions("work:report:workReport:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkReport workReport, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		boolean isManager = UserUtils.isManager();
		workReport.setStatus("1");

		if(user.isAdmin()){
			//Admin查看全平台发布的
		}else {
			workReport.setCompanyId(user.getComId());
			if(isManager){
				//公司管理员查看本公司发布的
			}else{
				//个人只查看自己发布的
				workReport.setCreateBy(user);
			}
		}
		Page<WorkReport> page = workReportService.findPage(new Page<WorkReport>(request, response), workReport);

		model.addAttribute("page", page);
		model.addAttribute("allList","allList");
		return "modules/work/report/workReportListAll";
	}
	
	
	/**
	 * 我收到的工作报告(我收到别人发给我的工作报告，不能删除)
	 */
	@RequestMapping(value = "getList")
	public String listGet(WorkReport workReport, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		workReport.setSelf(true);
		workReport.setCompanyId(user.getComId());
		workReport.setCurrentUser(user);

		Page<WorkReport> page = workReportService.findGetPage(new Page<WorkReport>(request, response), workReport);
		model.addAttribute("my_receive","true");
		model.addAttribute("getList","getList");
		model.addAttribute("page", page);
		return "modules/work/report/workReportListGet";
	}
	

	/**
	 * 我发出的工作报告(包含草稿和发布状态的，不能删除；要删除需要到"工作报告"列表执行)
	 */
	@RequestMapping(value = "outList")
	public String listOut(WorkReport workReport, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		workReport.setCurrentUser(user);
		workReport.setCompanyId(user.getComId());
		Page<WorkReport> page = workReportService.findOutPage(new Page<WorkReport>(request, response), workReport);
		model.addAttribute("my_send","true");
		model.addAttribute("outList","outList");
		model.addAttribute("page", page);
		return "modules/work/report/workReportListOut";
	}
	
	/**
	 * 查看，增加，编辑工作报告表单页面
	 */
	@RequiresPermissions(value={"work:report:workReport:view","work:report:workReport:add","work:report:workReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(@RequestParam(value = "readAttr",required = false)String readAttr,
					   WorkReport workReport, Model model,
					   @RequestParam(value = "view",required = false)String view,
					   @RequestParam(value = "updateReadFlag",required = false)String updateReadFlag,
					   @RequestParam(value = "forUpdate",required = false)String forUpdate) {


		//用于修改草稿状态的
		model.addAttribute("forUpdate",forUpdate);

		//在"我收到的工作报告"中，点击查看，同时更新阅读状态
		if(StringUtils.isNotBlank(updateReadFlag)&&"updateReadFlag".equals(updateReadFlag) && StringUtils.isNotBlank(workReport.getId())){
			//当前工作报告如果是发送给我的话，就将当前工作工作报告的阅读状态赋值
			if(workReport.getWorkReportRecordListUser().size()>0){
				for (int i = 0; i < workReport.getWorkReportRecordListUser().size(); i++) {
					WorkReportRecord workReportRecord = workReport.getWorkReportRecordListUser().get(i);
					if(workReportRecord!=null && workReportRecord.getUser().getId().equals(UserUtils.getUser().getId())){
						if("0".equals(workReportRecord.getReadFlag())){
							workReportService.updateReadFlag(workReport);
						}
					}
				}
			}
		}

		List<WorkReportReview> workReportReviewList =  workReportReviewService.findReviewListByReportId(workReport.getId());
		model.addAttribute("workReportReviewList",workReportReviewList);
		model.addAttribute("workReport", workReport);
		model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");


		if(workReport.getType().equals("1")){
			if(StringUtils.isNotBlank(view)&&view.equals("view")){
				return "modules/work/report/workReportViewDay";
			}
			return "modules/work/report/workReportFormDay";	
		}
		if(workReport.getType().equals("2")){
			if(StringUtils.isNotBlank(view)&&view.equals("view")){
				return "modules/work/report/workReportViewWeek";
			}
			return "modules/work/report/workReportFormWeek";	
		}
		if(workReport.getType().equals("3")){
			if(StringUtils.isNotBlank(view)&&view.equals("view")){
				return "modules/work/report/workReportViewMonth";
			}
			return "modules/work/report/workReportFormMonth";	
		}
		return adminPath;
		
	}

	/**
	 * 删除附件
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("delFile")
	@ResponseBody
	public AjaxJson delFile(WorkReport workReport, HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		String attaId = request.getParameter("attaId");
		String attachmentUrl = request.getParameter("attachmentUrl");
		workReportService.delFile(attaId,attachmentUrl);
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.put("attachmentUrl",attachmentUrl);
		return ajaxJson;
	}

	@RequiresPermissions(value={"work:report:workReport:view","work:report:workReport:add","work:report:workReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "formc")
	public String formChoose(@RequestParam(value = "readAttr",required = false)String readAttr,WorkReport workReport, Model model) {
		model.addAttribute("workReport", workReport);
		model.addAttribute("disabled",(readAttr==null||"".equals(readAttr))?"false":"true");
		//return "modules/work/report/workReportFormChoose";
		workReport.setType("1");  //默认选日报,在添加页面当选择的时候就跳到周报/月报
		return 	"modules/work/report/workReportFormDay";
	}

	/**
	 * 保存工作报告
	 */
	@RequiresPermissions(value={"work:report:workReport:add","work:report:workReport:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkReport workReport, Model model,
					   HttpServletRequest request,RedirectAttributes redirectAttributes/*,
					   @RequestParam(value = "this_upload_files",required = false)MultipartFile[] this_upload_files,
					   @RequestParam(value = "next_upload_files",required = false)MultipartFile[] next_upload_files*/) throws Exception{
		if (!beanValidator(model, workReport)){
			return form("",workReport, model,"","","");
		}
		workReport.setCompanyId(UserUtils.getUser().getComId());
		// 如果是修改，则状态为已发布，则不能再进行操作
		if (StringUtils.isNotBlank(workReport.getId())){
			WorkReport e = workReportService.get(workReport.getId());
			if ("1".equals(e.getStatus())){
				addMessage(redirectAttributes, "已发布，不能操作！");
				return "redirect:" + adminPath + "/work/report/workReport/?repage";
			}
		}
/*

		//--- 上传本月图片、日报图片
		String  this_uploadFolder = request.getSession().getServletContext().getRealPath("local_upload/workReport/"+System.nanoTime());
		new File(this_uploadFolder).mkdirs();
		List<String> this_imgList = new ArrayList<>();
		if(this_upload_files!=null && this_upload_files.length>0){
			for(int i=0;i<this_upload_files.length;i++){
				if(this_upload_files[i]==null || this_upload_files[i].getSize()==0)
					continue;
				String imageName = System.nanoTime()+this_upload_files[i].getOriginalFilename();
				String imageNewName = this_uploadFolder+"/"+imageName;
				this_imgList.add(imageNewName);
				try{
					this_upload_files[i].transferTo(new File(imageNewName));
				}catch (IllegalStateException | IOException e) {
					e.printStackTrace();
				}
			}
		}
		StringBuilder this_workreportFiles = new StringBuilder();
		InputStream inputStream = null;
		for(int i=0;i<this_imgList.size();i++) {
			String filePath = this_imgList.get(i);
			try {
				inputStream = new FileInputStream(new File(filePath));
				OSSClientUtil ossUtil = new OSSClientUtil();
				String suffix = filePath.substring(filePath.lastIndexOf("."));
				String name = System.nanoTime() + suffix;
				ossUtil.uploadFile2OSS(inputStream, Global.getReportDir(), name);
				this_workreportFiles.append(Global.getAliyunUrl() + "/" + Global.getReportDir() + name+",");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (inputStream != null)
						inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		//--- 上传下月图片
		String  next_uploadFolder = request.getSession().getServletContext().getRealPath("local_upload/workReport/"+System.nanoTime());
		new File(next_uploadFolder).mkdirs();
		List<String> next_imgList = new ArrayList<>();
		if(next_upload_files!=null && next_upload_files.length>0){
			for(int i=0;i<next_upload_files.length;i++){
				if(next_upload_files[i]==null || next_upload_files[i].getSize()==0)
					continue;
				String imageName = System.nanoTime()+next_upload_files[i].getOriginalFilename();
				String imageNewName = next_uploadFolder+"/"+imageName;
				next_imgList.add(imageNewName);
				try{
					next_upload_files[i].transferTo(new File(imageNewName));
				}catch (IllegalStateException | IOException e) {
					e.printStackTrace();
				}
			}
		}
		StringBuilder next_workreportFiles = new StringBuilder();
		InputStream next_inputStream = null;
		for(int i=0;i<next_imgList.size();i++) {
			String filePath = next_imgList.get(i);
			try {
				next_inputStream = new FileInputStream(new File(filePath));
				OSSClientUtil ossUtil = new OSSClientUtil();
				String suffix = filePath.substring(filePath.lastIndexOf("."));
				String name = System.nanoTime() + suffix;
				ossUtil.uploadFile2OSS(next_inputStream, Global.getReportDir(), name);
				next_workreportFiles.append(Global.getAliyunUrl() + "/" + Global.getReportDir() + name+",");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (next_inputStream != null)
						next_inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if(!StringUtils.isBlank(this_workreportFiles.toString()))
			workReport.setThisFiles(this_workreportFiles.toString().substring(0,this_workreportFiles.lastIndexOf(",")));
		if(!StringUtils.isBlank(next_workreportFiles.toString()))
			workReport.setNextFiles(next_workreportFiles.toString().substring(0,next_workreportFiles.lastIndexOf(",")));
*/


		workReportService.save(workReport);//保存
		addMessage(redirectAttributes, "保存工作报告成功");
		return "redirect:"+Global.getAdminPath()+"/work/report/workReport/outList";
	}
	
	/**
	 * 删除工作报告
	 */
	@RequiresPermissions("work:report:workReport:del")
	@RequestMapping(value = "delete")
	public String delete(WorkReport workReport, RedirectAttributes redirectAttributes) {
		workReportService.delete(workReport);
		addMessage(redirectAttributes, "删除工作报告成功");
		return "redirect:"+Global.getAdminPath()+"/work/report/workReport/list";
	}
	
	/**
	 * 批量删除工作报告
	 */
	@RequiresPermissions("work:report:workReport:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workReportService.delete(workReportService.get(id));
		}
		addMessage(redirectAttributes, "删除工作报告成功");
		return "redirect:"+Global.getAdminPath()+"/work/report/workReport/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("work:report:workReport:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkReport workReport, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工作报告"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkReport> page = workReportService.findPage(new Page<WorkReport>(request, response, -1), workReport);
    		new ExportExcel("工作报告", WorkReport.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出工作报告记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/work/report/workReport/?repage";
    }

	/**
	 * 导入Excel数据

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

	/**
	 * 工作
	 */

	@RequestMapping(value = {"reportlist"})
	public String reportlist(CalendarCountEntity calendarCountEntity, @RequestParam(value="flat",required = false)String flat, HttpServletRequest request, HttpServletResponse response, Model model) {
		String start=request.getParameter("start");
		User login_user = UserUtils.getUser();
		List<WorkReport> list=new ArrayList<>();
		if("1".equals(flat)){
			List manageCalendarDetailsList = workReportService.getReportUserList(start,calendarCountEntity);
			model.addAttribute("calendarCountEntity",calendarCountEntity);
			model.addAttribute("login_user",login_user);
			model.addAttribute("manageCalendarDetailsList", manageCalendarDetailsList);
			return "modules/oa/manageCalendarDetailsSelf";
		}else{
			List manageCalendarDetailsList = workReportService.getReportUserListAll(start,calendarCountEntity);
			model.addAttribute("login_user",login_user);
			model.addAttribute("calendarCountEntity",calendarCountEntity);
			model.addAttribute("manageCalendarDetailsList", manageCalendarDetailsList);
			return "modules/oa/manageCalendarDetailsAll";
		}
	}
}