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

// 开发文档：https://work.weixin.qq.com/api/doc/90000/90135/90664

class ModelEnWechat{
    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 $tagUrl         = "https://qyapi.weixin.qq.com/cgi-bin/tag/list";
    public $tagUserUrl     = "https://qyapi.weixin.qq.com/cgi-bin/tag/get";
    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(){
        $key = okeys::enWeChatAccessToken();
        $access_token = oo::commonOprRedis('common')->get($key);
        if(!empty($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('common')->setex($key,$access_token,7000);
        return $access_token;
    }

    /**
     * 获取标签列表
     * @return mixed
     * Created by: Owen
     * Created on: 2021/1/29 16:28
     */
    public function getTagList(){
        $accessToken = self::getAccessToken();
        $url  = "{$this->tagUrl}?access_token={$accessToken}";
        $ret = file_get_contents($url);
        $ret = json_decode($ret,true);
        if($ret['errcode'] == 0){
            return $ret['taglist'];
        }
    }

    /**
     * 根据标签获取用户
     * @param $tagId
     * @return mixed
     * Created by: Owen
     * Created on: 2021/1/29 16:34
     */
        public function getUserListByTagId($tagId){
        $accessToken = self::getAccessToken();
        $userList = [];
        $url  = "{$this->tagUserUrl}?access_token={$accessToken}&tagid={$tagId}";
        $ret = file_get_contents($url);
        $ret = json_decode($ret,true);
        if($ret['errcode'] == 0){
            foreach ($ret['userlist'] as $u){
                $userList[] = $u;
            }
        }
        return $userList;
    }

    /**
     * 拉取部门信息
     * 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;
            }
        }
    }

    /**
     * 获取部门用户
     * @param array $department
     * @return array
     * Created by: Owen
     * Created on: 2021/1/29 16:26
     */
    public function getUserListByDepartment($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;
    }

    /**
     * 如不限制用户列表或者部门列表就全公司推送
     * @param $message
     * @param array $uidList
     * @param array $department
     * @return bool
     * Created by: Owen
     * Created on: 2019/11/27 18:30
     */
    public function send_wx($message,$uidList = [],$department = [],$tagId = 0){
        $accessToken = self::getAccessToken();
        if(empty($uidList)){
            if(!empty($department)){
                $uidList = array_column(self::getUserListByDepartment($department),'userid');
            }else if($tagId){
                $uidList = array_column(self::getUserListByTagId($tagId),'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{
                return false;
            }
        }
        return false;
    }
    //飞书
    public function send($message,$uidList = [],$department = [],$tagId = 0){
//        $url  = "https://open.feishu.cn/open-apis/bot/v2/hook/f7d734e8-af47-4367-86d1-307124169fc0";
        $url = "https://open.feishu.cn/open-apis/bot/v2/hook/ede82ff8-1f18-40d8-87c9-4fd4169089c6";
        $data = [
            "msg_type"=>"text",
            "content"=>["text"=>"[CC-PHP服务预警]:".$message.'<at user_id="all">所有人</at>']
        ];
        $ret = $this->curlJson($url,json_encode($data));
        var_dump($ret);
    }
}