<?php


namespace app\traits;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

trait GongApiRequest
{
    //接口文档：https://kdocs.cn/l/cov4HdLPYVgV
    private static $path = 'https://www.douhuomall.com';
//    private static $app_id = 'YS112May13bb673b251a';
//    private static $app_secret = '38971362a8965c9135cb147d53e52706';
//    private static $mobile = '13911251783';
    private static $app_id = 'YS3a8ab661406e47bb86';
    private static $app_secret = '41d8b8e1dd9a454a1abc4534297e33c3';
    private static $mobile = '17855366921';

    public static function get_access_token(){
        $url = '/api_v2/noAuth/getAccessToken';
        $time = time();
        $body = [
            'app_id' => self::$app_id,
            'sign' => self::getSign($time),
            'mobile' => self::$mobile,
            'timestamp' => $time
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            Cache::set('gong_access_token', $res['result']['access_token'], 23*60*60);// 将取到的token存入redis方便下次使用
            return $res['result']['access_token'];
        }
        return false;
    }

    public static function access_token(){
        $gong_access_token = Cache::get('gong_access_token');
        $url = '/api_v2/Goods/getGoodsList';
        $body = ['access_token' => $gong_access_token];
        $res = self::curl_post(self::$path.$url,$body);
        if(!$gong_access_token || ($res['error_code'] == 1001)){
            Cache::delete('gong_access_token');
            $gong_access_token = self::get_access_token();
        }
        return $gong_access_token;
    }

    //分类(未更改)
    public static function get_category(){
        $url = '/api/category/get_list';
        $body = [
            'access_token' => self::access_token(),
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 1002 && $res['error_msg'] == '会话不存在'){
            return 1002;
        }
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 商品列表
     * @param int $page 页数
     * @param int $limit 每页数量
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:31:59
     */
    public static function get_goods_list($page=1,$limit=50){
        $url = '/api_v2/Goods/getGoodsList';
        $body = [
            'access_token' => self::access_token(),
            'page' => $page,
            'limit' => $limit
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 商品详情
     * @param array $goods_id 商品goods_id
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:31:59
     */
    public static function get_goods_info($goods_id){
        $url = '/api_v2/Goods/getGoodsDetail';
        $body = [
            'access_token' => self::access_token(),
            'goods_id' => $goods_id,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if ($res['error_code'] == 2001) {
            return $res;
        }
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }



    /**
     * 规格详情
     * @param array $sku_id 商品sku_id
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:31:59
     */
    public static function get_sku_detail($sku_id){
        $url = '/api_v2/Goods/getSkuDetail';
        $body = [
            'access_token' => self::access_token(),
            'sku_id' => $sku_id,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        echo json_encode($res);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }


    /**
     * 商品规格
     * @param array $sku_sn 商品sku_sn
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:31:59
     */
    public static function get_sku($sku_sn){
        $url = '/api/Goods/getSkuDetail';
        $body = [
            'access_token' => self::access_token(),
            'sku_sn' => $sku_sn
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }
    

    /**
     * 商品价格(未更改)
     * @param string $sku_id 商品skuid,[‘984783’,’984784’]
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:31:59
     */
    public static function get_price($sku_id){
        $url = '/api/goods/sell_price';
        $body = [
            'access_token' => self::access_token(),
            'skuid' => $sku_id
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 商品是否有货(未更改)
     * @param int $sku_id 商品sku_id
     * @param int $address_id 地址id（区id或者接到id）
     * @param int $goods_num 商品数量
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:31:59
     */
    public static function stock($sku_id,$address_id,$goods_num){
        $url = '/api/goods/stock';
        $body = [
            'access_token' => self::access_token(),
            'sku_id' => $sku_id,
            'address_id' => $address_id,
            'goods_num' => $goods_num
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 查询商品上下架
     * @param string $spu_id 商品spu_id
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     * */
    public static function goods_status($spu_id){
        $url = '/api_v2/Goods/getGoodsDetail';
        $body = [
            'access_token' => self::access_token(),
            'goods_id' => $spu_id,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if ($res['error_code'] == 2001) {
            return $res;
        }
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 查询商品库存
     * @param string $sku_list 商品sku和数量[{"sku_id":123123,"num":1},{"sku_id":123124,"num":1}]
     * @param int $address_id 地址id（区id或街道id）
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function sku_stock(string $sku_list, int $address_id){
        $url = '/api_v2/Goods/stock';
        $body = [
            'access_token' => self::access_token(),
            'sku_list' => $sku_list,
            'address_id' => $address_id,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 运费查询（下单前调用，确定可售） (未对接)
     * @param string $address_id 地址id
     * @param array $sku_list sku列表 [{‘sku_id’:80,‘num’:5},{‘sku_id’:81,‘num’:2}]
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function freight(string $address_id, array $sku_list){
        $url = '/api_v2/order/getFreightPrice';
        $body = [
            'access_token' => self::access_token(),
            'address_id' => $address_id,
            'sku_list' => $sku_list
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 正式下单
     * @param string $address_id 地址id
     * @param array $sku_list sku列表 [{‘sku_id’:80,‘num’:5},{‘sku_id’:81,‘num’:2}]
     * @param string $address 详细地址
     * @param string $third_order 订单id
     * @param string $other 备注
     * @param string $receiver 收货人
     * @param string $receiver_phone 收货人手机号
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日13:22:09
     */
    public static function submit(string $address_id, array $sku_list, string $address, string $third_order, string $other, string $receiver, string $receiver_phone){
        $url = '/api_v2/order/submit';
        $body = [
            'access_token' => self::access_token(),
            'address_id' => $address_id,
            'sku_list' => $sku_list,
            'receiver' => $receiver,
            'receiver_phone' => $receiver_phone,
            'address' => $address,
            'other' => $other,
            'third_order' => $third_order
        ];
//        Db::name('log')->insert(['data'=>'供应链发货-------2：']);
        $res = self::curl_post(self::$path.$url,$body);
        return $res;
    }

    /**
     * 手动发货(未对接)
     * @param string $out_order_no 订单编号
     * @param string $logistics_number 物流单号
     * @param string $logistics_company 物流名称
     * @return string|boolean 订单状态值 0失败 1待付款 2待发货 3待收货 4已完成 5已取消 6售后中 7售后完成8拒收
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function order_send(string $out_order_no, string $logistics_company, string $logistics_number){
        $url = '/api/order/send';
        $body = [
            'access_token' => self::access_token(),
            'out_order_no' => $out_order_no,
            'logistics_number' => $logistics_number,
            'logistics_company' => $logistics_company
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 查询订单状态(未对接)
     * @param string $out_order_no 订单编号
     * @return string|boolean 订单状态值 0失败 1待付款 2待发货 3待收货 4已完成 5已取消 6售后中 7售后完成8拒收
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function order_status(string $out_order_no){
        $url = '/api/order/status';
        $body = [
            'access_token' => self::access_token(),
            'out_order_no' => $out_order_no,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 查询订单详情
     * @param string $out_order_no 订单编号
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function order_details(string $out_order_no){
        $url = '/api_v2/order/getOrderDetail';
        $body = [
            'access_token' => self::access_token(),
            'out_order_no' => $out_order_no,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 查询配送信息
     * @param string $out_order_no 订单编号
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function order_track(string $out_order_no){
        $url = '/api_v2/order/track';
        $body = [
            'access_token' => self::access_token(),
            'out_order_no' => $out_order_no,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }


    /**
     * 确认收货(未对接)
     * @param string $out_order_no 订单编号
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function confirm_received(string $out_order_no){
        $url = '/api/order/confirm_received';
        $body = [
            'access_token' => self::access_token(),
            'out_order_no' => $out_order_no,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 查询商品是否可售后属性(未对接)
     * @param string $out_order_no 订单编号
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function after_is_can(string $out_order_no){
        $url = '/api/after/is_can';
        $body = [
            'access_token' => self::access_token(),
            'out_order_no' => $out_order_no,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 申请售后(未对接)
     * @param string $out_order_no 订单编号
     * @param string $customer_expect 1-退货。2-换货
     * @param string $question_desc 申请理由
     * @param array $sku_list 多商品规格
     * @param string $img 退货图片json['',''],链接
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function after_create_apply(string $out_order_no, string $customer_expect, string $question_desc, array $sku_list, string $img){
        $url = '/api/after/create_apply';
        $body = [
            'access_token'  => self::access_token(),
            'plat_order_no' => $out_order_no,
            'after_type'    => $customer_expect,
            'explain'       => $question_desc,
            'sku_list'      => $sku_list,
            'img'           => $img
        ];
        $res = self::curl_post(self::$path.$url,$body);
        return $res;
    }

    /**
     * 申请售后(未对接)
     * @param string $order_goods_id 订单商品id
     * @param string $out_order_no 系统订单号
     * @param string $after_type 1=未收货退款，2=退货退款，3=换货补发，4=不退货仅退款
     * @param string $explain 售后原因
     * @param string $after_num 售后数量
     * @return array|boolean
     * @author lin
     * @created 2022年5月19日11:46:54
     */
    public static function apply_after_sales(string $order_goods_id,string $out_order_no, string $after_type, string $explain, string $after_num){
        $url = '/api/After/applyAfterSales';
        $body = [
            'access_token'   => self::access_token(),
            'order_goods_id' => $order_goods_id,
            'after_type'     => $after_type,
            'after_num'      => $after_num,
            'explain'        => $explain,
            'plat_order_no'  => $out_order_no,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        return $res;
    }


    /**
     * 查询订单是否可售后(未对接)
     * @param string $out_order_no 系统订单号
     * @return mixed|string
     */
    public static function is_can_after(string $out_order_no){
        $url = '/api/After/isCanAfter';
        $body = [
            'access_token'   => self::access_token(),
            'order_goods_id' => '',
            'plat_order_no'  => $out_order_no,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        return $res;
    }

    /**
     * 售后订单状态(未对接)
     * @param string $after_sn 售后订单号
     * @return array|boolean
     */
    public static function after_status_new(string $after_sn){
        $url = '/api/after/afterStatus';
        $body = [
            'access_token' => self::access_token(),
            'plat_after_no' => $after_sn
        ];
        return self::curl_post(self::$path.$url,$body);

    }

    /**
     * 售后订单状态(未对接)
     * @param string $after_sn 售后订单号
     * @return array|boolean
     */
    public static function after_status(string $after_sn){
        $url = '/api/after/status';
        $body = [
            'access_token' => self::access_token(),
            'after_sn' => $after_sn
        ];
        return self::curl_post(self::$path.$url,$body);

    }

    /**
     * 退换货发货信息(未对接)
     * @param string $after_sn 售后订单编号。申请售后接口返回
     * @param string $logistics_company 1-退货。2-换货
     * @param string $logistics_number 申请理由
     * @return string|boolean
     * @author lin
     * @created 2022年5月19日13:40:52
     */
    public static function after_update_send_info(string $after_sn, string $logistics_number, string $logistics_company){
        $url = '/api/after/update_send_info';
        $body = [
            'access_token' => self::access_token(),
            'after_sn' => $after_sn,
            'logistics_company' => $logistics_company,
            'logistics_number' => $logistics_number
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 取消申请售后(未对接)
     * @param string $after_sn 售后订单编号。申请售后接口返回
     * @param string $out_order_no 订单编号
     * @return string|boolean
     * @author lin
     * @created 2022年5月19日13:40:52
     */
    public static function after_cancel_apply(string $after_sn, string $out_order_no){
        $url = '/api/after/cancel_apply';
        $body = [
            'access_token' => self::access_token(),
            'after_sn' => $after_sn,
            'out_order_no' => $out_order_no
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 获取地区(未对接)
     * @param string $code 地区代码，为空查询省级信息，否则查询code的下级
     * @return string|boolean
     * @author lin
     * @created 2022年5月19日13:40:52
     */
    public static function get_region_code(string $code = null){
        $url = '/api/regions/get_region_code';
        $body = [
            'access_token' => self::access_token(),
        ];
        if($code != null) $body['code'] = $code;
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    /**
     * 获取消息池消息(未对接)
     * @param int $type 1-订单状态变动, 2-商品详情, 3-sku价格, 4-商品删除, 5-规格状态变更, 6-规格删除, 7-规格详情, 8-商品状态变更
     * @return  array|boolean
     * @author lin
     * @created 2022年5月19日13:55:07
     */
    public static function MessagePool(int $type){
        $url = '/api/MessagePool/get';
        $body = [
            'access_token' => self::access_token(),
            'type' => $type,
        ];
        $res = self::curl_post(self::$path.$url,$body);
        if($res['error_code'] == 0){
            return $res['result'];
        }
        return false;
    }

    public static function getSign($time){
        //按照以下顺序将字符串拼接起来 app_id+mobile+timestamp+app_secret 再用md5加密
        return md5(self::$app_id.self::$mobile.$time.self::$app_secret);
    }

    //通过curl发送post请求带body传参
    public static function curl_post($url, $postFields = null, $header = array())
    {

//        Db::name('log')->insert(['data'=>'供应链发货-------3：']);
        if ($url != 'https://www.douhuomall.com/api/category/get_list') {
            Db::name("log")->insert(array('data' => '供应链【' . $url . '】body:' . json_encode($postFields)));//日志记录
        }
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postFields));
//        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
//        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        if(is_null(json_decode($data))){
            $data = strstr($data,'{');
        }
        if ($url != 'https://www.douhuomall.com/api/category/get_list'){
            // log::info('供应链【'.$url.'】body:'.json_encode($postFields,JSON_UNESCAPED_UNICODE));
            // log::info('供应链【'.$url.'】headerArray:'.json_encode($header,JSON_UNESCAPED_UNICODE));
            // log::info('供应链【'.$url.'】data:'.$data);
//            Db::name("log")->insert(array('data'=>'供应链【'.$url.'】body:'.json_encode($postFields)));//日志记录
//            Db::name("log")->insert(array('data'=>'供应链【'.$url.'】headerArray:'.json_encode($header)));//日志记录
//            Db::name("log")->insert(array('data'=>'供应链【'.$url.'】data:'.$data));//日志记录
//            dump($data);
        }
        // 显示错误信息
        if (curl_error($curl)) {
            return curl_error($curl);
        } else {
            curl_close($curl);
            return json_decode($data, true);
        }
    }


}
