package com.jeeplus.modules.API.userinfo;

import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.WordToPic;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
/**
 * 我的信息Controller
 * @author zmy
 * @version 2017-04-17
 */
@Controller
@RequestMapping(value = "${frontPath}/userInfo/myinfo")
public class MyInfoController extends BaseController{

	@Autowired
	private OfficeDao officeDao;	
	@Autowired
	private RoleDao roleDao;

    @Autowired
    private SystemService systemService;


        /**
         * 获取信息
         */
	@ResponseBody
	@RequestMapping(value = "getUserInfoMyInfoMap", method=RequestMethod.GET)
	public AjaxJson findMyInfo (String id,String officeId,String companyId, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes)
	{
		AjaxJson j=new AjaxJson();
		User user= new User();
		if (StringUtils.isNotBlank(id)){
			user = UserUtils.getNoSession(id);
		}else {
			user = UserUtils.getUser();
		}
		Office company = officeDao.get(user.getCompany());//当前企业
		Office office = officeDao.get(user.getOffice());//当前企业
		if (StringUtils.isNotBlank(officeId) && StringUtils.isNotBlank(companyId)){
			company = officeDao.get(officeId);
			office = officeDao.get(companyId);
			user.setOffice(company);
			user.setCompany(office);
			user.setCompanyName(company.getName());
			user.setOfficeName(office.getName());
		}
		if(company == null || company.getId().equals("1")){
            user.setCompanyName("");
            user.setCompany(new Office());
        } else{
			user.setCompanyName(company.getName());
			if (StringUtils.isBlank(companyId)) {
				UserUtils.removeCache("selectCompany");
				UserUtils.putCache("selectCompany", companyId);
			}
		}
		if(office == null || office.getId().equals("5") || office.getId().equals("e0ef8af9cae6416f8bb359714a1b4244")){
            user.setOfficeName("");
            user.setOffice(new Office());
        } else {
            user.setOfficeName(office.getName());
            if (StringUtils.isBlank(officeId)){
				UserUtils.removeCache("selectOffice");
				UserUtils.putCache("selectOffice",officeId);
			}
		}
		logger.info(user.getId()+"-------------------------------"+company.getId());
		logger.info(user.toString());
		List<Role> roles = systemService.getRoleList(user.getId(),company.getId());
		if (roles!=null && roles.size()!=0) {
			Role role = roles.get(0);
			if(org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().endsWith("gly")||role.getEnname().equals("system")){
				user.setIsManager("1");
			}else{
				user.setIsManager("0");
			}
			user.setRoleName(role.getName());

			UserUtils.removeCache("selectRole");
			UserUtils.putCache("selectRole", roles);
		}
		j.put("data",user);
		j.setErrorCode(ErrorCode.code_1004);
		return j;
	}

    /**
     * 保存用户个人信息
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveUserInfo",method=RequestMethod.GET)
    public AjaxJson saveUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
        AjaxJson j=new AjaxJson();
        HashMap<String, String> requestMap = findRequestMap(request);
		logger.info("saveUserInfo-------------------------------------------");
        logger.info("saveUserInfo:sign="+requestMap.get("sign"));
		String name = URLDecoder.decode(requestMap.get("name")==null?"":requestMap.get("name"), "UTF-8");
		String email = URLDecoder.decode(requestMap.get("email")==null?"":requestMap.get("email"), "UTF-8");
		String sign = URLDecoder.decode(requestMap.get("sign")==null?"":requestMap.get("sign"), "UTF-8");
		String sex = URLDecoder.decode(requestMap.get("sex")==null?"":requestMap.get("sex"), "UTF-8");
		logger.info("saveUserInfo-------------------------------------------"+sign);
		User user=UserUtils.getUser();
        //根据姓名生成图片
		if(StringUtils.isNotBlank(name) && !name.equals(user.getName())){
			user.setName(name);
			long time = System.currentTimeMillis();
			String realPathPhoto = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time+ "/img/";
			FileUtils.createDirectory(realPathPhoto);
			String picNamePhoto =time + ".png"; // encoderImgId此处图片名
			String filePathPhoto = realPathPhoto + picNamePhoto; // 存放路径
			WordToPic.TextToPic(name.substring(name.length()-2>0?name.length()-2:0,name.length()),200, 200, 55, filePathPhoto);
			String temp = request.getContextPath() + Global.USERFILES_BASE_URL + time + "/img/"+picNamePhoto;
			if (StringUtils.isNotBlank(user.getDefaultPhoto()) && user.getDefaultPhoto().equals("0")){
				InputStream inputStream = null;
				HttpURLConnection httpURLConnection;
				try {
					URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ temp);
					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 = temp.split("/");
					String photoName = System.currentTimeMillis()+arr[arr.length-1];
					ossUtil.uploadFile2OSS(inputStream, Global.getPhoto(), photoName);*/
					String path = new StringBuilder("/qrcode/")
							.append(name+System.currentTimeMillis()).append(".png").toString();
					BOSClientUtil bosClientUtil = new BOSClientUtil();
					String uploadPath = bosClientUtil.upload(path, inputStream);
					user.setPhoto(uploadPath);
					FileUtils.delFile(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if(inputStream!=null){
						try {
							inputStream.close();
						}catch (Exception e){
							e.printStackTrace();
						}
					}
				}
			}
		}
		if(StringUtils.isNotBlank(email)) user.setEmail(email);
        if(StringUtils.isNotBlank(sign)) user.setSign(sign);
        if(StringUtils.isNotBlank(sex)) user.setSex(sex);
        systemService.updateUserInfo(user);
        j.setMsg("修改用户信息成功");
        j.setErrorCode(ErrorCode.code_1004);
        return j;
    }


	/**
	 * 保存姓名
	 */
	 @ResponseBody
	 @RequestMapping(value = "saveUserName",method=RequestMethod.GET)
	    public AjaxJson saveUser(String id,HttpServletRequest request, HttpServletResponse response) {
		 AjaxJson j=new AjaxJson();
		 String name=request.getParameter("name");
         User user=UserUtils.getUser();
		 //根据姓名生成图片
		 if(StringUtils.isNotBlank(name) && !name.equals(user.getName())){
			 logger.info(name+"----"+user.getName());
			 user.setName(name);
			 long time = System.currentTimeMillis();
			 String realPathPhoto = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time+ "/img/";
			 FileUtils.createDirectory(realPathPhoto);
			 String picNamePhoto =time + ".png"; // encoderImgId此处图片名
			 String filePathPhoto = realPathPhoto + picNamePhoto; // 存放路径
			 WordToPic.TextToPic(name.substring(name.length()-2>0?name.length()-2:0,name.length()),200, 200, 55, filePathPhoto);
			 String temp = request.getContextPath() + Global.USERFILES_BASE_URL + time + "/img/"+picNamePhoto;
			 if (StringUtils.isNotBlank(user.getDefaultPhoto()) && user.getDefaultPhoto().equals("0")){
				 InputStream inputStream = null;
				 HttpURLConnection httpURLConnection;
				 try {
					 logger.info("");
					 URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ temp);
					 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 = temp.split("/");
					 String photoName = System.currentTimeMillis()+arr[arr.length-1];
					 ossUtil.uploadFile2OSS(inputStream, Global.getPhoto(), photoName);
					 user.setPhoto(Global.getAliyunUrl()+"/"+ Global.getPhoto() + photoName);
					 FileUtils.delFile(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time);
				 } catch (MalformedURLException e) {
					 e.printStackTrace();
				 } catch (IOException e) {
					 e.printStackTrace();
				 } finally {
					 if(inputStream!=null){
						 try {
							 inputStream.close();
						 }catch (Exception e){
							 e.printStackTrace();
						 }
					 }
				 }
			 }
		 }
		 if (user.getCompany()==null || StringUtils.isBlank(user.getCompany().getId())){
			 user.setCompany(new Office("1"));
		 }
		 if (user.getOffice()==null || StringUtils.isBlank(user.getOffice().getId())){
			 user.setOffice(new Office("5"));
		 }
         systemService.updateUserInfo(user);
		 j.setMsg("修改姓名成功");
		 j.setErrorCode(ErrorCode.code_1004);
		 return j;
	 }
	 /**
	  * 保存邮箱
	  */
	 @ResponseBody
	 @RequestMapping(value = "saveUserEmail",method=RequestMethod.GET)
		 public AjaxJson saveUserEmail(String id,HttpServletRequest request, HttpServletResponse response) {
		 AjaxJson j=new AjaxJson();
         String email=request.getParameter("email");
         User user=UserUtils.getUser();
			 user.setEmail(email);

            systemService.updateUserInfo(user);
			 j.setMsg("修改邮箱成功");
			 j.setErrorCode(ErrorCode.code_1004);
		 return j;
	 }
	 /**
	  * 保存签名
	  */
	 @ResponseBody
	 @RequestMapping(value = "saveUserSign",method=RequestMethod.POST)
		 public AjaxJson saveUserSign(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		 AjaxJson j=new AjaxJson();
		 HashMap<String, String> requestMap = findRequestMap(request);
		 String sign = URLDecoder.decode(requestMap.get("sign")==null?"":requestMap.get("sign"), "UTF-8");

		 String id =requestMap.get("id");
		 User user=UserUtils.getUser();
		 user.setSign(sign);
         systemService.updateUserInfo(user);
		 j.setMsg("设置签名成功");
		 j.setErrorCode(ErrorCode.code_1004);
		 return j;
	 }
	 /**
	  * 保存性别
	  */
	 @ResponseBody
	 @RequestMapping(value = "saveUserSex",method=RequestMethod.GET)
		 public AjaxJson saveUserSex(String id,HttpServletRequest request, HttpServletResponse response) {
		 AjaxJson j=new AjaxJson();
		 String sex=request.getParameter("sex");
         User user=UserUtils.getUser();
		 user.setSex(sex);
         systemService.updateUserInfo(user);
         j.setMsg("保存性别成功");
         j.setErrorCode(ErrorCode.code_1004);
		 return j;
	 }
    /**
     * 保存头像
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveUserPhoto",method=RequestMethod.POST)
    public AjaxJson saveUserPhoto(MultipartHttpServletRequest muiltRequest,HttpServletRequest servletRequest) throws Exception{
        AjaxJson j=new AjaxJson();
		try {
        User currentUser = UserUtils.getUser();
			String oldPhoto = currentUser.getPhoto();
			String aliyunUrl = Global.getAliyunUrl();
			String aliDownloadUrl = Global.getAliDownloadUrl();
			String cons = "";
			if (oldPhoto.contains(aliyunUrl)){
				cons = aliyunUrl;
			}else if (oldPhoto.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
				cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
			}else {
				cons = aliDownloadUrl;
			}
			String key = "";
			if(StringUtils.isNotBlank(oldPhoto)){
				String[] arr = oldPhoto.split(cons+"/");
				key = arr[1];
			}
        OSSClientUtil ossUtil =new OSSClientUtil();
        String fileName = muiltRequest.getFileNames().next(); //得到文件名（注意。是content-type 中的name="file1"，而不是真正的文件名）
        MultipartFile file = muiltRequest.getFile(fileName);   //得到该文件
        // 判断文件是否为空
        if (!file.isEmpty()) {
        	logger.info("key="+key);
        	try {
				ossUtil.deleteSingleObject(key);
			}catch (Exception e){
				logger.info("Exception e"+e);
			}
			//上面的删除方法里面有关闭oss客户端的操作,这里重新new一个
			ossUtil = new OSSClientUtil();
            String filePath= ossUtil.uploadFile2OSS(file, "photo");
			logger.info("filePath:"+filePath);
            currentUser.setPhoto(filePath);
            currentUser.setDefaultPhoto("1");
            systemService.updateUserInfo(currentUser);
            j.put("filePath",filePath);
        }
        j.setMsg("上传成功！");
        j.setErrorCode(ErrorCode.code_1004);
		logger.info("j:"+j.toString());
		}catch (Exception e){
			j.put("filePath","");
			j.setSuccess(false);
			j.setMsg("上传失败！");
			j.setErrorCode(ErrorCode.code_2004);
		}finally {
			return j;
		}
    }
}
