<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\Order;

class ElectronicWaybill extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        
        $electronic_waybill = $base['data']['electronic_waybill'];

        
        return $electronic_waybill;
    }

    
    public static function createWaybill($id){
        $set = self::getSet();
        
        if($set['status'] != 1){
            return __json(0,"未开启");
        }
        
        $order = Db::name("bbfx_order")->where(['id'=>$id])->find();
        $result = Order::checkFahuo($order);
        if($result['code'] !=1){
            return $result;
        }
        
        $express = Db::name("bbfx_express")->where(['id'=>$set['express_id']])->find();
        if(empty($express)){
            return __json(0,"快递公司信息错误");
        }
        $api_params = $set['api_params'];
        $goods_info = iunserializer($order['goods_info']);
        $Commodity = [];
        $Weight = 0;
        $Quantity = 1;
        $Volume = 0;
        if(is_string($goods_info)){
            $order_goods = Db::name("bbfx_order_goods")->where(['uniacid'=>UNIACID,'order_id'=>$id])->field("id,goods_info")->select();
            foreach ($order_goods as $key => $val){
                $goods_info = iunserializer($val['goods_info']);
                $Commodity[] = [
                    'GoodsName'=>$goods_info['title'],
                    'Goodsquantity'=>$goods_info['total'],
                    'GoodsWeight'=>$goods_info['weight']
                ];
                $Weight += $goods_info['weight'];
                $Volume += $goods_info['volume'];
            }
        }
        else{
            foreach ($goods_info as $key => $val){
                $Commodity[] = [
                    'GoodsName'=>$val['title'],
                    'Goodsquantity'=>$val['total'],
                    'GoodsWeight'=>$val['weight']
                ];
                $Weight += $val['weight'];
                // $Quantity += $val['total'];
                $Volume += $val['volume'];
            }
        }
        
        $data = [
            "OrderCode"=>$order['order_no'],// 订单编号
            "ShipperCode"=>$express['coding'],// 物流公司编码
            "PayType"=>1,// 运费支付方式:1=现付,2=到付,3=月结,4=第三方付,4=回单付
            // "CustomerName"=>$set['CustomerName'],
            // "CustomerPwd"=>$set['CustomerPwd'],
            // "MonthCode"=>$set['CustomerPwd'],
            "ExpType"=>1,// 快递业务类型
            // "Cost"=>1.0,// 快递运费
            // "OtherCost"=>1.0,// 其他费用
            "Sender"=>[
                // "Company"=>"LV",// 收件人公司 
                "Name"=>$set['fahuo_username'],// 发件人
                "Mobile"=>$set['fahuo_mobile'],
                "ProvinceName"=>$set['fahuo_province'],
                "CityName"=>$set['fahuo_city'],
                "ExpAreaName"=>$set['fahuo_area'],
                "Address"=>$set['fahuo_address']
            ],
            "Receiver"=>[
                // "Company"=>"GCCUI",// 收件人公司 
                "Name"=>$order['delivery_username'],
                "Mobile"=>$order['delivery_mobile'],
                "ProvinceName"=>$order['delivery_province'],
                "CityName"=>$order['delivery_city'],
                "ExpAreaName"=>$order['delivery_area'],
                "Address"=>$order['delivery_street'].$order['delivery_address']
            ],
            "Commodity"=>[
                [
                    "GoodsName"=>"鞋子",
                    "Goodsquantity"=>1,
                    "GoodsWeight"=>1.0
                ],
                [
                    "GoodsName"=>"衣服",
                    "Goodsquantity"=>1,
                    "GoodsWeight"=>1.0
                ]
            ],
            "IsReturnPrintTemplate"=>"1"
            // "Weight"=>$Weight,
            // "Quantity"=>$Quantity,
            // "Volume"=>$Volume,
            // "Remark"=>""
        ];
        
        // echo "<pre>";
        // print_r($Commodity);die;
        
        $data['Commodity'] = $Commodity;
        $data['TemplateSize'] = "1301";
        if(!empty($set['TemplateSize'])){
            $data['TemplateSize'] = $set['TemplateSize'];
        }
        
        foreach ($api_params as $key => $val){
            if(!empty($val)){
                $data[$key] = $val;
            }
            
        }
        
        
        // echo "<pre>";
        // print_r($data);die;
        
        $result = self::request("/api/order/create",json_encode($data));
        
        addFileLog("dzmd",json_encode($result));
        
        if($result['code'] == 1){
            $extend = iunserializer($order['extend']);
            $extend['express'] = $result['data'];
            
            $express_no = $result['data']['Order']['LogisticCode'];
            if(empty($express_no)){
                $express_no = $result['data']['Order'][0]['LogisticCode'];
            }
             
            $express = [
                [
                    "express_id"=>$express['id'],
                    "express_name"=>$express['name'],
                    "express_no"=>$express_no,
                    "goods_id"=>""
                ]
            ];

            $data = [
                'extend'=>iserializer($extend),
                'express'=>iserializer($express),
                'status'=>2,
                'deliverytime'=>time(),
                'deliver_type'=>1,
                'is_electronic_waybill_print'=>1
            ];
            
            Db::name("bbfx_order")->where(['id'=>$order['id']])->update($data);

            Order::sendGoods($order['id']);
            
            return __json(1,"操作成功",['expressPrintTemplate'=>$result['data']['PrintTemplate']]);
        }
        
        return $result;
    }
    
    public static function request($path,$bodys='',$method='POST'){
        $host = "https://alicloudmarket1007.kdniao.com";
        
        $set = self::getSet();
        $appcode = $set['AppCode'];
        
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        
        $url = $host . $path;
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $out_put = curl_exec($curl);
        
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        
        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        addFileLog("dzmd11",$body);
        if ($httpCode == 200) {
            $res = json_decode($body,true);
            if(empty($res) && !empty($body)){
                $body = explode('{"PrintTemplate":"', $body)[1];
                if(!empty($body)){
                    $res = json_decode('{"PrintTemplate":"'.$body,true);
                }
            }
            
            if(($res['ResultCode'] != 100 && $res['ResultCode'] != 106) || empty($res['Order'])){
                return __json(0,$res['Reason']);
            }
            
            return __json(1,"请求成功",$res);
        } else {
            if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
                return __json(0,"参数错误");
            } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
                return __json(0,"AppCode错误");
            } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
                return __json(0,"请求的 Method、Path 或者环境错误");
            } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
                return __json(0,"服务未被授权（或URL和Path不正确）");
            } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
                return __json(0,"套餐包次数用完");
            } elseif ($httpCode == 403 && strpos($header, "Api Market Subscription quota exhausted") !== false) {
                return __json(0,"套餐包次数用完，请续购套餐");
            } elseif ($httpCode == 500) {
                return __json(0,"API网关错误");
            } elseif ($httpCode == 0) {
                return __json(0,"URL错误");
            } else {
                return __json(0,"参数名错误 或 其他错误");
            }
        }
    }
}