package com.jeeplus.modules.API.userinfo;


import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.JPushClientUtil;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.iim.entity.LayGroup;
import com.jeeplus.modules.iim.service.LayGroupService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.dao.OfficeDao;
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.service.CompanyService;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.UserService;
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.utils.ErrorCode;
import com.jeeplus.modules.workcompanyinfo.service.CompanyinfoService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import io.swagger.client.model.Group;
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 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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;


/**
 * 管理企业Controller
 * @author zmy
 * @version 2017-04-17
 */
@Controller
@RequestMapping(value = "${frontPath}/userInfo/managecompany")
public class ManageCompanyController extends BaseController{
	@Autowired
	private OfficeDao officeDao;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserofficeService userofficeService;
	@Autowired
	private SystemService systemService;
    @Autowired
    private CompanyinfoService companyinfoService;
    @Autowired
    private PushinfoService pushinfoService;
    @Autowired
    private LayGroupService layGroupService;
    @Autowired
    private WorkStaffBasicInfoService workStaffBasicInfoService;
    @Autowired
    private UserService userService;

    /**
     * 已加入企业
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveGroupId", method=RequestMethod.GET)
    public AjaxJson saveGroupId (String companyId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception{
        AjaxJson j = new AjaxJson();
        Office company = officeService.get(companyId);

       /* Group group = new Group();
        group.groupname(company.getName()+"官方群").desc(company.getName()+"官方群")._public(true).maxusers(1000).approval(true).owner(company.getMaster());
        Object obj = easemobChatGroup.createChatGroup(group);
        JSONObject json = JSONObject.fromObject(obj);

        String groupid = null;
        if(json!=null && !json.get("data").toString().equals("")){
            JSONObject data = JSONObject.fromObject(json.get("data").toString());
            if(data!=null && !data.get("groupid").toString().equals(""))
                groupid = data.get("groupid").toString();
        }*/
        /*
        EasemobInfo easemobImuser = new EasemobInfo();
        easemobImuser.setUserId(company.getMaster());
        easemobImuser.setGroupId(groupid);
        easemobImuser.setJoinStatus("1");
        easemobImuser.setGroupName(company.getName()+"官方群");
        easemobInfoService.save(easemobImuser);*/
        //生成公司二维码，使用公司名
        String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL
                + company.getId() + "/qrcode/";
        FileUtils.createDirectory(realPath);
        String name= company.getId()+".png"; //encoderImgId此处二维码的图片名
        String filePath = realPath + name;  //存放路径
        String content = company.getId()+","+company.getName()+","+company.getMaster()+","+UserUtils.get(company.getMaster()).getName();
        logger.info("encoderQRCode.content="+content);
        TwoDimensionCode.encoderQRCode(content, filePath, "png");//执行生成二维码
        OSSClientUtil ossUtil =new OSSClientUtil();
        company.setCompanyQrcode(request.getContextPath() + Global.USERFILES_BASE_URL
                + company.getId() + "/qrcode/" + name);
        company.setCompanyQrcode(request.getContextPath() + Global.USERFILES_BASE_URL
                + company.getId() + "/qrcode/" + name);
        /*company.setGroupId(groupid);
        company.setGroupName(company.getName() + "官方群");*/
        if (company.getCompanyQrcode()!=null && !company.getCompanyQrcode().equals("")){
            InputStream inputStream = null;
            HttpURLConnection httpURLConnection;
            try {
                URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ company.getCompanyQrcode());
                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 = company.getCompanyQrcode().split("/");
                String qrcodeName = System.currentTimeMillis()+arr[arr.length-1];
                ossUtil.uploadFile2OSS(inputStream, Global.getRqcode(), qrcodeName);
                company.setCompanyQrcode(Global.getAliyunUrl() + "/" + Global.getRqcode() + qrcodeName);
                logger.info("-------companyId  " + companyId);
                logger.info("-------qrcode  "+company.getCompanyQrcode());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                inputStream.close();
            }
        }
        return j;
    }
	/**
	 * 已加入企业
	 */
	@ResponseBody
	@RequestMapping(value = "getUserInfoJoinCompanyList", method=RequestMethod.GET)
	public AjaxJson findJoinCompany (String id,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes)
	{
		AjaxJson j=new AjaxJson();
        User user =UserUtils.get(id);

        String isManager = "1";
        boolean b = UserUtils.isManager();
        if (!b){
            isManager = "0";
        }
		List<Office> companyList = UserUtils.getAllCompany(user);
		HashSet<Office> hs = new HashSet<Office>(companyList);
		List<Map<String,Object>> mapList = Lists.newArrayList();
        Map maps = new HashMap();
        maps.put("isManager",isManager);
        if (hs!=null &&hs.size()!=0) {
            for (Office off : hs) {
                if (!off.getId().equals("1")) {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("companyName", off.getName());
                    map.put("companyLogo", off.getLogo() == null ? "" : off.getLogo());
                    map.put("companyQrcode", off.getCompanyQrcode() == null ? "" : off.getCompanyQrcode());
                    map.put("companyId", off.getId());
                    map.put("master", off.getMaster() == null || UserUtils.get(off.getMaster()) == null ? "" : UserUtils.get(off.getMaster()).getName());
                    map.put("masterId", off.getMaster() == null ? "" : off.getMaster());
                    Useroffice useroffice = new Useroffice();
                    useroffice.setCompanyId(off.getId());
                    useroffice.setStatus("3");
                    List<Useroffice> userofficeList = userofficeService.findList(useroffice);
                    map.put("count", userofficeList.size());
                    map.put("isgly", 0);
                    map.put("glyName", "");
                    for (Useroffice useroffice1:userofficeList){
                        if (useroffice1.getUserId().equals(user.getId())){
                            map.put("officeId", useroffice1.getOfficeId());
                            if (StringUtils.isNotBlank(useroffice1.getOfficeId())){
                                map.put("officeName", officeService.get(useroffice1.getOfficeId()).getName());
                            }else {
                                map.put("officeName","");
                            }
                        }
                    }

                    Role role2 = new Role();
                    role2.setCompany(off);
                    role2.setUser(user);
                    List<Role> roleList2 = roleDao.findList(role2);
                    for (Role role : roleList2) {
                       /* map.put("officeId", role.getOffice().getId());
                        map.put("officeName", role.getOffice().getName());*/
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().endsWith("gly") || role.getEnname().equals("system")) {
                            map.put("isgly", 1);
                            List<User> userList2 = userDao.findUserByRole(role);
                            for (int k = 0; k < userList2.size(); k++) {
                                if (userList2.get(k) != null || userList2.get(k).equals("null")) {
                                    map.put("glyName", userList2.get(k).getName());
                                }
                            }
                            break;
                        }
                    }
                    mapList.add(map);
                }
            }
        }
        maps.put("list",mapList);
		j.put("data",maps);
		j.setErrorCode(ErrorCode.code_1004);
		j.setMsg("获取已加入企业列表成功");
		return j;
	}
	/**
	 * 企业申请记录
	 */
	@ResponseBody
	@RequestMapping(value = "getUserInfoManageCompanyList", method=RequestMethod.GET)
	public AjaxJson findManageCompany (String id,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes)
	{  
		AjaxJson j=new AjaxJson();
		Company company=new Company();

		User user = UserUtils.get(id);		
		company.setTuser(user);	
		List<Company> companyList = companyService.findList(company);
		List<Map<String,Object>> mapList = Lists.newArrayList();
		for(int i = 0; i < companyList.size(); i++){
			Map<String,Object> map = Maps.newHashMap();
			Company com1=companyList.get(i);	
			map.put("companyName", com1.getName());
            map.put("useable", com1.getUSEABLE());
			map.put("companyId", com1.getId());
            String logo = com1.getLogo() == null ? "" :  com1.getLogo();
            map.put("companyLogo", logo);
            Office off=new Office();
            off.setId(com1.getCompanyId());
            //map.put("companyQrcode", off.getCompanyQrcode()==null?"":off.getCompanyQrcode());
			User user2=new User();
			user2.setCompany(off);
			List<User> userList=userDao.findList(user2); 
			map.put("count", userList.size());	
			
			Role role3 = new Role();
			role3.setCompany(off);	
			List<Role> roleList3=roleDao.findList(role3);
			for(Role role : roleList3){	
				if(org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && role.getEnname().endsWith("gly")||role.getEnname().equals("system")){
					List<User> userList3=userDao.findUserByRole(role);
					for (int k = 0; k < userList3.size(); k++) {
						if(userList3.get(k)!=null ||userList3.get(k).equals("null")){
							map.put("glyName", userList3.get(k).getName());	
						}
					}
				}else{
					map.put("glyName", "");	
				}
			}
			mapList.add(map);
		}
		j.put("data",mapList);
        j.setErrorCode(ErrorCode.code_1004);
		return j;
	}
	
	/**
	 * 提醒一下
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "remindApprover", method=RequestMethod.GET)
	public AjaxJson remindApprover (String companyId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes)
	{ 
		AjaxJson j=new AjaxJson();
        try {
            Useroffice companyinfo = new Useroffice();
            companyinfo.setCompanyId(companyId);
            companyinfo.setUserId(UserUtils.getUser().getId());
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DATE, - 3);
            Date now = c.getTime();
            List<Useroffice> companyinfoList = companyinfoService.findListByCompany(companyinfo);
            if (companyinfoList!=null && companyinfoList.size()!=0){
                Useroffice com = companyinfoList.get(0);
                if (com.getStatus().equals("1") || com.getStatus().equals("2")){
                    com.setStatus("6");
                    companyinfoService.update(com);
                }else if (com.getStatus().equals("6")){
                    Date updatedate = com.getUpdateDate();
                    if (now.getTime()<updatedate.getTime()){
                        j.setMsg("提醒失败，提醒间隔为三天");
                        j.setErrorCode(ErrorCode.code_2003);
                        return j;
                    }
                }
                Map extras = new HashMap();
                String title="团队申请";
                Office office = officeService.get(companyId);
                String content=UserUtils.getUser().getName()+"提醒你审批他加入"+office.getName();
                extras.put("type", "2002");
                //该公司下所有的岗位
                List<Role> roleList = systemService.getRoleList("",companyId);
                Role role = new Role();
                if (roleList!=null && roleList.size()!=0){
                    for (Role r :roleList){
                        //要的是管理员
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(r.getEnname()) && r.getEnname().equals("gly")){
                            role = r;
                            break;
                        }
                    }
                }
                //该公司下拥有管理员岗位的所有员工
                List<User> userList = userDao.findUserByRole(role);
                //该公司下拥有管理员岗位的所有员工
                String assignees = "";
                if (userList!=null && userList.size()!=0) {
                    for (User user : userList) {
                        assignees += user.getId()+",";
                    }
                }
                String aliase = assignees==null?"":assignees.substring(0,assignees.length()-1);
                boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, aliase);
                if (b){
                    j.setMsg("提醒成功");
                    j.setErrorCode(ErrorCode.code_1004);
                }else {
                    j.setMsg("推送失败失败");
                    j.setErrorCode(ErrorCode.code_2006);
                    j.setSuccess(false);
                }
            }
        }catch (Exception e){
            j.setMsg("提醒失败");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
        }
		return j;
	}

	/**
	 * 重新申请企业审核信息
	 */
	@ResponseBody
	@RequestMapping(value = "aginJoinCompany", method=RequestMethod.GET)
	public AjaxJson aginJoinCompany(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
        HashMap<String, String> requestMap = findRequestMap(request);

       /* String taskId = requestMap.get("taskId");
        String taskName = requestMap.get("taskName");
        String taskDefKey = requestMap.get("taskDefKey");
        String procInsId = requestMap.get("procInsId");
        String procDefId = requestMap.get("procDefId");
        String flag = requestMap.get("flag");
        String comment = requestMap.get("comment");
        String companyInfoId = requestMap.get("companyInfoId");
        Act act = new Act();
        act.setTaskId(taskId);
        act.setTaskName(taskName);
        act.setTaskDefKey(taskDefKey);
        act.setProcInsId(procInsId);
        act.setProcDefId(procDefId);
        act.setFlag(flag);
        act.setComment(comment);
        j.setMsg("流程审核成功");
        j.setSuccess(true);
        j.setErrorCode(ErrorCode.code_1004);
        Useroffice companyinfo= companyinfoService.get(companyInfoId);
        if (flag.equals("yes")){
            companyinfo.setStatus("1");
        }else {
            companyinfo.setStatus("4");
        }
        companyinfo.setAct(act);
        companyinfoService.auditSave(companyinfo);*/
		/*List<Company> companyList = companyService.getByCompany(companyId);
		if(companyList!=null && companyList.size()!=0){
            Company company = companyList.get(0);
            String id = company.getId();
            company.setUSEABLE("0");
            company.setUpdateBy(UserUtils.getUser());
            company.setUpdateDate(new Date());
            company.setId("");
            companyService.save(company);//保存
            Company company1 = companyService.get(id);
            companyDao.deleteByLogic(company1);
			j.setMsg("重新申请企业审核成功");
		}else {
			j.setMsg("申请公司不存在");
		}*/
        j.setMsg("接口已作废!");
		return j;
	}

	/**
	 * 企业信息详情
	 */
	@ResponseBody
	@RequestMapping(value = "getUserInfoCompanyInfoMap", method=RequestMethod.GET)
	public AjaxJson findCompanyInfo (String companyId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes)
	{  
		AjaxJson j=new AjaxJson();
		Office com= officeDao.get(companyId);		
		Map<String,Object> map = Maps.newHashMap();
        if (com!=null){
            map.put("companyName", com.getName());
            map.put("master", com.getMaster()==null || UserUtils.get(com.getMaster())==null?"":UserUtils.get(com.getMaster()).getName());
            map.put("masterId", com.getMaster()==null ?"":com.getMaster());
            map.put("companyLogo", com.getLogo()==null?"":com.getLogo());
            map.put("companyQrcode", com.getCompanyQrcode()==null?"":com.getCompanyQrcode());
            j.put("data",map);
            j.setErrorCode(ErrorCode.code_1004);
            j.setMsg("获取企业详情成功");
        }else {
            j.setMsg("公司id错误");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_2003);
        }

		return j;
	}
	/**
	 * 退出企业
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value="delOffice",method=RequestMethod.GET)
	public AjaxJson delOffice(String id,String companyId,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes){
		AjaxJson j=new AjaxJson();
        //获取用户信息
        User user = UserUtils.get(id);
        if(user==null ||StringUtils.isBlank(user.getId())){
            j.setMsg("您的用户不存在");
            j.setErrorCode(ErrorCode.code_2003);
            return j;
        }

        WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
        workStaffBasicInfo.setCompany(new Office(companyId));
        workStaffBasicInfo.setUserId(user.getId());
        Integer count = workStaffBasicInfoService.getByCompany(workStaffBasicInfo);
        if (count == 0){
            String str = userService.deleteUserByCompany(user,new Office(companyId),"");
            str.replace("移除用户信息成功","退出企业成功");
            j.setMsg(str);
        }else{
            j.setMsg("退出企业失败,不能退出企业");
        }
		/*Company coms = new Company();
        coms.setUserId(id);
        coms.setCompanyId(companyId);
        List<Role> roleList = companyService.getUserRoleComManager(coms);
        if(roleList != null&&roleList.size() > 0){
            List<String> roleComList = companyService.getUserRoleManager(coms);
            int num = 0;
            for (String role: roleComList) {
                if(roleList.get(0).getId().equals(role)) {
                    num++;
                    if(num>1){
                        break;
                    }
                }
            }
            if( num == 1 ){//一个管理员
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_1005);
                j.setMsg("公司只有您一位管理员,您不能退出企业");
                return j;
            }
        }
		//公司信息
		Office com=new Office();
		com.setId(companyId);
		//岗位信息
		Role role=new Role();
		role.setCompany(com);
		role.setUser(user);
		//用户获取公司下岗位信息
		List<Role> roleLista = roleDao.findList(role);
		for(Role r : roleLista){
		    //根据用户岗位和用户判断
            systemService.updateUserToRole(r,user);
		}
        if (user.getCompany().getId().equals(companyId)){
            Role role1 = new Role();
            role1.setUser(user);
            List<Role> rolelist=roleDao.findList(role1);
            if (rolelist!=null && rolelist.size()!=0){
                String officeId = rolelist.get(0).getOffice().getId();
                String company = rolelist.get(0).getCompany().getId();
                systemService.saveCurrentCompanyById(id,company,officeId);
            }
            companyService.deleteWorkAppShow(companyId,id);
        }
        Useroffice companyinfo = new Useroffice();
        companyinfo.setCompanyId(companyId);
        companyinfo.setUserId(id);
        List<Useroffice> companyinfoList = companyinfoService.findListByCompany(companyinfo);
        if (companyinfoList!=null && companyinfoList.size()!=0){
            for (Useroffice info:companyinfoList){
                info.setDelFlag("1");
                companyinfoService.save(info);
                Pushinfo pushinfo = new Pushinfo();
                pushinfo.setPushId(info.getId());
                List<Pushinfo> pushinfos = pushinfoService.findList(pushinfo);
                if (pushinfos!=null && pushinfos.size()!=0){
                    pushinfoService.updateDelflagByPushId(info.getId(),"1");
                }
            }
        }
        Office office = officeService.get(companyId);
        if (StringUtils.isNotBlank(office.getGroupId())){
            LayGroup layGroup = layGroupService.getNoOwner(office.getGroupId());
            if (layGroup!=null && !layGroup.getCreateBy().getId().equals(user.getId())){
                layGroupService.deleteGroupUser(layGroup,user.getId());
            }
        }*/
        /*String groupId = office.getGroupId();
        String userId = user.getId();
        Object result = easemobChatGroup.removeSingleUserFromChatGroup(groupId, userId);
        if (result!=null){
            logger.info(result.toString());
        }*/
        /*EasemobInfo e = new EasemobInfo();
        e.setUserId(userId);
        e.setJoinStatus("2");
        e.setGroupId(groupId);
        e.setDelFlag("1");
        easemobInfoService.deleteByUserIdAndGroupId(e);*/
		return j;
	}
}