package com.pqs9900.controller.user;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
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.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njcn.enums.LogTypeEnum;
import com.njcn.enums.ProjectEnum;
import com.njcn.mapper.user.ManageListMapper;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.configuration.NodeInformation;
import com.njcn.pojo.user.ManageList;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.user.ManageListService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import com.njcn.utils.XssFilterUtil;
import com.njcn.utils.redis.JedisManager;
import com.pqs9900.service.DataInfo.AlarmInfoService;

@Controller
@RequestMapping(value ="/manage")
public class ManageListController {
	ObjectMapper objectMapper =new ObjectMapper();

	@Autowired
	ManageListService mService;

	@Autowired
	private JedisManager jedisManager;
	@Autowired
	ManageListMapper mlm;
	@Autowired
	private  AppConfig appConfig;

	@Autowired
    UserLogDetailService userLogDetailService;
	@Autowired
	private AlarmInfoService alarmInfoService;

	private int flag;
	// 日志记录
    private static final Logger logger = LoggerFactory.getLogger(ManageListController.class);
	@RequestMapping(value = "getManage", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getManage(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        try{
			List<List> users = mService.getManage();
			if (users.isEmpty()) {
				result.setCode(500);
				result.setMessage("没有获取到资源信息列表");
                userLogDetailService.getLog("查询资源", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
				logger.error("获取资源信息失败");
			} else {
				result.setCode(200);
				result.setBody(users);
				result.setMessage("获取资源信息列表成功");
                userLogDetailService.getLog("查询资源", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),0);
				logger.info("获取资源信息成功");
			}
		}catch (Exception e){
			logger.error("获取资源异常，异常为"+e.toString());
			result=PubUtils.assignmentResult(null,500,"获取资源失败");
		}
        return result;
    }

    @ResponseBody
	@RequestMapping(value = "getmange",method = RequestMethod.POST)
	public ManageList getmange(@Param("resIndex")String resIndex){
		return mService.selectTypeId(resIndex);
	}

	@ResponseBody
	@RequestMapping(value = "updateManageList"	,method = RequestMethod.POST)
	public int updateManageList(String resIndex,String name,String type,String description){
		int i=0;
		name = XssFilterUtil.dealString(name);
		description = XssFilterUtil.dealString(description);
		ManageList manageList=new ManageList();
		manageList.setRes_Index(resIndex);
		try {
			List<ManageList> manageLists=mService.selectOneByIndex(resIndex);
			if(!manageLists.isEmpty()) {
				String url=manageLists.get(0).getRes_Url();//资源地址
				File file=new File(url);
				// 判断目录或文件是否存在
				if (!file.exists()) {  // 不存在
					i=2;
				} else {
					mService.updateManageList(resIndex, name, type, description, TokenManager.getSysType(), TokenManager.getToken()
							.getUserIndex());
					i = 1;
				}
			}
		}catch ( Exception e){
			i=0;		}
		return i;
	}

	@RequestMapping(value = "getSourceManage", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getSourceManage(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        try{
			List<List> users = mService.getSourceManage();
			if (users.isEmpty()) {
				result.setCode(500);
				result.setMessage("没有获取到资源信息列表");
				logger.error("获取资源信息失败");
			} else {
				result.setCode(200);
				result.setBody(users);
				result.setMessage("获取资源信息列表成功");
				logger.info("获取资源信息成功");
			}
		}catch (Exception e){
			logger.error("获取资源异常，异常为"+e.toString());
			result=PubUtils.assignmentResult(null,500,"获取资源失败");
		}
        return result;
    }

	@RequestMapping(value="/uploadManageList",method = RequestMethod.POST)
    @ResponseBody
    public HttpResult  uploadManageList(@RequestParam(value="file",required = false)MultipartFile multipartFile,@Param(value="name")
			String name,@Param(value="type")String type,@Param(value="description")String description,
								 HttpServletRequest request, HttpServletResponse response) throws IOException, AccountException {
		HttpResult result = new HttpResult();
		/**
		 * ---------------------------------------------------------------------------------------------------
		 * xuyang 2020.08.27
		 * 修改：对上传文件做判断
		 * 1.文件类型 2.文件大小
		 */
		final long fixedSize = 3072;
		//获取文件名
		String fileName = multipartFile.getOriginalFilename();
		//文件大小(此大小为kb)
		Long fileSize  = multipartFile.getSize()/1024;
		if (fileSize > fixedSize){
			result = PubUtils.assignmentResult(null, 500, "上传失败,上传文件超过3M，文件过大!");
			return result;
		}
		if (!fileName.matches("^.+\\.(?i)(xlsx)$") && !fileName.matches("^.+\\.(?i)(xls)$")  && !fileName.matches("^.+\\.(?i)(doc)$") && !fileName.matches("^.+\\.(?i)(docx)$") && !fileName.matches("^.+\\.(?i)(pdf)$") && !fileName.matches("^.+\\.(?i)(png)$") && !fileName.matches("^.+\\.(?i)(jpg)$") && !fileName.matches("^.+\\.(?i)(cvs)$") && !fileName.matches("^.+\\.(?i)(jepg)$")) {
			result = PubUtils.assignmentResult(null, 500, "上传失败,上传文件类型错误!");
			return result;
		}
		/**
		 * over
		 * ---------------------------------------------------------------------------------------------------
		 */

		name = XssFilterUtil.dealString(name);
		description = XssFilterUtil.dealString(description);
		//首先根据deviceIndex获取IP，确定文件需要保存的文件夹路径
		//拷贝文件到指定文件夹下
		String path;
		//获取当前系统作为第二个目录
		String sysType=TokenManager.getSysType();
		String xt;
		//判断非空
        if(!org.apache.commons.lang3.StringUtils.isBlank(name)) {
            if(PubUtils.patternDes500(description)) {
                if (sysType == ProjectEnum.PQS9000.getKey()) {
                    xt = "wt";
                } else {
                    xt = "zt";
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
                String time = df.format(new Date());// new Date()为获取当前系统时间作为第三个目录
                String fTime = time +File.separator;
                try {
					String filePath = appConfig.getTmppath() +File.separator+ "Resources" +File.separator+ xt +File.separator+ fTime +File.separator+ multipartFile
                        .getOriginalFilename();
                    File file = new File(filePath);
                    FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
                    path = file.getPath();
                } catch (Exception e) {
                    logger.error("拷贝上传文件过程出错，原因：" + e.toString());
                    return PubUtils.assignmentResult(null, 500, "拷贝文件流出错");
                }
                //文件拷贝成功后，需要将路径保存起来，以便后面分析事件日志参考,注：只需要CFG文件的路径
                try {
                    if (!StringUtils.isEmpty(path) & path.toUpperCase(Locale.ENGLISH).endsWith("CFG")) {
                        String key = "Resources" + TokenManager.getUserId();
                        jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, key, path, RedisDB.SHORT_TIME);
                    }
                    result = PubUtils.assignmentResult(null, 200, "保存文件路径成功");
                } catch (Exception e) {
                    logger.error("保存文件路径出错，原因：" + e.toString());
                    result = PubUtils.assignmentResult(null, 500, "保存文件路径出错");
                }
                try {
                    ManageList ml = new ManageList();
                    String res_index = UUID.randomUUID().toString();
                    ml.setRes_Index(res_index);
                    ml.setDescription(description);
                    ml.setName(name);
                    ml.setType(type);
                    ml.setRes_Url(path);
                    User user = TokenManager.getToken();
                    String userIndex = user.getUserIndex();//当前登录用户
                    ml.setUpdateUser(userIndex);
                    ml.setUpdateTime(new Date());
                    ml.setState(1);//1表示正常
                    ml.setSysType(TokenManager.getSysType());
                    mlm.insert(ml);
                    userLogDetailService.getLog("上传资源", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                } catch (Exception e) {
                    logger.error("上传资源异常，异常为" + e.toString());
                    userLogDetailService.getLog("上传资源", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                    result = PubUtils.assignmentResult(null, 500, "上传资源失败");
                }
            }else{
                logger.error("上传资源错误，原因：资源描述长度超过限制");
                userLogDetailService.getLog("上传资源", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
                result = PubUtils.assignmentResult(null, 502, "上传资源错误，原因：资源描述长度超过限制");
            }
	    /*File file2=new File(url);
	    if(!file2.exists()){
	    	file2.mkdirs();              //判断本地是否有该路径，如果没有，就创建
	    }
        File myPath = new File( url+fTime );
        if ( !myPath.exists()){//若此目录不存在，则创建之
            myPath.mkdir();
        }
        */
        }else {
            logger.error("上传资源错误，原因：资源名称为空");
            userLogDetailService.getLog("上传资源", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
            result = PubUtils.assignmentResult(null, 501, "上传资源错误，原因：资源名称为空");
        }
		return result;
    }
	@RequestMapping(value="/deleteManageByIndex",method = RequestMethod.POST)
    @ResponseBody
	public int deleteManageByIndex(HttpServletRequest request,@Param(value="res_Index")String res_Index){
		int result=0;
		ManageList manageList=new ManageList();
		manageList.setRes_Index(res_Index);
		try {
			List<ManageList> manageLists=mService.selectOneByIndex(res_Index);
			if(!manageLists.isEmpty()){
				String url=manageLists.get(0).getRes_Url();//资源地址
				File file=new File(url);
				// 判断目录或文件是否存在
			    if (!file.exists()) {  // 不存在
			    	result=0;
			    } else {
			        // 判断是否为文件
			        if (file.isFile()) {  // 为文件时调用删除文件方法
			        	if (file.isFile() && file.exists()) {
			    	        file.delete();
			    	        mService.deleteIndex(res_Index);
			    	        result = 1;
                            userLogDetailService.getLog("删除资源", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
			    	    }else{
			    	    	result = 0;
                            userLogDetailService.getLog("删除资源", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(),1);
			    	    }
			        }
			    }
			}
		} catch (Exception e) {
			logger.error("删除资源异常，异常为"+e.toString());
			result=0;
		}
		return result;
	}

	/***
	 * 前置机管理详情
	 * @return
	 */
	@RequestMapping(value="getNodeInfo",method=RequestMethod.POST)
	@ResponseBody
	public String getNodeInfo(HttpSession session) throws JsonProcessingException{
		List<NodeInformation> result=new ArrayList<NodeInformation>();
		List<List> s=new ArrayList<List>();

		int j=0;
		try {
			result = mService.getNodeInfo();

			for (int i = 0; i < result.size(); i++) {
				List<String> a = new ArrayList<String>();
				a.add(String.valueOf(result.get(i).getNodeIndex()));
				a.add(result.get(i).getNodeName());
				a.add(result.get(i).getNodeDesc());
				a.add(result.get(i).getNodeIP());
				if (result.get(i).getNodeStatus() == 0) {
					a.add("删除");
				} else {
					a.add("正常");
				}
				s.add(a);
			}
		}catch (Exception e) {
			logger.error("查询前置机异常，异常是" + e.toString());
		}
		return objectMapper.writeValueAsString(s);
	}

	@RequestMapping(value="delNodeInfo",method=RequestMethod.POST)
	@ResponseBody
	public HttpResult delNodeInfo(HttpServletRequest request,Long nodeIndex){
		HttpResult result=new HttpResult();

		try {
			String message = mService.delNode(nodeIndex);
			if (message.equalsIgnoreCase("删除成功")) {
				result.setCode(200);
				result.setMessage(message);
				logger.info("删除前置机成功!");
			} else {
				result.setCode(500);
				result.setMessage(message);
				logger.error("删除前置机失败!");
			}

		} catch (Exception e) {
			result.setCode(500);
			result.setMessage("删除前置机失败!");
			logger.error("删除前置机失败!");
		}
		return result;
	}

	@RequestMapping(value="addNode",method=RequestMethod.POST)
	@ResponseBody
	public HttpResult addNode(HttpServletRequest request,HttpSession session,String nodeName,String nodeDesc,
			String ip4,String ip3,String ip2,String ip1){
		HttpResult result=new HttpResult();
		try {
			String message = mService.saveNode(nodeName, nodeDesc, ip4, ip3, ip2, ip1);
			if (message.equalsIgnoreCase("添加成功")) {
				result.setCode(200);
				result.setMessage(message);
				logger.info("新增前置机成功!");
			} else if (message.equalsIgnoreCase("添加失败a")) {
				result.setCode(400);
				result.setMessage(message);
				logger.error("新增前置机失败!名称已存在");
			} else {
				result.setCode(500);
				result.setMessage(message);
				logger.error("新增前置机失败!");
			}

		} catch (Exception e) {
			result.setCode(500);
			result.setMessage("新增前置机失败!");
			logger.error("新增前置机失败!");
		}
		return result;
	}

	@RequestMapping(value="loadNode",method=RequestMethod.POST)
	@ResponseBody
	public List<String> loadNode(HttpServletRequest request,Long nodeIndex){
		List<String> result = new ArrayList<>();
		try {
			result=mService.loadNode(nodeIndex);
		} catch (Exception e) {
			result = null;
		}

		return result;
	}

	@RequestMapping(value="modNode",method=RequestMethod.POST)
	@ResponseBody
	public HttpResult modNode(HttpServletRequest request,Long nodeIndex,String nodeName,String nodeDesc,
			String ip4,String ip3,String ip2,String ip1){
		HttpResult result=new HttpResult();

		try {
			String message = mService.updateNode(nodeIndex, nodeName, nodeDesc, ip4, ip3, ip2, ip1);
			if (message.equalsIgnoreCase("更新成功")) {
				result.setCode(200);
				result.setMessage(message);
				logger.info("更新前置机成功!");
			} else if (message.equalsIgnoreCase("更新失败a")) {
				result.setCode(400);
				result.setMessage(message);
				logger.error("更新前置机失败!名称已存在");
			} else {
				result.setCode(500);
				result.setMessage(message);
				logger.error("更新前置机失败!");
			}

		} catch (Exception e) {
			result.setCode(500);
			result.setMessage("更新前置机失败!");
			logger.error("更新前置机失败!");
		}
		return result;
	}
}
