package com.izouma.awesomeadmin.service.impl;

import com.izouma.awesomeadmin.constant.AppConstant;
import com.izouma.awesomeadmin.dao.UserInfoMapper;
import com.izouma.awesomeadmin.dto.Page;
import com.izouma.awesomeadmin.model.UserInfo;
import com.izouma.awesomeadmin.service.OSSFileService;
import com.izouma.awesomeadmin.service.UserInfoService;
import com.izouma.awesomeadmin.util.MD5Util;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import io.rong.RongCloud;
import io.rong.models.SMSVerifyCodeResult;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * user_info service接口实现类
 * Tue Apr 17 10:32:49 CST 2018  Suo Chen Cheng
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private static Logger logger = Logger.getLogger(UserInfoServiceImpl.class);
    private RongCloud rongCloud = RongCloud.getInstance(PropertiesFileLoader.getProperties("rongyunappkey"), PropertiesFileLoader.getProperties("rongyunappsecret"));


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private OSSFileService ossFileService;

    @Override
    public List<UserInfo> getUserInfoList(UserInfo record) {

        logger.info("getUserInfoList");
        try {

            return userInfoMapper.queryAllUserInfo(record);
        } catch (Exception e) {
            logger.error("getUserInfoList", e);
        }

        return null;
    }

    @Override
    public List<UserInfo> getUserInfoByPage(Page page, UserInfo record) {

        logger.info("getUserInfoByPage");
        try {

            Map<String, Object> parameter = new HashMap<String, Object>();
            parameter.put("record", record);
            parameter.put(AppConstant.PAGE, page);

            return userInfoMapper.queryUserInfosByPage(parameter);
        } catch (Exception e) {
            logger.error("getUserInfoByPage", e);
        }

        return null;
    }

    @Override
    public UserInfo getUserInfoById(String id) {

        logger.info("getUserInfoById");
        try {

            return userInfoMapper.selectByPrimaryKey(Integer.valueOf(id));
        } catch (Exception e) {
            logger.error("getUserInfoById", e);
        }

        return null;
    }

    @Override
    public UserInfo getUserInfo(UserInfo record) {

        logger.info("getUserInfo");
        try {

            return userInfoMapper.queryUserInfo(record);
        } catch (Exception e) {
            logger.error("getUserInfo", e);
        }

        return null;
    }

    @Override
    public boolean createUserInfo(UserInfo record) {

        logger.info("createUserInfo");
        try {
            if (StringUtils.isNotEmpty(record.getPassword())) {
                record.setPassword(MD5Util.getMD5(record.getPassword()));
            }else{
                record.setPassword(MD5Util.getMD5("123456"));
            }
            int updates = userInfoMapper.insertSelective(record);

            if (updates > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("createUserInfo", e);
        }

        return false;
    }

    @Override
    public boolean deleteUserInfo(String id) {

        logger.info("deleteUserInfo");
        try {

            int updates = userInfoMapper.delete(id);

            if (updates > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("deleteUserInfo", e);
        }

        return false;
    }

    @Override
    public boolean updateUserInfo(UserInfo record) {

        logger.info("updateUserInfo");
        try {

            int updates = userInfoMapper.updateByPrimaryKeySelective(record);

            if (updates > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.error("updateUserInfo", e);
        }

        return false;
    }

    @Override
    public UserInfo login(String username, String password) {
        logger.info("login");
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("username", username);
            map.put("password", MD5Util.getMD5(password));
            UserInfo result = userInfoMapper.login(map);
            return result;
        } catch (Exception e) {
            logger.error("login", e);
        }
        return null;
    }

    @Override
    public UserInfo loginSms(String phone, String code, String sessionId) throws LoginException {
        logger.info("loginSms");
        SMSVerifyCodeResult sMSVerifyCodeResult;
        try {
            sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LoginException("验证码错误");
        }
        if (200 == sMSVerifyCodeResult.getCode()) {
            Boolean success = sMSVerifyCodeResult.getSuccess();
            if (success) {
                UserInfo userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo = getUserInfo(userInfo);
                if (userInfo == null) {
                    userInfo = new UserInfo();
                    userInfo.setPhone(phone);
                    userInfo.setUsername(phone);
                    userInfo.setNickname(phone);
                    userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
                    if (!createUserInfo(userInfo)) {
                        throw new LoginException("登录失败");
                    }
                }
                return userInfo;
            }
        }
        throw new LoginException("验证码错误");
    }

    @Override
    public UserInfo loginWeiXin(String openId, String nickname, String sex, String headimgurl) {
        logger.info("loginWeiXin");
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setOpenId(openId);
            userInfo = getUserInfo(userInfo);

            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setUsername(nickname);
                userInfo.setNickname(nickname);
                userInfo.setWechatName(nickname);
                userInfo.setSex(sex);
                userInfo.setOpenId(openId);
                if (StringUtils.isNotEmpty(headimgurl)) {
                    HttpURLConnection httpUrl = null;
                    URL iconUrl = null;
                    try {
                        iconUrl = new URL(headimgurl);
                        httpUrl = (HttpURLConnection) iconUrl.openConnection();
                        httpUrl.connect();
                        // 图片生成名称
                        String fileName = "";
                        Date nowDate = new Date();
                        // 格式化时间对象返回字符串
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                        fileName += sdf.format(nowDate);
                        Random random = new Random();
                        String randomCode = "";
                        for (int i = 0; i < 8; i++) {
                            randomCode += Integer.toString(random.nextInt(36), 36);
                        }
                        fileName += randomCode;
                        String virtualPath = "xiangjuwu/application/" + fileName + ".jpg";
                        // item.write(new File(uploadPath + fileName));
                        String result = ossFileService.upload(httpUrl.getInputStream(), virtualPath);
                        System.out.println("存入照片：" + result);
                        userInfo.setIcon(result);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (httpUrl != null) {
                            httpUrl.disconnect();
                        }
                    }
                } else {

                    userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
                }
                if (!createUserInfo(userInfo)) {
                    return null;
                }
            }

            return userInfo;

        } catch (Exception e) {
            logger.error("loginWeiXin", e);
        }
        return null;
    }

    public class LoginException extends Exception {
        public LoginException(String message) {
            super(message);
        }
    }
}

