package com.jeeplus.modules.sys.service;


import com.easemob.server.example.api.impl.EasemobIMUsers;
import com.google.common.base.Strings;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.utils.DateUtils;
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.iim.entity.LayGroup;
import com.jeeplus.modules.iim.service.LayGroupService;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Company;
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.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.tools.utils.TwoDimensionCode;
import com.jeeplus.modules.workcompanyinfo.service.CompanyinfoService;
import io.swagger.client.model.NewPassword;
import io.swagger.client.model.Nickname;
import io.swagger.client.model.RegisterUsers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;




@Service
@Transactional()
public class UserService extends BaseController {

    @Autowired
    private UserofficeService userofficeService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CompanyService companyService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private LayGroupService layGroupService;
    @Autowired
    private CompanyinfoService companyinfoService;

    @Autowired
    private RoleDao roleDao;

    public User get(String userId){
        return userDao.get(userId);
    }

    String password;

    public boolean save(User user, HttpServletRequest request, MultipartFile this_upload_files) throws IOException {
        //UserUtils.clearCache();
        modifyPassword(user);
        return saveUser(user,request,this_upload_files);
    }

    public boolean save(User user, HttpServletRequest request) throws IOException {
        //UserUtils.clearCache();
        modifyPassword(user);
        return saveUser(user,request,null);
    }

    private void modifyPassword(User  user){
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            password = SystemService.encrypeString(user.getNewPassword());
            user.setPassword(SystemService.entryptPassword(password));
            user.setPasswordRemake(password);
        }else{
            //如果在修改用户时没有输入密码，应该保持原来密码不变
            //password = SystemService.encrypeString(user.getPassword());

        }
    }
    @Transactional(readOnly = false)
    public boolean saveUser(User user,HttpServletRequest request,MultipartFile this_upload_files) throws IOException {
        User loginUser = UserUtils.getUser();
        if(!"1".equals(loginUser.getCompany().getId())){
            user.setCompany(loginUser.getCompany());
            user.setComId(loginUser.getCompany().getId());
        }
        Boolean b = false;
        //生成用户二维码，使用登录名
        if (StringUtils.isBlank(user.getId())) {
            b = true;
            String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + user.getId() + "/qrcode/";
            FileUtils.createDirectory(realPath);
            String name = user.getId() + ".png"; //encoderImgId此处二维码的图片名
            String filePath = realPath + name;  //存放路径
            TwoDimensionCode.encoderQRCode(user.getLoginName(), filePath, "png");//执行生成二维码
            user.setQrCode(request.getContextPath() + Global.USERFILES_BASE_URL + user.getId() + "/qrcode/" + name);
            if (user.getQrCode() != null && !user.getQrCode().equals("") && user.getQrCode().contains("userfiles")) {
                String qrcode = user.getQrCode().replace("|", "");
                InputStream inputStream = null;
                HttpURLConnection httpURLConnection;
                try {
                    URL url = new URL(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + qrcode);
                    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();
                }
            }
        }
        if (this_upload_files != null && !this_upload_files.isEmpty() &&this_upload_files.getSize()>0){
            String oldPhoto = user.getPhoto();
            String key = "";
            if(StringUtils.isNotBlank(oldPhoto)){
                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[] arr = oldPhoto.split(cons+"/");
                key = arr[1];
            }
            try {
                OSSClientUtil ossUtil1 =new OSSClientUtil();
                if(StringUtils.isNotBlank(key)) {
                    ossUtil1.deleteSingleObject(key);
                }
                OSSClientUtil ossUtil2 =new OSSClientUtil();
                String filepath= ossUtil2.uploadFile2OSS(this_upload_files, "photo");
                user.setPhoto(filepath);
                user.setDefaultPhoto("1");
            }catch (Exception e){
                logger.error("oss删除/上传失败！");
            }finally {

            }

        }else{
            user.setDefaultPhoto("0");
            String userName = user.getName();
            if(StringUtils.isNotBlank(userName) && "0".equals(user.getDefaultPhoto())){
                long time = System.currentTimeMillis();
                String realPathPhoto = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time+ "/img/";
                FileUtils.createDirectory(realPathPhoto);
                String picNamePhoto =time + ".png"; //
                String filePathPhoto = realPathPhoto + picNamePhoto; // 存放路径
                WordToPic.TextToPic(userName.substring(userName.length()-2>0?userName.length()-2:0,userName.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);
                        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();
                            }
                        }
                    }
                }
            }
        }
        systemService.saveUserInfo(user);
        Object officeId = UserUtils.getCache("selectOffice");
        if (UserUtils.getUser().getId().equals(user.getId()) &&officeId!=null && !officeId.toString().equals(user.getOffice().getId())){
            UserUtils.removeCache("selectOffice");
            UserUtils.putCache("selectOffice", user.getOffice().getId());
        }
        if (!loginUser.getComId().equals("1")){
            Role comRole =  systemService.getRoleByEnname(loginUser.getCompany().getId(), user.getOffice(),"yg");
            if (comRole != null && !comRole.getCompany().getId().equals("1")){
                Useroffice useroffice = new Useroffice();
                useroffice.setUserId(user.getId());
                useroffice.setStatus("3");
                useroffice.setMaster(UserUtils.getUser().getId());
                useroffice.setCompanyId(loginUser.getCompany().getId());
                useroffice.setOfficeId(comRole.getOffice().getId());
                List<Useroffice> listOffice = userofficeService.findList(useroffice);
                if(listOffice==null || listOffice.size()==0){
                    userofficeService.save(useroffice);
                }else {
                    Useroffice oldUseroffice = listOffice.get(0);
                    oldUseroffice.setOfficeId(user.getOffice().getId());
                    userofficeService.save(oldUseroffice);
                }
            }
            if (b) {
                systemService.assignUserToRole(comRole, user,0);
            }
        }else {
            systemService.addUserToRole(user);
        }

        /*boolean bool = systemService.outUserInRole(new Role("1"), user);
        if (bool){
            systemService.saveCurrentCompanyById(user.getId(), user.getCompany().getId(), user.getOffice().getId());
        }
        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
            List<Role> roles = (List<Role>)UserUtils.getCache("selectRole");
            UserUtils.clearCache();
            UserUtils.putCache("selectRole", roles);
            //UserUtils.getCacheMap().clear();
        }*/
        return true;


    }
    /**
     * 依据部门查询用户的岗位
     * @param officeId
     * @return
     */
    public List queryRole(String officeId){
        return userDao.queryRole(officeId);
    }

    public User findUniqueByProperty(String name, String value) {
        return userDao.findUniqueByProperty(name,value);
    }

    public void updateOfficeById(User user) {
        userDao.updateUserInfo(user);
    }
    public String deleteUserByCompany(User user,Office com,String id) {
        String str = "";
        String content = "";
        Useroffice companyinfo = new Useroffice();
        String userId = user.getId();
        if(StringUtils.isNotBlank(id)) {
            content = "用户"+user.getName()+"退出企业";
            companyinfo = companyinfoService.get(id);
        }else {
            content = "您已被移出企业，请重新登录";
            companyinfo = companyinfoService.getByCompanyAndUserId(user.getId(),com.getId());
        }
        Company company = new Company();
        company.setCompanyId(companyinfo.getCompanyId());//公司id
        company.setUserId(userId);//用户id
        company.setId(companyinfo.getId());//基本信息id
        /**
         * 判断当前用户是不是管理员，
         * 如果是判断用户所在公司下有几个管理员，如果有一个管理员拒绝退出企业，多个可以退出企业！！
         */
        //1、查询当前用户在当前公司所在的岗位是不是管理员
        List<Role> roleList = companyService.getUserRoleComManager(company);
        if(roleList != null&&roleList.size() > 0){//是管理员
            // 2、查询当前公司下所有员工对应的岗位
            List<String> roleComList = companyService.getUserRoleManager(company);
            //3、查询员工所对应的岗位有几个是管理员
            int num = 0;
            for (String role: roleComList) {
                if(roleList.get(0).getId().equals(role)) {
                    num++;
                    if(num>1){
                        break;
                    }
                }
            }
            if( num > 1 ){  //多个管理员
                companyService.delete(company,2);
                Office office = officeService.get(companyinfo.getCompanyId());
                if (StringUtils.isNotBlank(office.getGroupId())) {
                    LayGroup layGroup = layGroupService.getNoOwner(office.getGroupId());
                    if (layGroup!=null && layGroup!=null && !layGroup.getCreateBy().getId().equals(companyinfo.getUserId())) {
                        layGroupService.deleteGroupUser(layGroup, companyinfo.getUserId());
                    }
                }
                str = "移除用户信息成功";
            }else if( num == 1 ){
                return "公司只有您一位管理员,您不能退出企业";
            }
        }else{//普通用户
            String data = companyService.delete(company,2);
            if(data==null||"".equals(data) || "Success".equals(data)){
                Office office = officeService.get(companyinfo.getCompanyId());
                if (StringUtils.isNotBlank(office.getGroupId())) {
                    LayGroup layGroup = layGroupService.getNoOwner(office.getGroupId());
                    if (layGroup!=null && !layGroup.getCreateBy().getId().equals(companyinfo.getUserId())) {
                        layGroupService.deleteGroupUser(layGroup, companyinfo.getUserId());
                    }
                }
                str = "移除用户信息成功";
            }else if("Invalid".equals(data)){
                //无效数据的原因是用户表和用户公司关联表数据不统一
                str = "Invalid Data";
            }
        }
        if(StringUtils.isBlank(id)) {
            UserUtils.pushIm(user.getId(), content);
        }else {
            //该公司下所有的岗位
            List<Role> roles = systemService.getRoleList("", companyinfo.getCompanyId());
            Role role = new Role();
            if (roles != null && roles.size() != 0) {
                for (Role r : roles) {
                    //要的是管理员
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(r.getEnname()) && r.getEnname().equals("gly")) {
                        role = r;
                        break;
                    }
                }
            }
            //该公司下拥有管理员岗位的所有员工
            List<User> userList = userDao.findUserByRole(role);
            for (User user1 : userList) {
                UserUtils.pushIm(user1.getId(), content);
            }
        }
        User user1 = UserUtils.getUser();
        if (user1.getId().equals(user.getId())){
            if (com.getId().equals(user1.getComId())) {
                UserUtils.clearCache();
                systemService.removeSession(UserUtils.getUser());
            }
        }else {
            UserUtils.clearCache(UserUtils.get(user.getId()));
            systemService.removeSession(user);
        }
        return str;
    }
    public Integer userCount(String officeId){
        return userDao.userCount(officeId);
    };
}
