<?php
/**
 * enWeChat.php
 * Created by: Owen
 * Created on: 2019/11/26 20:24
 *
 */

class EnWechatModel{
    public $access_token = '';
    public $corpid     = "wwab4cd61391c809f9";
    public $corpsecret = "dFohBcprezGR1qcWURjOgTIYuAm2jmLtgnYkhckgA0I";
    public $agentid    = 1000008;
    public $uidList    = ['luokunpeng'];
    public $sendUrl    = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
    public $accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    public $departmentUrl  = "https://qyapi.weixin.qq.com/cgi-bin/department/list";
    public $userUrl    = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist";
    public $userDetailUrl  = "https://qyapi.weixin.qq.com/cgi-bin/user/list";
    public function curlJson($url, $dataJson){
        $ch = curl_init($url); //请求的URL地址
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);//$data JSON类型字符串
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($dataJson)));
        $data = curl_exec($ch);
        return $data;
    }

    /**
     * 企业微信获取 accessToken
     * Created by: Owen
     * Created on: 2019/11/25 20:23
     */
    public function getAccessToken(){
        if(!empty($this->access_token)){
            return $this->access_token;
        }
        $key = okeys::enWeChatAccessToken();
        $access_token = oo::commonOprRedis('games')->get($key);
        if(!empty($access_token)){
            $this->access_token = $access_token;
            return $access_token;
        }

        $url  = "{$this->accessTokenUrl}?corpid={$this->corpid}&corpsecret={$this->corpsecret}";
        $data = file_get_contents($url);
        $data = json_decode($data,true);
        $access_token = $data['access_token'];
        oo::commonOprRedis('games')->setex($key,$access_token,7000);
        return $access_token;
    }

    /**
     * 拉取部门信息
     * Created by: Owen
     * Created on: 2019/11/27 17:57
     */
    public function getDepartmentList($departmentId = []){
        $accessToken = self::getAccessToken();
        $url  = "{$this->departmentUrl}?access_token={$accessToken}";
        $ret = file_get_contents($url);
        $ret = json_decode($ret,true);
        if($ret['errcode'] == 0){
            if(empty($departmentId)){
                return $ret['department'];
            }else{
                $out = [];
                foreach ($ret['department'] as $row){
                    if(in_array($row['id'],$departmentId)){
                        $out[] = $row;
                    }
                }
                return $out;
            }
        }
    }

    public function getUserList($department = []){
        $accessToken = self::getAccessToken();
        $userList = [];
        $department = self::getDepartmentList($department);
        foreach ($department as $row){
            $url  = "{$this->userUrl}?access_token={$accessToken}&department_id={$row['id']}";
            $ret = file_get_contents($url);
            $ret = json_decode($ret,true);
            if($ret['errcode'] == 0){
                foreach ($ret['userlist'] as $u){
                    $userList[] = $u;
                }
            }
        }
        return $userList;
    }

    public function getUserByMobile($mobile){
        $cacheKey = okeys::EnWechatMobile($mobile);
        $cache    = oo::commonOprRedis('games')->get($cacheKey);
        if($cache){
           return json_decode($cache,true);
        }
        $accessToken = self::getAccessToken();
        $department = self::getDepartmentList();
        foreach ($department as $row){
            $url  = "{$this->userDetailUrl}?access_token={$accessToken}&department_id={$row['id']}";
            $ret = file_get_contents($url);
            $ret = json_decode($ret,true);
            if($ret['errcode'] == 0){
                foreach ($ret['userlist'] as $u){
                    if($u['mobile'] == $mobile){
                        oo::commonOprRedis('games')->setex($cacheKey,json_encode($u),7*24*60*60);
                        return $u;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 如不限制用户列表或者部门列表就全公司推送
     * @param $message
     * @param array $uidList
     * @param array $department
     * @return bool
     * Created by: Owen
     * Created on: 2019/11/27 18:30
     */
    public function send($message,$uidList = [],$department = []){
        $accessToken = self::getAccessToken();
        if(empty($uidList)){
            $uidList = array_column(self::getUserList($department),'userid');
            $uidList = array_unique($uidList);
        }
        if(!empty($accessToken) && !empty($uidList)) {
            $message = [
                'touser' =>implode('|',$uidList),
                'msgtype'=>"text",
                'agentid'=>$this->agentid,
                'text'   => [
                    'content' =>$message
                ],
                'safe'   => 0
            ];
            $sendUrl = "{$this->sendUrl}?access_token={$accessToken}";
            $response = $this->curlJson($sendUrl, json_encode($message));
            $response = json_decode($response,true);
            if($response['errcode'] == 0){
                return true;
            }else{
                die(json_encode(['code'=> -3, 'msg' => '发送验证码失败','res' => $response]));
                return false;
            }
        }
        die(json_encode(['code'=> -3, 'msg' => '发送验证码失败','token' => $accessToken, 'uidList' => $uidList]));
        return false;
    }
}