<?php
class TCSync {
    const user_url = 'http://218.1.67.130:8988/api/NanTongWechat/GetPropertyConsultant?cityId=1';
    const other_url = 'http://218.1.67.130:8988/api/NanTongWechat/GetCommonPlate?radomPla=123456';
    const organization_url = 'http://218.1.67.130:8988/api/NanTongWechat/GetOrgnaziTion?radomOrg=123456';

    const DIC_CITY_TABLE = 'dic_city';
    const DIC_ROOM_TABLE = 'dic_room';
    const DIC_BUILDPROPERTY_TABLE = 'dic_buildproperty';
    const DIC_AREA_TABLE = 'dic_area';
    const DIC_UNITPRICERANGE_TABLE = 'dic_unitpricerange';
    const DIC_TOTALPRICE_TABLE = 'dic_totalprice';
    const TOSPUR_ORGANIZATION_TABLE = 'tospur_organization';

    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)){
                    if(!is_null($item['ImageUrl']))
                        update_user_meta( $user_id, "tc_image", $item['ImageUrl'] );
                    update_user_meta( $user_id, "tc_cityId", $item['CityId'] );
                }
            }
        }
        return $res;
    }

    public static function other_sync(){
        global $wpdb;
        $response = wp_remote_post( TCSync::other_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 info error";
        }else{
            set_time_limit(0) ;
            //获取请求内容
            $result = wp_remote_retrieve_body( $response );
            $result = json_decode($result,true);
            //print_r($result['data']['CityList']);
            foreach($result['data']['CityList'] as $item){
                $wpdb->query(TCSync::create_insert_update_sql(TCSync::DIC_CITY_TABLE,$item,array('plateId')));
                //print_r(TCSync::create_insert_update_sql(TCSync::CITY_TABLE,$item,array('plateId')));print_r("<br />");
            }

            foreach($result['data']['RoomStyle'] as $item){
                $wpdb->query(TCSync::create_insert_update_sql(TCSync::DIC_ROOM_TABLE,$item,array('id')));
                //print_r(TCSync::create_insert_update_sql(TCSync::DIC_ROOM_TABLE,$item,array('id')));print_r("<br />");
            }

            foreach($result['data']['BulidProperty'] as $item){
                $wpdb->query(TCSync::create_insert_update_sql(TCSync::DIC_BUILDPROPERTY_TABLE,$item,array('id')));
                //print_r(TCSync::create_insert_update_sql(TCSync::DIC_BUILDPROPERTY_TABLE,$item,array('id')));print_r("<br />");
            }

            foreach($result['data']['AreaRange'] as $item){
                $wpdb->query(TCSync::create_insert_update_sql(TCSync::DIC_AREA_TABLE,$item,array('id'),array('maxValue'=>'max','minValue'=>'min')));
                //print_r(TCSync::create_insert_update_sql(TCSync::DIC_AREA,$item,array('id'),array('maxValue'=>'max','minValue'=>'min')));print_r("<br />");
            }

            foreach($result['data']['TotalPrice'] as $item){
                $wpdb->query(TCSync::create_insert_update_sql(TCSync::DIC_TOTALPRICE_TABLE,$item,array('id'),array('maxValue'=>'max','minValue'=>'min')));
                //print_r(TCSync::create_insert_update_sql(TCSync::DIC_AREA,$item,array('id'),array('maxValue'=>'max','minValue'=>'min')));print_r("<br />");
            }

            foreach($result['data']['UnitPriceRange'] as $item){
                $wpdb->query(TCSync::create_insert_update_sql(TCSync::DIC_UNITPRICERANGE_TABLE,$item,array('id'),array('maxValue'=>'max','minValue'=>'min')));
                //print_r(TCSync::create_insert_update_sql(TCSync::DIC_AREA,$item,array('id'),array('maxValue'=>'max','minValue'=>'min')));print_r("<br />");
            }

        }
    }

    public static function organization_sync(){
        global $wpdb;
        $response = wp_remote_post( TCSync::organization_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 info error";
        }else{
            set_time_limit(0) ;
            $result = wp_remote_retrieve_body( $response );
            $result = json_decode($result,true);
            foreach($result['data'] as $item){
                $wpdb->query(TCSync::create_insert_update_sql(TCSync::TOSPUR_ORGANIZATION_TABLE,$item,array('Id')));
                //print_r(TCSync::create_insert_update_sql(TCSync::DIC_AREA,$item,array('id'),array('maxValue'=>'max','minValue'=>'min')));print_r("<br />");
            }
        }
    }

    private static function create_insert_update_sql($table,$item,$primary=array(),$change=array()){
        $keys = "";
        $values = "";
        $update = "";
        foreach($item as $key => $value){
            if(strlen($keys)>0)
                $keys .= ",";
            $keys .= $change[$key]?$change[$key]:$key;
            if(strlen($values)>0)
                $values .= ",";
            $value = is_numeric($value)?$value:"'".$value."'";
            $values .= $value;
            if(!in_array($key,$primary)){
                if(strlen($update)>0)
                    $update .= ",";
                $update .= ($change[$key]?$change[$key]:$key)."=".$value;
            }
        }
        $sql = "insert into ".$table."(".$keys.") values(".$values.") ON DUPLICATE KEY UPDATE ".$update;
        return $sql;
    }
} 