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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.*;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.appversion.entity.Appversions;
import com.jeeplus.modules.appversion.service.AppversionsService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tools.utils.TwoDimensionCode;
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.ModelAttribute;
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.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * app版本信息Controller
 * @author YangFan
 * @version 2017-07-07
 */
@Controller
@RequestMapping(value = "${adminPath}/appversion/appversions")
public class AppversionsController extends BaseController {

	@Autowired
	private AppversionsService appversionsService;
	@Autowired
	private PushinfoService pushinfoService;

	@ModelAttribute
	public Appversions get(@RequestParam(required=false) String id) {
		Appversions entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = appversionsService.get(id);
		}
		if (entity == null){
			entity = new Appversions();
		}
		return entity;
	}
	
	/**
	 * app版本信息列表页面
	 */
	@RequiresPermissions("appversion:appversions:list")
	@RequestMapping(value = {"list", ""})
	public String list(Appversions appversions, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Appversions> page = appversionsService.findPage(new Page<Appversions>(request, response), appversions);
		model.addAttribute("page", page);
		return "modules/appversion/appVersionsList";
	}

	/**
	 * 查看，增加，编辑app版本信息表单页面
	 */
	@RequiresPermissions(value={"appversion:appversions:view","appversion:appversions:add","appversion:appversions:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Appversions appversions, Model model,@RequestParam(value = "readAttr",required = false)String readAttr) {
		model.addAttribute("readAttr",StringUtils.isBlank(readAttr)?"false":"true");
		model.addAttribute("appversions", appversions);
		return "modules/appversion/appVersionsForm";
	}

	/**
	 *  不使用ckfinder 工具，直接上传到阿里云
	 * @param appversions
	 * @param model
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions(value={"appversion:appversions:add","appversion:appversions:edit"},logical=Logical.OR)
	@RequestMapping(value = "saveFiles")
	public String saveFiles(Appversions appversions, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes)throws Exception{
		if (!beanValidator(model, appversions)){
			return form(appversions, model,"");
		}
		String urls = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
		String middUrl = request.getContextPath()+"uploadFiles/appversion";
		if(!appversions.getIsNewRecord()){//编辑表单保存
			Appversions t = appversionsService.get(appversions.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(appversions, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			//重新生成二维码
			createQrCode(t,urls,middUrl);
			//附件上传
			fileUpload(request,t);
			appversionsService.save(t);//保存
			//推送新版本信息
			pushAppversionsInfo(t);
		}else{//新增表单保存
			if (appversions.getFiles()!=null && appversions.getFiles().contains("|")){
				appversions.setFiles(appversions.getFiles().replace("|",""));
			}else {
				appversions.setFiles("");
			}
			//生成二维码
			createQrCode(appversions,urls,middUrl);

			//附件上传到阿里云
			InputStream inputStream = null;
			HttpURLConnection httpURLConnection;
			if (appversions.getFiles()!=null && !appversions.getFiles().equals("")){
				String files = appversions.getFiles().replace("|","");
				try {
					URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ files);
					httpURLConnection = (HttpURLConnection) url.openConnection();
					// 设置网络连接超时时间
					httpURLConnection.setConnectTimeout(3000);
					// 设置应用程序要从网络连接读取数据
					httpURLConnection.setDoInput(true);
					httpURLConnection.setRequestMethod("GET");
					int responseCode = httpURLConnection.getResponseCode();
					if (responseCode == 200) {
						// 从服务器返回一个输入流
						inputStream = httpURLConnection.getInputStream();
					}
					OSSClientUtil ossUtil =new OSSClientUtil();
					String[] arr = appversions.getFiles().split("/");
					logger.info("arr[arr.length-1]="+arr[arr.length-1]);
					String name = System.currentTimeMillis()+arr[arr.length-1];
					ossUtil.uploadFile2OSS(inputStream,  Global.getAppData(),name);
					appversions.setFiles(Global.getAliyunUrl()+"/"+Global.getAppData()+name);

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					inputStream.close();
				}
			}
			appversionsService.save(appversions);//保存
			//推送版本更新信息
			pushAppversionsInfo(appversions);
		}
		addMessage(redirectAttributes, "保存app版本信息成功");
		return "redirect:"+Global.getAdminPath()+"/appversion/appversions/?repage";
	}
	/**
	 * 保存app版本信息
	 */
	@RequiresPermissions(value={"appversion:appversions:add","appversion:appversions:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Appversions appversions, Model model,HttpServletRequest request,
					   RedirectAttributes redirectAttributes,
					   @RequestParam(value = "appFile",required = false) MultipartFile appFile) throws Exception{
		if (!beanValidator(model, appversions)){
			return form(appversions, model,"");
		}

		if("ios".equals(appversions.getRemarks().toLowerCase())){
			//ios版本
			String iosAddress = "";
			Properties prop =  new  Properties();
			InputStream in = this.getClass().getClassLoader().getResourceAsStream("/app-ios.properties");
			try  {
				prop.load(in);
				iosAddress = prop.getProperty( "ios" ).trim();

				appversions.setUrl(iosAddress);
				//生成并上传二维码到阿里云
				createQrCode_ios_android(request,appversions,iosAddress,"");
			}  catch  (IOException e) {
				e.printStackTrace();
			}
			if(!StringUtils.isBlank(iosAddress)){
				appversions.setUrl(iosAddress);
			}
			appversionsService.save(appversions,null);
		}
		if("Android".equalsIgnoreCase(appversions.getRemarks())){
			appversionsService.save(appversions,appFile);
			//生成并上传二维码到阿里云
			String aliyunUrl = appversions.getUrl();
			createQrCode_ios_android(request,appversions,"",aliyunUrl);
		}

		pushAppversionsInfo(appversions);
		addMessage(redirectAttributes, "保存app版本信息成功");
		return "redirect:"+Global.getAdminPath()+"/appversion/appversions/?repage";
	}

	//附件上传到阿里云
	public void fileUpload(HttpServletRequest request,Appversions t){
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection;
		if (t.getFiles()!=null && !t.getFiles().equals("")){
			String files = t.getFiles().replace("|","");
			try {
				URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ files);
				httpURLConnection = (HttpURLConnection) url.openConnection();
				// 设置网络连接超时时间
				httpURLConnection.setConnectTimeout(3000);
				// 设置应用程序要从网络连接读取数据
				httpURLConnection.setDoInput(true);
				httpURLConnection.setRequestMethod("GET");
				int responseCode = httpURLConnection.getResponseCode();
				if (responseCode == 200) {
					// 从服务器返回一个输入流
					inputStream = httpURLConnection.getInputStream();
				}
				OSSClientUtil ossUtil =new OSSClientUtil();
				String[] arr = t.getFiles().split("/");
				logger.info("arr[arr.length-1]="+arr[arr.length-1]);
				String name = System.currentTimeMillis()+arr[arr.length-1];
				ossUtil.uploadFile2OSS(inputStream,  Global.getAppData(),name);
				t.setFiles(Global.getAliyunUrl()+"/"+Global.getAppData()+name);

			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if(inputStream != null){
						inputStream.close();
					}
				}catch (IOException e){
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 按照Android或IOS机型分别推送版本更新信息
	 * @param
	 */
	private void pushAppversionsInfo(Appversions appversions){
		String remarks = appversions.getRemarks();
		Map extras = new HashMap();
		String title = "版本更新";
		String content = appversions.getContent();
		extras.put("versions",appversions.getVersions());
		extras.put("type","1002");
		extras.put("url",appversions.getUrl());
		//type 1002  url

		JPushClientUtil.sendNotificationTo_Android_or_IOS(remarks,title,content,extras);

		Pushinfo pushinfo = new Pushinfo();
		pushinfo.setCurrentUser(UserUtils.getUser());
		pushinfo.setRemarks(appversions.getContent());
		pushinfo.setUserId(UserUtils.getUser().getId());
		pushinfo.setType("1002");
		pushinfo.setPushId(appversions.getId());
		pushinfo.setTitle(title);
		pushinfo.setContent(appversions.getVersions()+"版本新功能介绍");
		pushinfo.setStatus("版本更新");
		pushinfo.setPushUserId("allpushusers");//
		pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
		pushinfo.setAddcontent(appversions.getUrl());
		pushinfo.setMobile(remarks.toLowerCase());
		pushinfo.setParentType("allVersion");

		pushinfoService.save(pushinfo);

	}
	//ios的下载地址是固定的，Android的下载地址为阿里云，根据下载地址生成二维码
	private void createQrCode_ios_android(HttpServletRequest request,Appversions appversions,String iosAddress , String aliyunUrl)throws Exception{

		if(appversions!=null){
			String filePath = "" ;
			if(!StringUtils.isBlank(iosAddress)){
				String iosQrcode_local = request.getSession().getServletContext().getRealPath("local_upload/ios_qrcode/")+System.currentTimeMillis();
				new File(iosQrcode_local).mkdirs();
				String name =System.currentTimeMillis()+ ".png";
				filePath = iosQrcode_local+File.separator+name;
				//生成二维码
				TwoDimensionCode.encoderQRCode(iosAddress,filePath,"png");
			}else if(!StringUtils.isBlank(aliyunUrl)){
				String androidQrcode_local = request.getSession().getServletContext().getRealPath("local_upload/android_qrcode/")+System.currentTimeMillis();
				new File(androidQrcode_local).mkdirs();
				String name =System.currentTimeMillis()+ ".png";
				filePath = androidQrcode_local+File.separator+name;
				//生成二维码
				TwoDimensionCode.encoderQRCode(aliyunUrl,filePath,"png");
			}

			//上传二维码
			OSSClientUtil ossUtil = new OSSClientUtil();
			InputStream inputStream = null;
			try {
				inputStream = new FileInputStream(new File(filePath));
				String qrcodeName = iosAddress+aliyunUrl+System.currentTimeMillis()+filePath.substring(filePath.lastIndexOf("."));
				ossUtil.uploadFile2OSS(inputStream, Global.getAppData(), qrcodeName);
				appversions.setQrcode(Global.getAliyunUrl()+"/"+Global.getAppData()+qrcodeName);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try{
					if(inputStream != null){
						inputStream.close();
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		}

	}
	/**  该方法已废弃；
	 * 输入字符串，生成二维码信息
	 * @param appversions
	 * @param urls
	 * @param middUrl
	 * @throws Exception
	 */
	private void createQrCode(Appversions appversions,String urls,String middUrl)throws Exception{
		try {
			long curr = System.currentTimeMillis();
			String realPath = Global.getUserfilesBaseDir()+Global.USERFILES_BASE_URL+curr+"/qrcode/";
			FileUtils.createDirectory(realPath);
			String name = System.currentTimeMillis()+".png";
			String filePath = realPath + name;

			if (appversions.getUrl()!=null && !appversions.getUrl().equals("")){
				String content = appversions.getUrl();
				logger.error("encodeQrCode.content="+content);
				TwoDimensionCode.encoderQRCode(content,filePath,"png");//执行生成二维码
				OSSClientUtil ossUtil =new OSSClientUtil();

				appversions.setQrcode(middUrl+curr+"/qrcode/"+name);

				InputStream inputStream = null;
				HttpURLConnection httpURLConnection;
				try {
					URL url = new URL(urls+appversions.getQrcode());
					httpURLConnection = (HttpURLConnection) url.openConnection();
					// 设置网络连接超时时间
					httpURLConnection.setConnectTimeout(3000);
					// 设置应用程序要从网络连接读取数据
					httpURLConnection.setDoInput(true);
					httpURLConnection.setRequestMethod("GET");
					int responseCode = httpURLConnection.getResponseCode();
					if (responseCode == 200) {
						// 从服务器返回一个输入流
						inputStream = httpURLConnection.getInputStream();
					}
					String[] arr = appversions.getQrcode().split("/");
					logger.info("arr[arr.length-1]="+arr[arr.length-1]);
					String qrcodeName = System.currentTimeMillis()+arr[arr.length-1];
					ossUtil.uploadFile2OSS(inputStream, Global.getAppData(), qrcodeName);

					appversions.setQrcode(Global.getAliyunUrl()+"/"+Global.getAppData()+qrcodeName);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
                    inputStream.close();
                }
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 删除app版本信息
	 */
	@RequiresPermissions("appversion:appversions:del")
	@RequestMapping(value = "delete")
	public String delete(Appversions appversions, RedirectAttributes redirectAttributes) {
		appversionsService.delete(appversions);
		addMessage(redirectAttributes, "删除app版本信息成功");
		return "redirect:"+Global.getAdminPath()+"/appversion/appversions/?repage";
	}
	
	/**
	 * 批量删除app版本信息
	 */
	@RequiresPermissions("appversion:appversions:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			appversionsService.delete(appversionsService.get(id));
		}
		addMessage(redirectAttributes, "删除app版本信息成功");
		return "redirect:"+Global.getAdminPath()+"/appversion/appversions/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("appversion:appversions:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Appversions appversions, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "app版本信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Appversions> page = appversionsService.findPage(new Page<Appversions>(request, response, -1), appversions);
    		new ExportExcel("app版本信息", Appversions.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出app版本信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/appversion/appversions/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("appversion:appversions: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<Appversions> list = ei.getDataList(Appversions.class);
			for (Appversions appversions : list){
				try{
					appversionsService.save(appversions);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条app版本信息记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条app版本信息记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入app版本信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/appversion/appversions/?repage";
    }
	
	/**
	 * 下载导入app版本信息数据模板
	 */
	@RequiresPermissions("appversion:appversions:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "app版本信息数据导入模板.xlsx";
    		List<Appversions> list = Lists.newArrayList(); 
    		new ExportExcel("app版本信息数据", Appversions.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/appversion/appversions/?repage";
    }
	
	
	

}