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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
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.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
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.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 附件信息Controller
 * @author yangfan
 * @version 2017-10-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/workattachment")
public class WorkattachmentController extends BaseController {

	@Autowired
	private WorkattachmentService workattachmentService;
	
	@ModelAttribute
	public Workattachment get(@RequestParam(required=false) String id) {
		Workattachment entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workattachmentService.get(id);
		}
		if (entity == null){
			entity = new Workattachment();
		}
		return entity;
	}
	
	/**
	 * 附件信息列表页面
	 */
	@RequiresPermissions("sys:workattachment:list")
	@RequestMapping(value = {"list", ""})
	public String list(Workattachment workattachment, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Workattachment> page = workattachmentService.findPage(new Page<Workattachment>(request, response), workattachment); 
		model.addAttribute("page", page);
		return "modules/sys/workattachmentList";
	}

	/**
	 * 查看，增加，编辑附件信息表单页面
	 */
	@RequiresPermissions(value={"sys:workattachment:view","sys:workattachment:add","sys:workattachment:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Workattachment workattachment, Model model) {
		model.addAttribute("workattachment", workattachment);
		return "modules/sys/workattachmentForm";
	}

	/**
	 * 查看，增加，编辑附件信息表单页面
	 */
	@RequestMapping(value = "ddsc")
	public String ddsc(Workattachment workattachment, Model model) {
		return "modules/sys/ddsc";
	}
	/**
	 * 查看，增加，编辑附件信息表单页面
	 */
	@RequestMapping(value = "postUrl")
	public String postUrl(Workattachment workattachment, Model model) {
		return "modules/sys/post";
	}


	/**
	 * 查看，增加，编辑附件信息表单页面
	 */
	@RequestMapping(value = "doUpload")
	public String doUpload(Workattachment workattachment, Model model) {
		return "modules/sys/doUpload";
	}

	/**
	 * 查看，增加，编辑附件信息表单页面
	 */
	@RequestMapping(value = "jsDoUpload")
	public String jsDoUpload(Workattachment workattachment, Model model) {
		return "modules/sys/jsDoUpload";
	}

	/**
	 * 保存附件信息
	 */
	@RequiresPermissions(value={"sys:workattachment:add","sys:workattachment:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Workattachment workattachment, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workattachment)){
			return form(workattachment, model);
		}
		if(!workattachment.getIsNewRecord()){//编辑表单保存
			Workattachment t = workattachmentService.get(workattachment.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workattachment, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workattachmentService.save(t);//保存
		}else{//新增表单保存
			workattachmentService.save(workattachment);//保存
		}
		addMessage(redirectAttributes, "保存附件信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/workattachment/?repage";
	}

	/**
	 * 保存附件信息
	 */
	@RequestMapping(value = "/saveAttachment")
	@ResponseBody
	public Map<String,String> saveAttachment(Workattachment workattachment) throws Exception{
		Map<String,String> map = new HashMap<>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String[] type = workattachment.getAttachmentName().split("\\.");
			String url = workattachment.getUrl();
			workattachment.setType(type[type.length-1]);
			workattachment.setAttachmentUser(UserUtils.getUser().getId());
			workattachment.setCompanyId(UserUtils.getSelectCompany().getId());
			workattachment.setUrl(url);
			if(StringUtils.isNotBlank(workattachment.getAttachmentId())){
				workattachmentService.save(workattachment);//保存
			}
			map.put("status","Success");
			map.put("url",workattachment.getUrl().replace("%","%25")
					.replace("`","%60")
					.replace("}","%7D")
					.replace("#","%23")
					.replace("[","%5B")
					.replace("=","%3D"));
			map.put("attachmentName",workattachment.getAttachmentName());
			map.put("attachmentId",workattachment.getAttachmentId());
			map.put("type",workattachment.getType());
			map.put("createBy", UserUtils.getUser().getId());
			map.put("createByName", UserUtils.getUser().getName());
			map.put("createDate", sdf.format(new Date()));
			map.put("attachmentFlag", workattachment.getAttachmentFlag());
			map.put("id", workattachment.getId());
		}catch (Exception e){
			map.put("status","Fail");
		}
		return map;
	}

	/**
	 * 上传附件到阿里云

	 */
	@RequestMapping("/uploadFiletoAly")
	@ResponseBody
	public Map<String,String> uploadFiletoAly(MultipartHttpServletRequest multiRequest) {
		Map<String,String> map = new HashMap<>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Workattachment workattachment = workattachmentService.uploadFiletoAly(multiRequest);
			map.put("url",workattachment.getUrl());
			map.put("attachmentName",workattachment.getAttachmentName());
			map.put("attachmentId",workattachment.getAttachmentId());
			map.put("type",workattachment.getType());
			map.put("createBy", UserUtils.getUser().getId());
			map.put("createByName", UserUtils.getUser().getName());
			map.put("createDate", sdf.format(new Date()));
			map.put("attachmentFlag", workattachment.getAttachmentFlag());
			map.put("id", workattachment.getId());
			map.put("status","Success");
			logger.info("workattachment.getUrl()="+workattachment.getUrl());
		} catch (Exception e) {
			map.put("status","Fail");
		}
		return map;
	}

	/**
	 *  单个删除阿里云上的文件，同时更新相关对象的附件信息
	 *  阿里云文件地址http://gangwan-app.oss-cn-hangzhou.aliyuncs.com/attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 *  其中阿里云删除接口所需的参数 key 指的是 attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 * @return
	 */
	@RequestMapping("/deleteFileFromAliyun")
	@ResponseBody
	public HashMap<Object, Object> deleteFileFromAliyun(String id,String type,String url,Model model){
		if(StringUtils.isNotBlank(id)) {
			Workattachment workattachment = workattachmentService.get(id);
			workattachmentService.deleteFileFromAliyun(workattachment, workattachment == null ? url : workattachment.getUrl());
		}
		HashMap<Object, Object> map = Maps.newHashMap();
		map.put("str","success");
		return map;
	}
	
	/**
	 * 删除附件信息
	 */
	@RequiresPermissions("sys:workattachment:del")
	@RequestMapping(value = "delete")
	public String delete(Workattachment workattachment, RedirectAttributes redirectAttributes) {
		workattachmentService.delete(workattachment);
		addMessage(redirectAttributes, "删除附件信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/workattachment/?repage";
	}
	
	/**
	 * 批量删除附件信息
	 */
	@RequiresPermissions("sys:workattachment:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workattachmentService.delete(workattachmentService.get(id));
		}
		addMessage(redirectAttributes, "删除附件信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/workattachment/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("sys:workattachment:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Workattachment workattachment, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "附件信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Workattachment> page = workattachmentService.findPage(new Page<Workattachment>(request, response, -1), workattachment);
    		new ExportExcel("附件信息", Workattachment.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出附件信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/workattachment/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("sys:workattachment: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<Workattachment> list = ei.getDataList(Workattachment.class);
			for (Workattachment workattachment : list){
				try{
					workattachmentService.save(workattachment);
					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()+"/sys/workattachment/?repage";
    }

	/**
	 * 下载导入附件信息数据模板
	 */
	@RequiresPermissions("sys:workattachment:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "附件信息数据导入模板.xlsx";
    		List<Workattachment> list = Lists.newArrayList(); 
    		new ExportExcel("附件信息数据", Workattachment.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/workattachment/?repage";
    }
	
	
	

}