package com.bcxin.ars.rest;

import com.abcxin.smart.validator.annotation.DataSyncOutAnnotation;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.exception.ArsException;
import com.bcxin.ars.model.Nation;
import com.bcxin.ars.model.Native;
import com.bcxin.ars.model.User;
import com.bcxin.ars.model.task.TaskCatalog;
import com.bcxin.ars.model.task.TaskLevel;
import com.bcxin.ars.model.task.TaskStatus;
import com.bcxin.ars.model.task.TaskType;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.service.SecurityPersonService;
import com.bcxin.ars.service.util.ConfigUtils;
import com.bcxin.ars.service.util.DataSyncUtil;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.DateUtil;
import com.bcxin.ars.util.IdNumUtil;
import com.bcxin.ars.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/***
 * 控制层基类
 * @author  subh
 */
@Controller
@RequestMapping("/")
public class BaseController {
	/***
	 * 日志
	 */
	public static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	@Value("${base-folder}")
	private String baseFolder;
	
	@Value("${upload-folder}")
	private String uploadFolder;

    @Value("${uploadInToOutFolder}")
    private String uploadInToOutFolder;

    @Value("${uploadInToOutAuthFolder}")
    private String uploadInToOutAuthFolder;
    @Value("${temp-folder}")
	private String tempFolder;

	@Value("${pdf-folder}")
	private String pdfFolder;

	@Value("${personImg-folder}")
	private String personImg;
    @Autowired
    private ConfigUtils configUtils;

    //北京ftp临时目录
    @Value("${ftpServerTemp}")
    private String ftpServerTemp;
	@Autowired
	private ArsRestUtil arsRestUtil;
	
	@Autowired
	private SecurityPersonService personService;
	/***
	 * 根据url获取SaaS的图片信息
	 * @param url 图片地址
	 * @return 百保盾路径
	 */
	public String getPhotoPath(String url) {
		//定义输出流对象，用于生成文件
		FileOutputStream outStream = null;
		//定义输入流对象，用于获取文件流
		InputStream inStream = null;
		//返回对易用
		StringBuffer result = new StringBuffer("");
		try {
			//多张照片用，号隔开
			String[] urls = url.split(Constants.COMMA);
			for (String urlStr: urls){
				//获取图片地址信息
				URL imgPath = new URL(urlStr);
				//打开链接
				HttpURLConnection conn = (HttpURLConnection)imgPath.openConnection();
				//设置请求方式为"GET"
				conn.setRequestMethod("GET");
				//超时响应时间为5秒
				conn.setConnectTimeout(5 * 1000);
				//通过输入流获取图片数据
				inStream = conn.getInputStream();
				//得到图片的二进制数据，以二进制封装得到数据，具有通用性
				byte[] data = readInputStream(inStream);
				//日期
				Date now = new Date();
				//对图片地址以逗号，如 XXXX.png 分割成数据，array[0]=XXXX,array[1]=png
				String[] fileTypes = urlStr.split("\\.");
				//获取文件类型
				String materialFileType = fileTypes[fileTypes.length-1]; //文件类型
				Random random = new Random();
				int rannum = (int) (random.nextDouble() * (99 - 10 + 1)) + 100;// 获取5位随机数
				//生成新的文件名，格式 时间戳+文件类型
				StringBuffer fileName =new StringBuffer();
				fileName.append(now.getTime());
				fileName.append(rannum).append("."+ materialFileType);
				//获取当前日期
				String dirDate = DateUtil.systemDate.format(now);
				//定义目录file对象，用于判断文件夹是否存在
				File dir = new File(uploadFolder + dirDate);
				//判断文件是否存在，如不存在则创建
				if(!dir.exists()) {
					dir.mkdirs();
				}
				//文件的完整路径
				String key = "upload/" + dirDate + "/" + fileName;
				//生成请求地址 多个地址用&&隔开
				if(StringUtil.isEmpty(result.toString())) {
					result.append("getResource.do?path=" + key);
				}else{
					result.append("&&getResource.do?path=" + key);
				}
				//操作系统真实路径
				String targetPath = uploadFolder + dirDate + "/" + fileName;
				//new一个文件对象用来保存图片，默认保存当前工程根目录
				File imageFile = new File(targetPath);
				//创建输出流
				outStream = new FileOutputStream(imageFile);
				//写入文件数据
				outStream.write(data);
				//刷新输出流
				outStream.flush();
				logger.info("本地文件上传成功!");
			}

		} catch(Exception e) {
			result.append(url);
			logger.error(e.getMessage(), e);
		} finally {
			try {
				//关闭输入流
				if (inStream != null) {
					inStream.close();
				}
				//关闭输出流
				if (outStream != null) {
					outStream.close();
				}
			}catch (Exception e){
				logger.error(e.getMessage(), e);
			}
		}
		return result.toString();
	}
	/****
	 * 读取输入流信息
	 * @param inStream 输入流对接
	 * @return 文件byte
	 * @throws Exception 异常信息
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		//创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		//每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		//使用一个输入流从buffer里把数据读取出来
		while( (len=inStream.read(buffer)) != -1 ){
			//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
			outStream.write(buffer, 0, len);
		}
		//关闭输入流
		inStream.close();
		//把outStream里的数据写入内存
		return outStream.toByteArray();
	}
	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	@RequestMapping("uploadFile")
	public @ResponseBody AjaxResult uploadFile(MultipartFile file) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Date now = new Date();
			String[] fileTypes = file.getOriginalFilename().split("\\.");
			String materialFileType = fileTypes[fileTypes.length-1]; //文件类型
			/***  上传的文件类型可能小写、可能大写、可能大小混合 by llc 2018-08-21 ***/
			String fileType = "ZIP,RAR,PDF,TXT,XML,DOC,GIF,PNG,BMP,JPEG,JPG,DOCX,XLS,XLSX,PPT,PPTX";
//			判断是否为允许上传的文件类型
			if ( !Arrays.<String> asList(fileType.split(",")).contains(materialFileType.toUpperCase()))
			{
				result.setSuccessful(false);
				result.setMsg("文件格式不对，重新上传！！");
				return result;
			}
			String fileName = now.getTime() +"."+ materialFileType;
			String dirDate = DateUtil.systemDate.format(now);
			File dir = new File(uploadFolder + dirDate);
			if(!dir.exists()) {
				dir.mkdirs();
			}
			String key = "upload/" + dirDate + "/" + fileName;
			String url = "getResource.do?path=" + key;
			String targetPath = uploadFolder + dirDate + "/" + fileName;
			File targetFile = new File(targetPath);
			logger.info("执行本地文件上传..." + targetFile);
			file.transferTo(targetFile);
			Map<String,String> map = new HashMap<String, String>();
			map.put("key", key);
			map.put("url", url);
			logger.info("本地文件上传成功!");
			result.setSuccessful(true);
			result.setData(map);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
    @Autowired
    private DataSyncUtil dataSyncUtil;
    /**
     * 上传文件(用于同步)
     * @param file
     * @return
     */
    @RequestMapping("uploadFileGxToBj")
    public @ResponseBody AjaxResult uploadFileGxToBj(MultipartFile file) throws Exception {
        AjaxResult result = new AjaxResult();
        try {
            Date now = new Date();
            String[] fileTypes = file.getOriginalFilename().split("\\.");
            String materialFileType = fileTypes[fileTypes.length-1]; //文件类型
            /***  上传的文件类型可能小写、可能大写、可能大小混合 by llc 2018-08-21 ***/
            String fileType = "ZIP,RAR,PDF,TXT,XML,DOC,GIF,PNG,BMP,JPEG,JPG,DOCX,XLS,XLSX,PPT,PPTX";
//			判断是否为允许上传的文件类型
            if ( !Arrays.<String> asList(fileType.split(",")).contains(materialFileType.toUpperCase()))
            {
                result.setSuccessful(false);
                result.setMsg("文件格式不对，重新上传！！");
                return result;
            }
            String fileName = file.getOriginalFilename();
            String dirDate = DateUtil.systemDate.format(now);
            File dir = new File(uploadInToOutFolder + dirDate);
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String key = "uploadInToOut/" + dirDate + "/" + fileName;
            String url = "getResource.do?path=" + key;
            String targetPath = uploadInToOutFolder + dirDate + "/" + fileName;
            File targetFile = new File(targetPath);
            logger.info("执行本地文件上传..." + targetFile);
            file.transferTo(targetFile);
            Map<String,String> map = new HashMap<String, String>();
            map.put("key", key);
            map.put("url", url);
            logger.info("本地文件上传成功!");
            //读取文件
            new Thread(()->{
                try {
                    dataSyncUtil.readDSFile(DataSyncOutAnnotation.class,targetFile);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }).start();
            result.setSuccessful(true);
            result.setData(map);
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }
    /**
     * 上传文件(用于同步)
     * @param file
     * @return
     */
    @RequestMapping("uploadFileBjToGx")
    public @ResponseBody AjaxResult uploadFileBjToGx(MultipartFile file) throws Exception {
        AjaxResult result = new AjaxResult();
        try {
            Date now = new Date();
            String[] fileTypes = file.getOriginalFilename().split("\\.");
            String materialFileType = fileTypes[fileTypes.length-1]; //文件类型
            /***  上传的文件类型可能小写、可能大写、可能大小混合 by llc 2018-08-21 ***/
            String fileType = "ZIP,RAR,PDF,TXT,XML,DOC,GIF,PNG,BMP,JPEG,JPG,DOCX,XLS,XLSX,PPT,PPTX";
//			判断是否为允许上传的文件类型
            if ( !Arrays.<String> asList(fileType.split(",")).contains(materialFileType.toUpperCase()))
            {
                result.setSuccessful(false);
                result.setMsg("文件格式不对，重新上传！！");
                return result;
            }
            String fileName = file.getOriginalFilename();
            String dirDate = DateUtil.systemDate.format(now);
            File dir = new File(uploadInToOutFolder + dirDate);
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String key = "uploadInToOut/" + dirDate + "/" + fileName;
            String url = "getResource.do?path=" + key;
            String targetPath = uploadInToOutFolder + dirDate + "/" + fileName;
            File targetFile = new File(targetPath);
            logger.info("执行本地文件上传..." + targetFile);
            file.transferTo(targetFile);
            Map<String,String> map = new HashMap<String, String>();
            map.put("key", key);
            map.put("url", url);
            logger.info("本地文件上传成功!");
            result.setSuccessful(true);
            result.setData(map);
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /**
     * 上传文件认证(用于同步)
     * @param file
     * @return
     */
    @RequestMapping("uploadFileBjToAuthGx")
    public @ResponseBody AjaxResult uploadFileBjToAuthGx(MultipartFile file) throws Exception {
        AjaxResult result = new AjaxResult();
        try {
            Date now = new Date();
            String[] fileTypes = file.getOriginalFilename().split("\\.");
            String materialFileType = fileTypes[fileTypes.length-1]; //文件类型
            /***  上传的文件类型可能小写、可能大写、可能大小混合 by llc 2018-08-21 ***/
            String fileType = "ZIP,RAR,PDF,TXT,XML,DOC,GIF,PNG,BMP,JPEG,JPG,DOCX,XLS,XLSX,PPT,PPTX";
//			判断是否为允许上传的文件类型
            if ( !Arrays.<String> asList(fileType.split(",")).contains(materialFileType.toUpperCase()))
            {
                result.setSuccessful(false);
                result.setMsg("文件格式不对，重新上传！！");
                return result;
            }
            String fileName = file.getOriginalFilename();
            String dirDate = DateUtil.systemDate.format(now);
            File dir = new File(uploadInToOutAuthFolder + dirDate);
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String key = "uploadInToOutAuth/" + dirDate + "/" + fileName;
            String url = "getResource.do?path=" + key;
            String targetPath = uploadInToOutAuthFolder + dirDate + "/" + fileName;
            File targetFile = new File(targetPath);
            logger.info("执行本地文件上传..." + targetFile);
            file.transferTo(targetFile);
            Map<String,String> map = new HashMap<String, String>();
            map.put("key", key);
            map.put("url", url);
            logger.info("本地文件上传成功!");
            result.setSuccessful(true);
            result.setData(map);
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

    /****
	 * 判断字符串是否为日期格式
	 * @param str
	 * @return
	 */
	public static boolean isValidDate(String str) {
		boolean convertSuccess=true;
		// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess=false;
		}
		return convertSuccess;

	}

	public static void main(String[] args) throws Exception{
		/*String path ="upload/2018-01-21/121.jpg";
		//判断是否为三段式，不是三段式则有问题路径
		String[] paths =  path.split("/");
		if(paths.length!=3){
			throw new Exception("系统错误！！！");
		}else{
			//判断第二段是否为日期
			if(!isValidDate(paths[1])) {
				throw new Exception("系统错误！！！");
			}
			String fileType = paths[2];
			String[] temp =fileType.split("\\.");
			if(temp.length!=2){
				throw new Exception("系统错误！！！");
			}
			//文件名是否为时间戳
			String fileName = fileType.split("\\.")[0]; //文件类型
			if(!timeStampDate(fileName)){
				throw new Exception("系统错误！！！");
			}
			//文件类型判断
			if(!StringFilter(fileType)){
				throw new Exception("系统错误！！！");
			}
		}
		System.out.println("d1");*/
		String materialFileType = "doc";
		//允许上传的文件类型
		String fileType = "zip,rar,pdf,txt,xml,doc,gif,png,bmp,jpeg,jpg,docx,xls,xlsx,ppt,pptx";
		//判断是否为允许上传的文件类型
		if ( !Arrays.<String> asList(fileType.split(",")).contains(materialFileType))
		{
			throw new Exception("系统错误！！！");
		}
		System.out.println("成功");

	}
	/***
	 * 过滤非法字符
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public   static   boolean StringFilter(String   str)   throws PatternSyntaxException {
		boolean resulst = true;
		String regEx = "[ `~!@#$%^&*()+=|{}':;',\\[\\]<>?~！@#￥%……&*（）—+|{}【】‘；：”“’。，、？]|\n|\r|\t";
		//不允许..
		if(str.indexOf("..")>0){
			resulst =false;
		}
		//非法字符
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);

		if(m.find()){
			resulst = false;
		}
		return  resulst;
	}
	/***
	 * 时间戳转日期类型
	 * @param seconds
	 * @return
	 */
	public static boolean timeStampDate(String seconds) {
		boolean convertSuccess=true;
		try {
			if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
				return false;
			}
			String format="yyyy-MM-dd";
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			sdf.format(new Date(Long.valueOf(seconds+"000")));
		} catch (Exception e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess=false;
		}
		return convertSuccess;
	}
	/**
	 * 下载文件
	 * @param path
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "getResource")
	public void getResource(String path, HttpServletResponse response) throws Exception {
		File file = null;
		if(path.startsWith("upload")) {
			file = new File(baseFolder + path);
		} else if(path.startsWith("temp")) {
			file = new File(baseFolder + path);
		}  else if(path.startsWith("pdf")) {
			file = new File(baseFolder + path);
		}else if(path.startsWith("sysAttachment")) {
			file = new File(baseFolder + path);
		}else if(path.startsWith("approveAttachment")) {
			file = new File(baseFolder + path);
		}else if(path.startsWith("personImg")) {
			file = new File(baseFolder + path);
		}else if(path.startsWith("ftp")) {
			file = new File(baseFolder + path);
		}else{
			throw new Exception("系统错误！！！");
		}



		//判断是否为三段式，不是三段式则有问题路径
		String[] paths =  path.split("/");
		if(paths.length!=3){
			throw new Exception("系统错误！！！");
		}else{
			//判断第二段是否为日期
			if(!isValidDate(paths[1])) {
				throw new Exception("系统错误！！！");
			}
			String fileType = paths[2];
			String[] temp =fileType.split("\\.");
			if(temp.length!=2){
				throw new Exception("系统错误！！！");
			}
			//文件名是否为时间戳
			/*String fileName = fileType.split("\\.")[0]; //文件类型
			/*if(!timeStampDate(fileName)){
				throw new Exception("系统错误！！！");
			}*/
			//文件类型判断
			if(!StringFilter(fileType)){
				throw new Exception("系统错误！！！");
			}
		}

		if(file != null) {
			ServletOutputStream out = response.getOutputStream();
			String fileName = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");
			response.addHeader("Content-Disposition","attachment;filename=" + fileName);
			InputStream is = new FileInputStream(file);
			int read = 0;
			byte[] buffer = new byte[8192];
			while ((read = is.read(buffer)) != -1) {
				out.write(buffer, 0, read);
			}
			is.close();
			out.flush();
			out.close();
		}
	}

    /**
	 * 获取民族列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getNation")
	public @ResponseBody AjaxResult getNation(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<Nation> nationList = (List<Nation>) request.getSession().getServletContext().getAttribute(Constants.NATION_LIST);
			result.setSuccessful(true);
			result.setData(nationList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取指定代号下的省市县
	 * @param code 默认0表示获取所有省数据
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getNative/{code}")
	public @ResponseBody AjaxResult getNative(@PathVariable("code")Long code, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Map<Long, List<Native>> nativeMap = (Map<Long, List<Native>>) request.getSession().getServletContext().getAttribute(Constants.NATIVE_MAP);
			List<Native> data = nativeMap.get(code);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据身份证号获取籍贯
	 * @param idNum 身份证
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getNativeByIdNum/{idNum}")
	public @ResponseBody AjaxResult getNativeByIdNum(@PathVariable("idNum")String idNum, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Map<Long, Native> nativeData = (Map<Long, Native>) request.getSession().getServletContext().getAttribute(Constants.NATIVE_DATA);
			if(idNum.length() > 10) {
				idNum = IdNumUtil.getNativeCodeByIdNum(idNum,4);
				Long id = Long.valueOf(idNum);
				Native area = nativeData.get(id);
				if(area != null) {
					Native city = area.getParent();
					if(city != null) {
						city.getParent();
					}
					result.setSuccessful(true);
					result.setData(area);
				} else {
					result.setSuccessful(false);
					result.setMsg("未找到省市区");
				}
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取当前区域对象
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getCurrentNative")
	public @ResponseBody AjaxResult getCurrentNative(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Long currentNativeCode = Long.valueOf(request.getServletContext().getAttribute(Constants.CURRENT_NATIVE).toString());
			Map<Long, Native> nativeData = (Map<Long, Native>) request.getServletContext().getAttribute(Constants.NATIVE_DATA);
			Native na = nativeData.get(currentNativeCode);
			Map<Long, List<Native>> nativeMap = (Map<Long, List<Native>>) request.getServletContext().getAttribute(Constants.NATIVE_MAP);
			List<Native> nativeList = nativeMap.get(currentNativeCode);
			na.setChildren(nativeList);
			result.setSuccessful(true);
			result.setData(na);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务等级
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskLevel")
	public @ResponseBody AjaxResult getTaskLevel(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<TaskLevel> levelList = (List<TaskLevel>) request.getServletContext().getAttribute(Constants.TASK_LEVEL);
			result.setSuccessful(true);
			result.setData(levelList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务种类
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskCatalog")
	public @ResponseBody AjaxResult getTaskCatalog(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<TaskCatalog> catalogList = (List<TaskCatalog>) request.getServletContext().getAttribute(Constants.TASK_CATALOG);
			result.setSuccessful(true);
			result.setData(catalogList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务类型
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskType")
	public @ResponseBody AjaxResult getTaskType(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User currentUser = arsRestUtil.getCurrentUser();
			if(currentUser == null){
				throw new ArsException("用户未登录!");
			}

			int platform = arsRestUtil.getCurrentUser().getPlatform();
			
			List<TaskType> typeList = (List<TaskType>) request.getServletContext().getAttribute(Constants.TASK_TYPE);
			
			List<TaskType> data = new ArrayList<TaskType>();
			for(TaskType type : typeList) {
				if(type.getPlatform() >= platform) {
					data.add(type);
				}
			}
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务状态
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskStatus")
	public @ResponseBody AjaxResult getTaskStatus(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<TaskStatus> statusList = (List<TaskStatus>) request.getServletContext().getAttribute(Constants.TASK_STATUS);
			result.setSuccessful(true);
			result.setData(statusList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	@RequestMapping("login")
	public @ResponseBody AjaxResult login() {
		AjaxResult result = new AjaxResult();
		result.setCode("0000");
		result.setMsg("未找到登录信息。");
		result.setSuccessful(false);
		return result;
	}
	
	@RequestMapping("refuse")
	public @ResponseBody AjaxResult refuse() {
		AjaxResult result = new AjaxResult();
		result.setCode("0001");
		result.setMsg("未授权访问。");
		result.setSuccessful(false);
		return result;
	}
	
}
