<?php
namespace App\Http\Controllers;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class LdapController extends Controller
{
    public $host = '172.20.100.201';
    public $dn = 'ou=Users_hoto,dc=hoto,dc=test';
    public $username = 'hoto\hcmadmin';
    public $password = 'hcmadmin123';
	public $provider=null;
	public function __construct()
	{
		$ad = new \Adldap\Adldap();
		$config = [
			'hosts'=>[$this->host],
			'base_dn'=>$this->dn,
			'username' => $this->username,
			'password' =>$this->password
		];
		$ad->addProvider($config);
		$this->provider = $ad->connect();
	}
    public function handle(Request $request)
    {

		$data = $request->all();
        try{
            Log::info(json_encode($data));
//		//新增人员数据格式:
//		$data = [
//			'operation_type'=>'emp',
//			'operation'=>"add",
//			'data'=>['jiangbowen9090','jiangbowen90912']
//		];
//        //编辑人员数据格式:
//        $data = [
//            'operation_type'=>'emp',
//            'operation'=>"edit",
//            'data'=>['jiangbowen9090'=>'jiangbowen9090et','jiangbowen90912']
//        ];
//        //删除人员格式
//        $data = [
//            'operation_type'=>'emp',
//            'operation'=>"del",
//            'data'=>['jiangbowen90912']
//        ];
//        //添加部门数据格式
//        $data = [
//            'operation_type'=>'dept',
//            'operation'=>'add',
//            'data'=>['产品技术中心2/测试部57']
//        ];
        //编辑部门数据格式
//        $data = [
//            'operation_type'=>'dept',
//            'operation'=>'edit',
//            'data'=>['产品技术中心2/测试部2'=>'产品技术中心/测试部35']
//        ];
        //删除部门数据格式
//        $data = [
//            'operation_type'=>'dept',
//            'operation'=>'del',
//            'data'=>['产品技术中心2/测试部35']
//        ];
            if(!empty($data['data']))//转换数组
            {
                $data['data']=json_decode($data['data'],true);
            }
		if ($data['operation_type'] == 'emp') {
			if ($data['operation'] == 'add') {
				$this->saveEmp($data);
			} else if($data['operation'] == 'edit'){
				$this->editEmp($data['data']);
			} else if ($data['operation'] == 'del'){
				$this->delEmp($data['data']);
			}
		} else if ($data['operation_type'] == 'dept') {
			if ($data['operation'] == 'add') {
				$this->saveDept($data['data']);
			} else if ($data['operation'] == 'edit') {
                $this->editDept($data['data']);
			} else if ($data['operation'] == 'del') {
				$this->delDept($data['data']);
			}
		}
         $res=   ['status' => true,'msg'=>'success'];
     } catch (\Exception $e) {
         $res= self::recordLog($e);
     }
        $res['data']=$data;
        Log::info(json_encode($res));
        return   response()->json($res);

    }

    //记录异常出来的错误
    public static function recordLog($e) {
        $filename = 'ldap/'.date('Ymd').'.log';
        $content = "time:".date("Y-m-d H:i:s").trans('service.20700').":".$e->getMessage().'所在文件:'.$e->getFile().'行号:'.$e->getLine();//发生异常
        Storage::append($filename, $content);
        return ['status' => false, 'msg' => $e->getMessage().$e->getMessage().'所在文件:'.$e->getFile().'行号:'.$e->getLine()];

    }


    public function saveEmp($data)
    {

    	if (empty($data)) return;

    	$dept_name='';

        $ou_str='';
        if(!empty($data['deptName'])){
            $ous = [];
            $arr = explode('/',$data['deptName']);
            foreach ($arr as $key => $v) {
                $ous[] = "ou={$v}";
            }
            $ou_str = implode(',',array_reverse($ous));
            $dept_name=$ou_str;
        }
    	foreach ($data['data'] as $key => $users) {
            $value=$users['fullName']?$users['fullName']:'';;
            $mobileNumber=$users['mobileNumber']?$users['mobileNumber']:'';
            $company_email=$users['company_email']?$users['company_email']:'';
            $account=$users['account']?$users['account']:'';
            $first_name=$users['first_name']?$users['first_name']:'';
            $last_name=$users['last_name']?$users['last_name']:'';

    		$entry=["cn"=>"{$value}"];
			$user=$this->provider->make()->user($entry);
			//$user->setDn("cn={$value},ou='.$dept_name.',ou=Users_hoto,dc=hoto,dc=test"); //在IT发展部新增人员
            $user->setDn("cn={$value},{$dept_name},ou=Users_hoto,dc=hoto,dc=test"); //在IT发展部新增人员
			$user->setAccountName("$value");
			$user->setCommonName("$value");
			//$user->setPassword("iiooii");

			//属性设置
            //登陆状态默认启用 544默认启用 66080密码永不过期
            $user->setUserAccountControl(544);
            //邮箱
            if(!empty($company_email)) {
                $user->setAttribute('mail', $company_email);
            }
            //联系方式
            if(!empty($mobileNumber)) {
                $user->setAttribute('telephoneNumber', $mobileNumber);
            }
            //姓
            if(!empty($first_name)) {
                $user->setAttribute('sn', $first_name);
            }
            //名
            if(!empty($last_name)) {
                $user->setAttribute('givenName', $last_name);
            }
            //显示名称
            $user->setAttribute('displayName',$value);
            //登陆账号
            if(!empty($account)) {
                $user->setAttribute('sAMAccountName', $account);
            }
			if($user->create()){
				Log::info("{$value} created success....");
			} else {
				Log::info("{$value} created failed....");
			}
    	}
    }

    public function editEmp($data)
    {
    	if (empty($data)) return;
    	foreach ($data as $key => $value) {
    	    if (is_numeric($key)) continue;
    		$user=$this->provider->search()->find($key);
    		if ($user->exists) {
    			$user->rename("cn=$value");
                Log::info("{$key} edit success....");
    		}else{
                Log::info("{$key} not exist....");
            }
    	}
    }

    public function delEmp($data)
    {
    	if (empty($data)) return;
    	foreach($data as $key=>$value){
	    	$user=$this->provider->search()->find($value);
			if ($user->exists) {
				$user->delete();
                Log::info("{$value} delete success....");
			}else{
                Log::info("{$value} delete success....");
            }
    	}
    }


    public function saveDept($data)
    {
    	/**
    	 *数据格式
         *$data = ['一级部门/二级部门/三级部门']
         */
    	if (empty($data)) return;
    	foreach ($data as $key => $value) {
    		$depts = [];
    		$arr = explode('/',$value);
    		foreach ($arr as $key => $v) {
    				
    			// var_dump($result);
    			$depts[] = $v;
    			$depts2=array_reverse($depts);
				foreach ($depts2 as $key => $value) {
					$ous[] = "ou={$value}";
				}
				$ou_str = implode(',',$ous);
				$result=$this->provider->search()->setDn("$ou_str,ou=Users_hoto,dc=hoto,dc=test")->find($v);
    			// $dn = $result->getDnBuilder();->ous()
    			// $dn->addOu("$ou_str,ou=department,dc=test,dc=com");
				// var_dump($ou_str);die;
    			// $result->setDn();
    			if (is_null($result)) {
    				$this->generateOu($v,$depts);
    			}
    		}
    	}
    }

    public function generateOu($value,$depts)
    {
    	$entry=[
			"name"=>"{$value}"
		];
		$ou=$this->provider->make()->ou($entry);
		$depts=array_reverse($depts);
		foreach ($depts as $key => $value) {
			$ous[] = "ou={$value}";
		}
		$ou_str = implode(',',$ous);
		$ou->setDn("$ou_str,ou=Users_hoto,dc=hoto,dc=test");
		if($ou->create()){
			Log::info("{$value} created success....");
		} else {
			Log::info("{$value} created failed....");
		}
    }


    public function delDept($data)
    {
    	if (empty($data)) return;
    	foreach ($data as $key => $value) {
    			$depts = explode('/',$value);
    			$depts2=array_reverse($depts);
				foreach ($depts2 as $v) {
					$ous[] = "ou={$v}";
				}
				$ou_str = implode(',',$ous);
				$result=$this->provider->search()->setDn("$ou_str,ou=IT发展部,ou=Users_hoto,dc=hoto,dc=test")->find($depts[count($depts)-1]);
    		if (is_null($result)) return;
    		if ($result->exists) {
    			$result->delete();
                Log::info("{$value} delete success....");
    		}else{
                Log::info("{$value} not exist....");
            }
    	}
    }


    public function editDept($data)
    {
    	if (empty($data)) return;
    	foreach ($data as $key => $value) {
    		if ($key === $value) continue;
     		$depts=explode('/',$key);
     		$hou_depts = explode('/',$value);
     		$depts=array_reverse($depts);
     		$hou_depts=array_reverse($hou_depts);
			 foreach ($depts as $k => $v) {
			 	$ous[] = "ou={$v}";
			 }
			 foreach ($hou_depts as $k => $v) {
			 	$hou_ous[] = "ou={$v}";
			 }
			$ou_str = implode(',',$ous);
//			 var_export($depts[0]);
    		$result=$this->provider->search()->ous()->find($depts[0]);
//    		var_export($result);die;
    		$result->setDn("$ou_str,ou=Users_hoto,dc=hoto,dc=test");
//    		 var_dump($result);die;
    		if ($result->exists) {
    			$result->rename("ou=".$hou_depts[0]);
                Log::info("{$value} edit success....");
    		} else{
                Log::info("{$value} not exist....");
            }
    	}
//    	$this->saveDept($handleData);
    }

    /**
     * 输出调试函数
     *
     * @param array $args
     */
    function  pr($args = array()) {
        $escape_html = true;
        $bg_color = '#EEEEE0';
        $txt_color = '#000000';
        $args = func_get_args();

        foreach($args as $arr){
            echo sprintf('<pre style="background-color: %s; color: %s;">', $bg_color, $txt_color);
            if($arr) {
                if($escape_html){
                    echo htmlspecialchars( print_r($arr, true) );
                }else{
                    print_r($arr);
                }
            }else {
                var_dump($arr);
            }
            echo '</pre>';
        }
    }




    public function getData()
    {

        try {
            $data=[];
//            $data=['人力资源部/Users_Hoto','IT发展部/Users_Hoto','工程经济专业/Users_Hoto','项目管理部/Users_Hoto','EPC项目管理/项目管理部/Users_Hoto',
//                '档案出版管理/项目管理部/Users_Hoto','产品技术中心/IT发展部/Users_Hoto','测试部/产品技术中心/IT发展部/Users_Hoto'];
            $result = $this->provider->search()->ous()->get();
            $result = json_decode(json_encode($result), true);
            $key=0;
            foreach ($result as $value) {
                $new_distinguishedname_arr = [];
                $distinguishedname = $value['distinguishedname'][0];
                $distinguishedname_arr = explode(',', $distinguishedname);
                foreach ($distinguishedname_arr as $k => $v) {
                    $vv = explode('=', $v);
                    if ($vv[0] === 'DC') continue;
                    $new_distinguishedname_arr[] = $vv[1];
                }
                if ($new_distinguishedname_arr) {
                    $new_distinguishedname_str = implode('/', $new_distinguishedname_arr);
                }
                //echo $new_distinguishedname_str . "....\r\n";
                $data[$key]=$new_distinguishedname_str;
                $key++;
            }
            $res=   ['status' => true,'msg'=>'success'];
            //测试部/产品技术中心2/IT发展部

        } catch (\Exception $e) {
            $res = self::recordLog($e);
        }
        $res['data']=$data;
        Log::info(json_encode($res));
        return   response()->json($res);
    }

}