<?php
class TCSync {
    const user_url = 'http://218.1.67.130:8988/api/NanTongWechat/GetPropertyConsultant?cityId=1';
    public static function user_sync(){
        $response = wp_remote_post( TCSync::user_url );
        $res = array(
            'code' => 200,
            'msg' => "success"
        );
        //判断请求是否成功
        if( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ){
            $res['code'] = 500;
            $res['msg'] = "get user info error";
        }else{
            set_time_limit(0) ;
            //获取请求内容
            $result = wp_remote_retrieve_body( $response );
            $result = json_decode($result,true);
            foreach($result['data'] as $item){
                if(username_exists($item['WorkNum'])){
                    $user = get_user_by( "login", $item['WorkNum'] );
                    $userdata = array(
                        'ID' => $user->data->ID,
                        'display_name' => $item['Name']
                    );
                    $user_id = wp_update_user( $userdata ) ;
                }else{
                    $userdata = array(
                        'user_login'  =>  $item['WorkNum'],
                        'user_pass'   =>  $item['WorkNumAndID'],  // When creating an user, `user_pass` is expected.
                        'role' => 'editor',
                        'wp_user_level' => 7,
                        'display_name' => $item['Name']
                    );
                    $user_id = wp_insert_user( $userdata ) ;
                }
                if(is_numeric($user_id) && !is_null($item['ImageUrl'])){
                    update_user_meta( $user_id, "tc_image", $item['ImageUrl'] );
                }
            }
        }
        return $res;
    }
} 