package com.lerx.handlers;

import java.io.IOException;
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.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lerx.annotation.Token;
import com.lerx.dao.iface.IAlbumArticleAttaDao;
import com.lerx.dao.iface.IAlbumArticleDao;
import com.lerx.dao.iface.IArticleAttaDao;
import com.lerx.dao.iface.IArticleDao;
import com.lerx.dao.iface.IUploadedFileDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.entities.AlbumArticleAtta;
import com.lerx.entities.ArticleAtta;
import com.lerx.entities.UploadedFile;
import com.lerx.login.util.LoginUtil;
import com.lerx.portal.obj.UploadArgs;
import com.lerx.portal.obj.UploadResultForCk5Editor;
import com.lerx.portal.obj.UploadResultForKindEditor;
import com.lerx.portal.obj.UploadResultForWangEditor;
import com.lerx.sys.obj.LayerUploadReturnData;
import com.lerx.sys.obj.LayerUploadedReturn;
import com.lerx.sys.util.FileUtil;
import com.lerx.sys.util.HttpUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.sys.util.SysUtil;
import com.lerx.v6.util.UploadUtil;

@RequestMapping("/action_file")
@Controller
public class FileHandler {

	private static final String LOGINPAGE = "jsp/user/login";

	@Autowired
	private ResourceBundleMessageSource messageSource;

	@Autowired
	private IUserDao userDaoImpl;

	@Autowired
	private IUploadedFileDao uploadedFileDaoImpl;

	@Autowired
	private IArticleDao articleDaoImpl;

	@Autowired
	private IArticleAttaDao articleAttaDaoImpl;

	@Autowired
	private IAlbumArticleDao albumArticleDaoImpl;

	@Autowired
	private IAlbumArticleAttaDao albumArticleAttaDaoImpl;

	/*
	 * p上传目标类型： 0门户文章 1专辑文章 tmpID
	 */
	@RequestMapping(value = "/uploadAtta/{p}", method = RequestMethod.POST)
	@ResponseBody
	@Token(ajax = true,csrf=true,contrast = true, log = true, loginOrAdmin = true, mark = "file--<upload>", failedPage = LOGINPAGE, msgKey = "fail.nologin")
	public long uploadAtta(@PathVariable(value = "p", required = true) Long p,
			@RequestParam(value = "file", required = true) MultipartFile file,
			@RequestParam(value = "targetFile", required = false) String targetFile,
			@RequestParam(value = "title", required = false) String title,
			@RequestParam(value = "intact", required = false) Boolean intact,
			@RequestParam(value = "cw", required = false) Integer cw,
			@RequestParam(value = "ch", required = false) Integer ch,
			@RequestParam(value = "aid", required = true) long aid,
			@RequestParam(value = "tid", required = false) long tid, HttpServletRequest request, HttpSession session)
			throws IOException {
		String fileExtAllowed = messageSource.getMessage("file.upload.ext.allowed", null, "jpg,jpeg,png,gif", null);
		fileExtAllowed = fileExtAllowed.toLowerCase();

		String ext = FileUtil.getFileExt(file.getOriginalFilename());
		if (!FileUtil.extTypeChk(ext, fileExtAllowed)) {
			return -415;
		}

		if (intact == null) {
			intact = false;
		}
		if (cw == null) {
			cw = 0;
		}
		if (ch == null) {
			ch = 0;
		}
		long uid = LoginUtil.uid(messageSource, request);

		// System.out.println("uid:"+uid);
		targetFile = SysUtil.uploadTarget(messageSource, file.getOriginalFilename(), targetFile, uid);
		if (intact) {
			cw = 0;
			ch = 0;
		} else {
			if (cw == 0) {
				cw = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.width", null, "0", null));
			}
			if (ch == 0) {
				ch = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.height", null, "0", null));
			}
		}
		if (title.trim().equals("")) {
			title = null;
		} else {
			title = StringUtil.escapeUrl(title, 0);
		}
		UploadArgs ua = new UploadArgs();
		ua.setCh(ch);
		ua.setCw(cw);
		ua.setFile(file);
		ua.setIntact(intact);
		ua.setMessageSource(messageSource);
		ua.setRequest(request);
		ua.setSession(session);
		ua.setTargetFile(targetFile);
		ua.setUploadedFileDaoImpl(uploadedFileDaoImpl);
		ua.setUserDaoImpl(userDaoImpl);
		ua.setUid(uid);
		UploadedFile uf = UploadUtil.upload(ua);
		if (uf == null) {
			return -1;
		}
		if (p == 0) {
			ArticleAtta aa = new ArticleAtta();
			if (aid > 0L) {
				aa.setArticle(articleDaoImpl.findByID(aid));
			}
			aa.setTmpID(tid);
			aa.setUf(uf);
			aa.setTitle(title);

			return articleAttaDaoImpl.add(aa);
		} else {
			AlbumArticleAtta aa = new AlbumArticleAtta();
			if (aid > 0L) {
				aa.setArticle(albumArticleDaoImpl.findByID(aid));
			}
			aa.setTmpID(tid);
			aa.setUf(uf);
			aa.setTitle(title);
			long r = albumArticleAttaDaoImpl.add(aa);
			return r;
		}

		/*
		 * if (aa!=null) { return aa.getId(); }else { return -1; }
		 */

	}

	@RequestMapping(value = "/uploadForWangEditor", method = RequestMethod.POST)
	@ResponseBody
	@Token(ajax = true,csrf=true,contrast = true, log = true, loginOrAdmin = true, mark = "file--<upload>", failedPage = LOGINPAGE, msgKey = "fail.nologin")
	public UploadResultForWangEditor uploadForWangEditor(
			@RequestParam(value = "files", required = true) MultipartFile[] files,
			@RequestParam(value = "intact", required = false) Boolean intact,
			@RequestParam(value = "cw", required = false) Integer cw,
			@RequestParam(value = "ch", required = false) Integer ch, HttpServletRequest request, HttpSession session)
			throws IOException {
		UploadResultForWangEditor urfwe = new UploadResultForWangEditor();
		String fileExtAllowed = messageSource.getMessage("file.img.exts", null, "jpg,jpeg,png,gif", null);
		fileExtAllowed = fileExtAllowed.toLowerCase();

		if (files.length < 1) {
			urfwe.setErrno(-1);
			return urfwe;
		}

		if (intact == null) {
			intact = false;
		}
		if (cw == null) {
			cw = 0;
		}
		if (ch == null) {
			ch = 0;
		}

		long uid = LoginUtil.uid(messageSource, request);

		if (intact) {
			cw = 0;
			ch = 0;
		} else {
			if (cw == 0) {
				cw = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.width", null, "0", null));
			}
			if (ch == 0) {
				ch = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.height", null, "0", null));
			}
		}

		String targetFile;
		List<String> data = new ArrayList<String>();
		for (int i = 0; i < files.length; i++) {
			MultipartFile file = files[i];
			String ext = FileUtil.getFileExt(file.getOriginalFilename());
			if (!FileUtil.extTypeChk(ext, fileExtAllowed)) {
				continue;
			}

			targetFile = null;
			targetFile = SysUtil.uploadTarget(messageSource, file.getOriginalFilename(), targetFile, uid);

			UploadArgs ua = new UploadArgs();
			ua.setCh(ch);
			ua.setCw(cw);
			ua.setFile(file);
			ua.setIntact(intact);
			ua.setMessageSource(messageSource);
			ua.setRequest(request);
			ua.setSession(session);
			ua.setTargetFile(targetFile);
			ua.setUploadedFileDaoImpl(uploadedFileDaoImpl);
			ua.setUserDaoImpl(userDaoImpl);
			ua.setUid(uid);

			UploadedFile ue = UploadUtil.upload(ua);
			data.add(HttpUtil.currRequest().getContextPath() + "/" + ue.getUrl());

		}

		urfwe.setData(data);
		urfwe.setErrno(0);
		return urfwe;

	}

	@RequestMapping(value = "/uploadForKindEditor", method = RequestMethod.POST)
	@ResponseBody
	public UploadResultForKindEditor uploadForKindEditor(
			@RequestParam(value = "imgFile", required = true) MultipartFile imgFile,
			@RequestParam(value = "intact", required = false) Boolean intact,
			@RequestParam(value = "cw", required = false) Integer cw,
			@RequestParam(value = "ch", required = false) Integer ch, HttpServletRequest request, HttpSession session)
			throws IOException {
		String fileExtAllowed = messageSource.getMessage("file.upload.ext.allowed", null, "jpg,jpeg,png,gif", null);
		fileExtAllowed = fileExtAllowed.toLowerCase();
		UploadResultForKindEditor urfke = new UploadResultForKindEditor();
		String ext = FileUtil.getFileExt(imgFile.getOriginalFilename());
		if (!FileUtil.imgFileCheck(imgFile.getOriginalFilename(),"jpg,jpeg,png,gif")) {
			intact=true;
		}
		if (!FileUtil.extTypeChk(ext, fileExtAllowed)) {

			urfke.setError(1);
			urfke.setMessage(
					messageSource.getMessage("fail.not.allowed.file.ext", null, "File type is not allowed!", null));
			return urfke;
		}
		if (intact == null) {
			intact = false;
		}
		if (cw == null) {
			cw = 0;
		}
		if (ch == null) {
			ch = 0;
		}

		long uid = LoginUtil.uid(messageSource, request);

		if (intact) {
			cw = 0;
			ch = 0;
		} else {
			if (cw == 0) {
				cw = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.width", null, "0", null));
			}
			if (ch == 0) {
				ch = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.height", null, "0", null));
			}
		}

		String targetFile;
		MultipartFile file = imgFile;
		targetFile = null;
		targetFile = SysUtil.uploadTarget(messageSource, file.getOriginalFilename(), targetFile, uid);

		UploadArgs ua = new UploadArgs();
		ua.setCh(ch);
		ua.setCw(cw);
		ua.setFile(file);
		ua.setIntact(intact);
		ua.setMessageSource(messageSource);
		ua.setRequest(request);
		ua.setSession(session);
		ua.setTargetFile(targetFile);
		ua.setUploadedFileDaoImpl(uploadedFileDaoImpl);
		ua.setUserDaoImpl(userDaoImpl);
		ua.setUid(uid);

		UploadedFile ue = UploadUtil.upload(ua);
		String url = HttpUtil.currRequest().getContextPath() + "/" + ue.getUrl();

		urfke.setError(0);
		urfke.setUrl(url);
		return urfke;

	}

	@RequestMapping(value = "/uploadForUEditor", method = RequestMethod.POST)
	@ResponseBody
	@Token(ajax = true,csrf=true,contrast = true, log = true, loginOrAdmin = true, mark = "file--<upload>", failedPage = LOGINPAGE, msgKey = "fail.nologin")
	public Map<String, Object> uploadForUEditor(@RequestParam(value = "upfile", required = true) MultipartFile imgFile,
			@RequestParam(value = "intact", required = false) Boolean intact,
			@RequestParam(value = "cw", required = false) Integer cw,
			@RequestParam(value = "ch", required = false) Integer ch, HttpServletRequest request, HttpSession session)
			throws IOException {
		String fileExtAllowed;
		if (intact == null) {
			intact = false;
		}
		if (intact){
			fileExtAllowed= messageSource.getMessage("file.upload.ext.allowed", null, "jpg,gif,jpeg,png,zip,rar,doc,docx,xls,xlsx,ppt,txt,mp3", null);
		}else{
			fileExtAllowed= messageSource.getMessage("file.img.exts", null, "jpg,jpeg,png,gif", null);
		}
		
		fileExtAllowed = fileExtAllowed.toLowerCase();
		String ext = FileUtil.getFileExt(imgFile.getOriginalFilename());
		Map<String, Object> params = new HashMap<String, Object>();
		if (!FileUtil.extTypeChk(ext, fileExtAllowed)) {
			params.put("state", messageSource.getMessage("fail.upload.ext.type", null, "The type of file uploaded is not within the scope of permission!", null));
			return params;
		}
		
		if (cw == null) {
			cw = 0;
		}
		if (ch == null) {
			ch = 0;
		}
		long uid = LoginUtil.uid(messageSource, request);

		if (intact) {
			cw = 0;
			ch = 0;
		} else {
			if (cw == 0) {
				cw = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.width", null, "0", null));
			}
			if (ch == 0) {
				ch = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.height", null, "0", null));
			}
		}
		String targetFile;
		MultipartFile file = imgFile;
		targetFile = null;
		targetFile = SysUtil.uploadTarget(messageSource, file.getOriginalFilename(), targetFile, uid);
		UploadArgs ua = new UploadArgs();
		ua.setCh(ch);
		ua.setCw(cw);
		ua.setFile(file);
		ua.setIntact(intact);
		ua.setMessageSource(messageSource);
		ua.setRequest(request);
		ua.setSession(session);
		ua.setTargetFile(targetFile);
		ua.setUploadedFileDaoImpl(uploadedFileDaoImpl);
		ua.setUserDaoImpl(userDaoImpl);
		ua.setUid(uid);
		UploadedFile ue = UploadUtil.upload(ua);
		String url = HttpUtil.currRequest().getContextPath() + "/" + ue.getUrl();

		params.put("state", "SUCCESS");
		params.put("url", url);
		params.put("size", file.getSize());
		params.put("original", file.getName());
		params.put("type", file.getContentType());
		params.put("filename", file.getOriginalFilename());
		return params;

	}
	
	
	
	@RequestMapping(value = "/uploadForCKEditor", method = RequestMethod.POST)
	@ResponseBody
	@Token(ajax = true,csrf=true,contrast = true, log = true, loginOrAdmin = true, mark = "file--<upload>", failedPage = LOGINPAGE, msgKey = "fail.nologin")
	public String uploadForCKEditor(
			@RequestParam(value = "upload", required = true) MultipartFile upload,
			@RequestParam(value = "intact", required = false) Boolean intact,
			@RequestParam(value = "cw", required = false) Integer cw,
			@RequestParam(value = "ch", required = false) Integer ch, HttpServletRequest request, HttpSession session)
			throws IOException {
		
		String fileExtAllowed = messageSource.getMessage("file.img.exts", null, "jpg,jpeg,png,gif", null);
		fileExtAllowed = fileExtAllowed.toLowerCase();
		

		if (intact == null) {
			intact = false;
		}
		if (cw == null) {
			cw = 0;
		}
		if (ch == null) {
			ch = 0;
		}

		long uid = LoginUtil.uid(messageSource, request);
		if (intact) {
			cw = 0;
			ch = 0;
		} else {
			if (cw == 0) {
				cw = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.width", null, "0", null));
			}
			if (ch == 0) {
				ch = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.height", null, "0", null));
			}
		}
		

		String targetFile;
		String url = null;
		
		String result="[";
		MultipartFile file= upload;
		String ext = FileUtil.getFileExt(file.getOriginalFilename());
		if (!FileUtil.extTypeChk(ext, fileExtAllowed)) {
			return "";
		}

		targetFile = SysUtil.uploadTarget(messageSource, file.getOriginalFilename(), "md5", uid);
		UploadArgs ua = new UploadArgs();
		ua.setCh(ch);
		ua.setCw(cw);
		ua.setFile(file);
		ua.setIntact(intact);
		ua.setMessageSource(messageSource);
		ua.setRequest(request);
		ua.setSession(session);
		ua.setTargetFile(targetFile);
		ua.setUploadedFileDaoImpl(uploadedFileDaoImpl);
		ua.setUserDaoImpl(userDaoImpl);
		ua.setUid(uid);
		UploadedFile ue = UploadUtil.upload(ua);
		url=ue.getUrl();
		url=HttpUtil.currRequest().getContextPath() + "/" + url;
		UploadResultForCk5Editor ur=new UploadResultForCk5Editor();
		ur.setUploaded(true);
		ur.setUrl(url);
		result="{\"uploaded\":1,\"url\":\""+url+"\"}";

		return result;

	}
	

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	@Token(ajax = false,contrast = true,csrf = true, log = true, loginOrAdmin = true, mark = "file--<upload>", failedPage = LOGINPAGE, msgKey = "fail.nologin")
	public LayerUploadedReturn upload(@RequestParam(value = "file", required = true) MultipartFile file,
			@RequestParam(value = "targetFile", required = false) String targetFile,
			@RequestParam(value = "title", required = false) String title,
			@RequestParam(value = "intact", required = false) Boolean intact,
			@RequestParam(value = "cw", required = false) Integer cw,
			@RequestParam(value = "ch", required = false) Integer ch, HttpServletRequest request, HttpSession session)
			throws IOException {
		String fileExtAllowed;
		if (intact == null) {
			intact = false;
		}
		if (intact){
			fileExtAllowed= messageSource.getMessage("file.upload.ext.allowed", null, "jpg,gif,jpeg,png,zip,rar,doc,docx,xls,xlsx,ppt,txt,mp3", null);
		}else{
			fileExtAllowed= messageSource.getMessage("file.img.exts", null, "jpg,jpeg,png,gif", null);
		}
		
		fileExtAllowed = fileExtAllowed.toLowerCase();
		
		LayerUploadedReturn lur = new LayerUploadedReturn();
		String ext = FileUtil.getFileExt(file.getOriginalFilename());
		if (!FileUtil.extTypeChk(ext, fileExtAllowed)) {
			lur.setCode(-415);
			lur.setMsg(messageSource.getMessage("fail.not.allowed.file.ext", null, "File type is not allowed!", null));
			return lur;
		}

		if (cw == null) {
			cw = 0;
		}
		if (ch == null) {
			ch = 0;
		}
		long uid = LoginUtil.uid(messageSource, request);

		targetFile = SysUtil.uploadTarget(messageSource, file.getOriginalFilename(), targetFile, uid);
		if (intact) {
			cw = 0;
			ch = 0;
		} else {
			if (cw == 0) {
				cw = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.width", null, "0", null));
			}
			if (ch == 0) {
				ch = Integer.valueOf(messageSource.getMessage("img.resize.cut.default.height", null, "0", null));
			}
		}

		UploadArgs ua = new UploadArgs();
		ua.setCh(ch);
		ua.setCw(cw);
		ua.setFile(file);
		ua.setIntact(intact);
		ua.setMessageSource(messageSource);
		ua.setRequest(request);
		ua.setSession(session);
		ua.setTargetFile(targetFile);
		ua.setTitle(title);
		ua.setUploadedFileDaoImpl(uploadedFileDaoImpl);
		ua.setUserDaoImpl(userDaoImpl);
		ua.setUid(uid);

		UploadedFile ue = UploadUtil.upload(ua);

		LayerUploadReturnData rd = new LayerUploadReturnData();

		rd.setSrc(HttpUtil.currRequest().getContextPath() + "/" + ue.getUrl());
		lur.setData(rd);
		lur.setCode(0);
		lur.setMsg(ua.getMessageSource().getMessage("success.upload", null, "Upload success!", null));

		return lur;

	}

	/*
	 * private static UploadedFile upload(UploadArgs ua) throws IOException {
	 * FileInf fi; if (ua.getCw()==0 && ua.getCh()==0){ fi =
	 * FileUtil.upload(ua.getFile(), ua.getTargetFile()); }else{ fi =
	 * FileUtil.upload(ua.getFile(), ua.getTargetFile(), ua.getCw(), ua.getCh()); }
	 * String filenameNoExt = fi.getNameNoExt(); fi.setNameNoExt(filenameNoExt);
	 * UploadedFile fu = UploadUtil.coverFromFi(fi);
	 * fu.setUser(ua.getUserDaoImpl().findByID(ua.getUid()));
	 * fu.setRemark(ua.getTitle()); UploadedFile existu =
	 * ua.getUploadedFileDaoImpl().findByMD5(fu.getMd5(), fu.getId()); UploadedFile
	 * ue; if (existu != null) { FileUtil.delete(fu.getFullPath()); ue = existu; }
	 * else { ue = fu; ua.getUploadedFileDaoImpl().add(ue); }
	 * 
	 * return ue; }
	 */

}
