package com.jeeplus.modules.API.sys;

import com.easemob.server.example.api.impl.EasemobIMUsers;
import com.google.common.collect.Lists;
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.JedisUtils;
import com.jeeplus.common.utils.RequestUtils;
import com.jeeplus.common.utils.WordToPic;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Dict;
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.DictService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tools.utils.TwoDimensionCode;
import com.jeeplus.modules.utils.ErrorCode;
import io.swagger.client.model.Nickname;
import io.swagger.client.model.RegisterUsers;
import net.sf.json.JSONObject;
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 redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 注册Controller
 *
 * @author mengxy
 * @version 2017-5-22
 */
@Controller

public class RegisterMobileController extends BaseController {

//	@Autowired
//	private SystemConfigService systemConfigService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "test" , method=RequestMethod.GET)
    public AjaxJson test(HttpServletRequest request, HttpServletResponse response) {
        return new AjaxJson();
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "${frontPath}/registerUser", method = RequestMethod.POST)
    public AjaxJson registerUser(HttpServletRequest request, HttpServletResponse response) {
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String mobile = requestMap.get("mobile");
            String randomCode = requestMap.get("randomCode");
            String name = requestMap.get("name");
            String password = requestMap.get("password");
            AjaxJson j = new AjaxJson();

            if (!randomCode.equals(jedis.get(mobile)) || !"1".equals(jedis.get("1"))) {
                String message= "验证码验证失败!";
                j.setSuccess(false);
                j.setMsg(message);
                j.setErrorCode(ErrorCode.code_1011);
                return j;
            }
            // 清除验证码
            //request.getSession().getServletContext().removeAttribute(mobile);
            jedis.del(mobile);
            String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
            String contextPath = request.getContextPath();
            j = systemService.registerUser(mobile,randomCode,name,password,contextPath,url);
            return j;
        } catch (Exception e) {
            //logger.error("getActiveSessions", e);
            AjaxJson j = new AjaxJson();
            String message= "验证码验证失败!";
            j.setSuccess(false);
            j.setMsg(message);
            j.setErrorCode(ErrorCode.code_1011);
            return j;
        } finally {
            JedisUtils.returnResource(jedis);
        }

       /* long time = System.currentTimeMillis();
        try {
            // 验证手机号是否已经注册
            if (userDao.findUniqueByProperty("mobile", mobile) != null) {
                // 如果是手机登录，则返回JSON字符串
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_1007);
                j.setMsg("手机号已经被使用！");
                return j;
            }
            //		// 验证短信内容
            //		if (!randomCode.equals(request.getSession().getServletContext().getAttribute(mobile))) {
            //			// 如果是手机登录，则返回JSON字符串
            //			j.setSuccess(false);
            //			j.setErrorCode("3");
            //			j.setMsg("手机验证码不正确!");
            //			return j;
            //		}

            // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
            List<Dict> dictList = DictUtils.getDictList("defalut_role");
            Dict dict = dictList.get(0);
            Role role = systemService.getRole(dict.getValue());


            // 密码MD5加密
            user.setPasswordRemake(password);
            user.setPassword(SystemService.entryptPassword(password));
            user.setLoginName(mobile);

            // 岗位数据有效性验证，过滤不在授权内的岗位
            List<Role> roleList = Lists.newArrayList();
            roleList.add(role);
            user.setRoleList(roleList);
            *//*
             * //保存机构 user.setCompany(office); user.setOffice(office);
             *//*
            // 生成用户二维码，使用登录名
            String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL +time+ "/qrcode/";
            FileUtils.createDirectory(realPath);
            String picName = time + ".png"; // encoderImgId此处二维码的图片名
            String filePath = realPath + picName; // 存放路径
            TwoDimensionCode.encoderQRCode(user.getLoginName(), filePath, "png");// 执行生成二维码
            user.setQrCode(request.getContextPath() + Global.USERFILES_BASE_URL +time+  "/qrcode/" + picName);
            if (user.getQrCode()!=null && !user.getQrCode().equals("")){
                InputStream inputStream = null;
                HttpURLConnection httpURLConnection;
                try {
                    URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ user.getQrCode());
                    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 = user.getQrCode().split("/");
                    String qrCodeName = System.currentTimeMillis()+arr[arr.length-1];
                    ossUtil.uploadFile2OSS(inputStream, Global.getRqcode(),qrCodeName);
                    user.setQrCode(Global.getAliyunUrl()+"/"+ Global.getRqcode() + qrCodeName);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    inputStream.close();
                }
            }
            user.setName(name);
            String realPathPhoto = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time+ "/img/";
            FileUtils.createDirectory(realPathPhoto);
            String picNamePhoto =time + ".png"; // encoderImgId此处二维码的图片名
            String filePathPhoto = realPathPhoto + picNamePhoto; // 存放路径
            //FontImageUtil.createImage(name.substring(0, 1), new Font("宋体", Font.BOLD, 100), new File(filePathPhoto), 200, 200);
            WordToPic.TextToPic(name.substring(name.length()-2>0?name.length()-2:0,name.length()),200, 200, 55, filePathPhoto);
            user.setPhoto(request.getContextPath() + Global.USERFILES_BASE_URL + time + "/img/"+picNamePhoto);
            if (user.getPhoto()!=null && !user.getPhoto().equals("")){
                InputStream inputStream = null;
                HttpURLConnection httpURLConnection;
                try {
                    URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ user.getPhoto());
                    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 = user.getPhoto().split("/");
                    String photoName = time+arr[arr.length-1];
                    ossUtil.uploadFile2OSS(inputStream, Global.getPhoto(),photoName);
                    user.setPhoto(Global.getAliyunUrl() + "/" + Global.getPhoto() + photoName);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    inputStream.close();
                }
            }
            user.setMobile(mobile);
            // 保存用户信息
            user.setDefaultPhoto("0");
            user.setComId("1");
            user.setRole(new Role("1"));
            user.setCompany(new Office("1"));
            user.setOffice(new Office("5"));
            systemService.saveUser(user);
            // 清除当前用户缓存
            if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
                UserUtils.clearCache();
                // UserUtils.getCacheMap().clear();
            }
            request.getSession().getServletContext().removeAttribute(user.getMobile());// 清除验证码
            //环信注册
            RegisterUsers users = new RegisterUsers();
            io.swagger.client.model.User user1 = new io.swagger.client.model.User().username(user.getId()).password(password);
            users.add(user1);
            Object result = easemobIMUsers.createNewIMUserSingle(users);
            Nickname nickname =new Nickname();
            nickname.setNickname(user.getName());
            easemobIMUsers.modifyIMUserNickNameWithAdminToken(user.getId(),nickname);
            logger.info(result.toString());
            JSONObject json = JSONObject.fromObject(result);
            j.put("IMUser", json);

            j.setSuccess(true);
            j.setMsg("注册用户'" + user.getLoginName() + "'成功");
            j.put("userId", user.getId());
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            e.printStackTrace();
            userDao.delete(user);
        }*/

    }

    /**
     * 获取验证码
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "${frontPath}/getRandomCode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson getRegisterCode(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        String mobile = request.getParameter("mobile");
        String type = request.getParameter("type");
        logger.info(request.getContextPath()+"/f/getRandomCode?mobile="+mobile+"&type="+type);
        Jedis jedis = null;
        try {
            // 验证手机号是否已经注册
            if (userDao.findUniqueByProperty("mobile", mobile) != null) {
                if (type.equals("1") || type.equals("4")) {
                    j.setSuccess(false);
                    j.setErrorCode(ErrorCode.code_1007);
                    j.setMsg("手机号已经被使用！");
                    return j;
                }
            }

            String randomCode = String.valueOf((int) (Math.random() * 9000 + 1000));
            HashMap<String,Object> result =UserUtils.sendRandomCodes(mobile, randomCode);
            String statusCode = (String) result.get("statusCode");
                //if (result.contains("Success") && result.contains("ok")) {
                if (("000000").equals(statusCode)) {
                    j.setSuccess(true);
                    j.setErrorCode(ErrorCode.code_1004);
                    j.setMsg("短信发送成功!");
                    Map<String,Object> map = new HashMap<>();
                    map.put("randomCode",randomCode);
                    map.put("type",type);
                    map.put("mobile",mobile);
                    j.put("data",map);
                    logger.info("../f/getRandomCode/  randomCode=" + randomCode);
                    jedis = JedisUtils.getResource();
                    if(jedis.get(mobile)!=null && jedis.get(type)!=null){
                        jedis.del(mobile);
                        jedis.del(type);
                    }
                    jedis.set(mobile, randomCode);
                    jedis.setex(mobile, 300, randomCode);
                    jedis.set(type, type);
               /* if(request.getSession().getServletContext().getAttribute(mobile)!=null && request.getSession().getServletContext().getAttribute(type)!=null){
                    request.getSession().getServletContext().removeAttribute(mobile);
                    request.getSession().getServletContext().removeAttribute(type);
                }
                request.getSession().getServletContext().setAttribute(mobile, randomCode);
                request.getSession().getServletContext().setAttribute(type, type);*/
                } else {
                    j.setSuccess(false);
                    j.setErrorCode(ErrorCode.code_1008);
                    j.setMsg("短信发送失败，错误代码：101，请联系管理员。");
                    j.put("ErrorXml",result);
                }


        }catch (Exception e){
            logger.info("5");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_1008);
            j.setMsg("短信发送失败!");
        }
        finally {
            JedisUtils.returnResource(jedis);
        }
        return j;
    }

    /**
     * 验证手机验证码是否正确
     */
    @ResponseBody
    @RequestMapping(value = "${frontPath}/validateMobileCode", method = RequestMethod.GET)
    public AjaxJson validateMobileCode(HttpServletRequest request) {
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
        String mobile = requestMap.get("mobile");
        String randomCode = requestMap.get("randomCode");
        String type = requestMap.get("type");
        String message ="验证失败!";
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            String a= jedis.get(mobile);
            if (randomCode.equals(jedis.get(mobile)) && type.equals(jedis.get(type))) {
                message= "验证成功!";
                j.setSuccess(true);
                j.setMsg(message);
                j.setErrorCode(ErrorCode.code_1004);
            } else {
                j.setSuccess(false);
                j.setMsg(message);
                j.setErrorCode(ErrorCode.code_1011);
            }
            return j;
        } catch (Exception e) {
            //logger.error("getActiveSessions", e);
            j.setSuccess(false);
            j.setMsg(message);
            j.setErrorCode(ErrorCode.code_1011);
            return j;
        } finally {
            JedisUtils.returnResource(jedis);
        }
    }
}
