<?php

/**

 * @method 大有接口基础
 * 
 * @author zhengweihua 
 * @copyright 2024-06-22
 */
class B2cBaseCustom extends B2cBase
{

    public $dyopenApi = [];
    public $dyApi = [];
    public function __construct($dyApiConfig=null)
    {
        parent::__construct();
        if($dyApiConfig){
            $this->dyApi = $dyApiConfig;
        }
    }


    /**
     * @method 通过大有接口获取产品信息
     * @author zhengweihua 
     * @copyright 2024-06-22
     */
    public function getStockChange($shopId)
    {   
        ini_set('memory_limit', '4096M');
        $LibCurl = new LibCurl();
        $url = 'http://service.doyor.com/FitService/GetStockChange';
        $postArr = [
            'webname'=>$this->dyApi['webname'],
            'appkey'=>$this->dyApi['appkey'],
            'apppwd'=>$this->dyApi['apppwd'],
            'pageindex'=>1,
            'pagesize'=>1,
            'stockType'=>1
        ];
        
        $jsonres =  $LibCurl->fetch($url,$postArr);
        $jsonArr = json_decode($jsonres,true);

        //每次取1000条
        $pagesize = 1000;
        $total =ceil($jsonArr['count']/$pagesize);
        $cacheData = [];
        if ($total > 0) {
            $postArr['pagesize'] = $pagesize; 
            for ($i=1; $i <= $total; $i++) 
            { 
                $postArr['pageindex'] = $i;
                $jsonres = $LibCurl->fetch($url,$postArr);
                $jsonArr = json_decode($jsonres,true);
				$cacheData[] = json_encode($postArr);
				$cacheData[] = $jsonArr;
                unset($jsonArr);
            }
            // 缓存下
            file_put_contents(mvc::$cfg['ROOT'].'admins/cache/erpdata'.$shopId.$this->dyApi['webname'].'_'.date('N').'.php',"<?php ".var_export($cacheData,true).";?>"); 
            return $cacheData;
        }
    }
    

     /**
     * @param  [string] $phone
     * @method 大有API检查手机号
     * @author zhengweihua 
     * @copyright 2023-06-08
     */
    public function checkPhoneByDy($phone)
    {
        $data = [
            'phone' => $phone,
        ];
        $result = $this->httpCurl('api/dyApi/checkPhone',$data);
        return LibFc::ReturnData(true,$result['data']);
    }


    public function httpCurl($urlPath,$getArr = [],$postArr = [])
    {
        $url = $this->dyopenApi['baseUrl'] . $urlPath;
        $time = time();
        if ($getArr){
            $data = $getArr;
        } 
        if ($postArr) $data = $postArr;

        $data['appkey'] = $this->dyopenApi['appkey'];
        $data['timeStamp'] = $time;
        
        ksort($data);
        $queryArr = [];
        foreach ($data as $key => $val) 
        {
            if (is_array($val)) {
                $val = json_encode($val, 1344);
            }
            $queryArr[] = $key . '=' . $val;
        }
        $query = implode('&', $queryArr);
        $query .= '&' . $this->dyopenApi['appKeySecret'];

        $query =  str_replace('"', '', $query);
        $sign = md5($query);
        $data['sign'] = $sign;

        if($getArr){
            $url = $url . '?' . http_build_query($data);
        }
        if ($postArr) {
            $postJson = json_encode($data,1344);
        }
		$btime = microtime(true);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER,['Content-Type:application/json;charset=UTF-8']);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        if (!empty($postArr)) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postJson);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ssl = substr($url, 0, 8) == "https://" ? true : false;
        if ($ssl) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 信任任何证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 检查证书中是否设置域名
        }
        $html = curl_exec($ch);
        curl_close($ch);
		$runtime = ceil((microtime(true) - $btime)*1000);
		if($runtime > 1000){
			 LibLog::write('Erp推送时间=>'.$url.'=>'.json_encode($postArr).'=>'.$runtime.'ms');
		}
        //处理错误提示
        $return = json_decode($html, true);

        if (is_array($return)) {
            if($return['code']==20000)
            {
                return LibFc::ReturnData(true, $return['data']);
            }else{
                /*$logData = [
                    'url'=>$url,
                    'postJson'=>$postJson?:'',
                    'signStr'=>$query
                ];
                file_put_contents(mvc::$cfg['LOGS'].'Erp_'.date('Y-m-d').'.log',date('Y-m-d H:i:s').":".var_export($logData,true)."\r\n",FILE_APPEND);*/
                LibLog::write('Erp推送异常=>'.$url.'=>'.json_encode($postArr).'=>返回'.$html);
				return LibFc::ReturnData(false, '大有接口：'.$return['message']);
            }   
            
        } else {
			LibLog::write('Erp推送异常=>'.$url.'=>'.json_encode($postArr).'=>返回'.$html);
            return LibFc::ReturnData(false, '大有接口：'.$html);
        }
    }
}
