<?php

declare (strict_types=1);
namespace library\lib;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-10-22 09:24
// +----------------------------------------------------------------------
class hupun {

    private $config;

    public function  __construct()
    {
        $this->config = config('hupun');
    }

    //推送订单到ERP
    public function tradesErp($data){
        $d['tradeID']  = $data['order_id'];//第三方交易号
        $d['shopNick'] = '飞播';//对应到ERP中的店铺昵称
        $d['status']   = 2;
        $d['createTime'] = $data['time'] * 1000;//下单时间
        $d['payTime'] = $data['payTime'] * 1000;//支付时间
        $d['modifyTime'] = time() * 1000;//时间戳
        $d['storeID'] = $data['storeID'];//仓库编码
        $d['sellerMemo'] = $data['mono'];
        $d['shippingType'] = 0;//发货类型:0：快递；
        $d['totalFee'] = $data['pro_price'];//商品总金额，不含邮费
        $d['postFee'] = $data['exp_price'];//邮费
        $d['buyer'] = $data['ts_name'];//买家
        $d['receiverName'] = $data['name'];//收货人
        $d['receiverProvince'] = $data['province'];//收件省
        $d['receiverCity'] = $data['city'];//收件市
        $d['receiverArea'] = $data['area'];//收件区
        $d['receiverAddress'] = $data['address'];//收货地址
        $d['receiverMobile'] = $data['mobile'];//收货手机号码
        $d['hasRefund'] = 0;
        //子订单
        $d['orders'] = [
            ['tradeID' => $data['order_id'],
             'orderID' => $data['in_order_id'],
             'itemID'  => $data['csno'],
              'itemCode' =>    $data['csno'],
             'itemTitle' => $data['pro_title'],
             'skuCode'   => '无',
             'status'    => '2',
             'price'     => $data['pro_price'],
             'size'      => 1,
             'buyerMessage' => $data['mono'],
             'imageUrl'  => $data['pro_img'],
             'payment'   => $data['pro_price']]
        ];
        $save['trades'] =json_encode([$d],\JSON_UNESCAPED_UNICODE);
        //https://erp-open.hupun.com/api/v1/trades/open
       $dd =  $this->getXac('https://erp-open.hupun.com/api/v1/trades/open',$save);
       return json_decode($dd,true);

    }


    /**
     * 查询订单号
     */
    public function orderFind($orderIds){
        $d['shop_type'] = 100;
        $d['shop_nick'] = '飞播';
        $d['trade_ids'] = $orderIds;
        $post = $this->getParam($d);
        $post_string = http_build_query($post, '', '&');
        //$post_string = urldecode($post_string);
        $dd =  $this->httpGet('https://erp-open.hupun.com/api/v1/trades/erp/status?'.$post_string);
        return json_decode($dd,true);
    }


    /**
     * 推送产品信息
     * @param $data
     */
    public function addProduct($data){
        $d['itemID'] = $data['code'];
        $d['shopNick'] = '飞播';
        $d['title'] = $data['title'];
        $d['itemCode'] = $data['code'];
        $d['price'] = $data['price'];
        $d['quantity'] = $data['quantity'];
        $d['itemURL'] = $data['url'];
        $d['barcode'] = $data['csno'];
        $d['imageURL'] = $data['img'];
        $d['status'] = $data['status'];//状态,0：已删除，1：在售，2：待售，仓库中
        $d['createTime'] = $data['time'] * 1000;
        $d['modifyTime'] = time() * 1000;
        $d['skus'] = [];
        $save['items'] =json_encode([$d],\JSON_UNESCAPED_UNICODE);
        $dd =  $this->getXac('https://erp-open.hupun.com/api/v1/items/open',$save);
        return json_decode($dd,true);
    }


    /**
     * 生成字符串
     * @param $save
     * @return mixed
     */
    private function getParam($save){
        $time = time();
        $save['app_key'] = $this->config['app_key'];
        $save['format'] = 'json';
        $save['timestamp'] = $time * 1000;
        $save['sign'] = $this->sign($save);
        return $save;
    }


    /**
     * MD5 加密
     * @param $data
     */
    private function sign($data){
        ksort($data);
        $str =  '';
        foreach ($data as $k => $v) {
            $str .= $k.$v;
        }
       return strtoupper(md5($this->config['app_secret'] . $str .$this->config['app_secret']));
    }

    private function getXac($url,$data){
        $post = $this->getParam($data);
       return  $this->curlPost($url,$post);
    }


    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    function curlPost($url, $post_data = array(), $timeout = 5, $data_type = "") {
        //支持json数据数据提交
        if($data_type == 'json'){
            $post_string = json_encode($post_data);
        }elseif($data_type == 'array') {
            $post_string = $post_data;
        }elseif(is_array($post_data)){
            $post_string = http_build_query($post_data, '', '&');
            $post_string = urldecode($post_string);
        }

        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
      //  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        $result = curl_exec($ch);

        // 打印请求的header信息
        //$a = curl_getinfo($ch);
        //var_dump($a);
        curl_close($ch);
        return $result;
    }

}