package com.bcxin.ars.rest.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bcxin.ars.dto.NativeReturnDTO;
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 com.bcxin.ars.model.Nation;
import com.bcxin.ars.model.Native;
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.dto.AppAjaxResult;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.DateUtil;
import com.bcxin.ars.util.IdNumUtil;

@Controller
@RequestMapping("/app")
public class AppBaseController {
	
	private Logger logger = LoggerFactory.getLogger(AppBaseController.class);
	
	@Value("${base-folder}")
	private String baseFolder;
	
	@Value("${upload-folder}")
	private String uploadFolder;
	
	@Value("${temp-folder}")
	private String tempFolder;
	
	@Autowired
	private ArsRestUtil arsRestUtil;
	
	
	/**
	 * 获取民族列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getNation")
	public @ResponseBody AppAjaxResult getNation(HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<Nation> nationList = (List<Nation>) request.getSession().getServletContext().getAttribute(Constants.NATION_LIST);
			result.setSuccessful(true);
			result.setEncodeData(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 AppAjaxResult getNative(@PathVariable("code")Long code, HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		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.setEncodeData(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 AppAjaxResult getNativeByIdNum(@PathVariable("idNum")String idNum, HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		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);
				NativeReturnDTO returnArea=new NativeReturnDTO();
				if(area != null) {
				    //modify by zjh time：2018年8月7日 14:24:53 改造返回方法类，之前的类会在json序列化的时候无限递归
					returnArea.setNativeName(area.getParent().getNativeName()+"-"+area.getNativeName());
					returnArea.setCode(area.getCode());
					result.setSuccessful(true);
					result.setEncodeData(returnArea);
				} 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 AppAjaxResult getCurrentNative(HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		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.setEncodeData(na);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务等级
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskLevel")
	public @ResponseBody AppAjaxResult getTaskLevel(HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskLevel> levelList = (List<TaskLevel>) request.getServletContext().getAttribute(Constants.TASK_LEVEL);
			result.setSuccessful(true);
			result.setEncodeData(levelList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务种类
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskCatalog")
	public @ResponseBody AppAjaxResult getTaskCatalog(HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskCatalog> catalogList = (List<TaskCatalog>) request.getServletContext().getAttribute(Constants.TASK_CATALOG);
			result.setSuccessful(true);
			result.setEncodeData(catalogList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务类型
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskType")
	public @ResponseBody AppAjaxResult getTaskType(HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskType> typeList = (List<TaskType>) request.getServletContext().getAttribute(Constants.TASK_TYPE);
			int platform = arsRestUtil.getCurrentUser().getPlatform();
			List<TaskType> data = new ArrayList<TaskType>();
			for(TaskType type : typeList) {
				if(type.getPlatform() >= platform) {
					data.add(type);
				}
			}
			result.setSuccessful(true);
			result.setEncodeData(data);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	
	/**
	 * 获取任务状态
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getTaskStatus")
	public @ResponseBody AppAjaxResult getTaskStatus(HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			List<TaskStatus> statusList = (List<TaskStatus>) request.getServletContext().getAttribute(Constants.TASK_STATUS);
			result.setSuccessful(true);
			result.setEncodeData(statusList);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 获取当前服务器时间
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("getCurrentDate")
	public @ResponseBody AppAjaxResult getTime(HttpServletRequest request) throws Exception {
		AppAjaxResult result = new AppAjaxResult();
		try {
			String currentDate=DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss");
			result.setSuccessful(true);
			result.setEncodeData(currentDate);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

}
