HEX
Server: nginx/1.28.1
System: Linux 10-41-63-61 6.8.0-31-generic #31-Ubuntu SMP PREEMPT_DYNAMIC Sat Apr 20 00:40:06 UTC 2024 x86_64
User: www (1001)
PHP: 7.4.33
Disabled: passthru,exec,system,putenv,chroot,chgrp,chown,shell_exec,popen,proc_open,pcntl_exec,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv
Upload Files
File: //www/备份的/mmmmm.mnbola.site/m.php
<?php

namespace app\api\controller;

use app\common\extensions\Common;
use app\common\model\Country;
use app\common\model\IntMobile;
use app\common\model\Opt;
use app\common\model\OptOptions;
use app\common\model\OrderDetail;
use app\common\model\Web;
use app\common\model\Slide;
use app\common\model\Category;
use app\common\model\GoodsOptData;
use app\common\model\GoodsOpt;
use app\common\model\Goods;
use app\common\model\GoodsBatch;
use app\common\model\GoodsAttribute;
use app\common\model\GoodsRelated;
use app\common\model\GoodsPic;
use app\common\model\GoodsCategory;
use app\common\model\LengthUnit;
use app\common\model\WeightUnit;
use app\common\model\TaxClass;
use app\common\model\TaxClassList;
use app\common\model\TaxList;
use app\common\model\User;
use app\common\model\UserIntegral;
use app\common\model\UserIp;
use app\common\model\UserMoney;
use app\common\model\UserAddress;
use app\common\model\UserGroup;
use app\common\model\Cart;
use app\common\model\Brand;
use app\common\model\Attribute;
use app\common\model\AttributeGroup;
use app\common\model\Zone;
use app\common\model\Order as ModelOrder;
use app\common\model\OrderStatus;
use app\common\model\Pay;
use app\common\model\Express;
use app\common\model\OrderPay;
use app\common\model\OrderTransport;
use app\common\model\OrderRevoke;
use app\common\model\CoinSign;
use app\common\model\Dict;
use think\facade\App;
use think\facade\Env;
use think\Db;

class Order extends Base
{
    public function initialize()
    {
        parent::initialize();
    }

    //下单(没登录)
    public function logoutMakeOrder(){
        $post = $this->post;
        $common = new Common();
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);

//        $d = [
//            [
//                "goods_id" => 1,
//                "num" => 1,
//                "opt" => [
//                    [
//                        "opt_id" => 49,
//                        "opt_name" => "尺寸",
//                        "opt_options_id" => 30,
//                        "opt_options_name" => "10nm",
//                    ],
//                    [
//                        "opt_id" => 50,
//                        "opt_name" => "服务",
//                        "opt_options_id" => 33,
//                        "opt_options_name" => "保修1年",
//                    ],
//                ],
//            ]
//        ];
//        var_dump(json_encode($d));die;


        $resArr = array();
        Db::startTrans();
        try {
            $email = $post["email"];
            $express_id = $post["express_id"];
            if(empty($email)){
                return returnJson(1, 'E-Mail not empty');
            }
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                return returnJson(1, 'E-Mail format error');
            }
            if(empty($express_id)){
                return returnJson(1, 'express_id not empty');
            }
            //配送信息
            $delivery_first_name = $post["delivery_first_name"];
            $delivery_last_name = $post["delivery_last_name"];
            $delivery_intmobile_id = $post["delivery_intmobile_id"];
            $delivery_mobile = $post["delivery_mobile"];
            $delivery_company = $post["delivery_company"];
            $delivery_country_id = $post["delivery_country_id"];
            $delivery_province_id = $post["delivery_province_id"];
            $delivery_city = $post["delivery_city"];
            $delivery_district = $post["delivery_district"];
            $delivery_address = $post["delivery_address"];
            $delivery_street = $post["delivery_street"];
            $delivery_postcode = $post["delivery_postcode"];

            if(empty($delivery_intmobile_id)){
                return returnJson(1, "please select country calling codes(Delivery Details)" );
            }
            if(empty($delivery_first_name)){
                return returnJson(1, "please fill in first name(Delivery Details)" );
            }
            if(empty($delivery_last_name)){
                return returnJson(1, "please fill in last name(Delivery Details)" );
            }
            if(empty($delivery_mobile)){
                return returnJson(1, "please fill in mobile(Delivery Details)" );
            }
            preg_match_all('/[^\d]/is',$delivery_mobile,$match);
            if(!empty($match[0])){
                return returnJson(1, "mobile incorrect(Delivery Details)" );
            }
            if(empty($delivery_country_id)){
                return returnJson(1, "please select country(Delivery Details)" );
            }
            if(empty($delivery_province_id)){
                return returnJson(1, "please select zone(Delivery Details)" );
            }
            if(empty($delivery_address)){
                return returnJson(1, "please select address detail(Delivery Details)" );
            }

            $IntMobile = IntMobile::where(["id"=>$delivery_intmobile_id])->find();
            if(empty($IntMobile)){
                return returnJson(1, "data error" );
            }
            $delivery_intmobile_value = $IntMobile["number"];

            $Country = Country::where(["id"=>$delivery_country_id])->find();
            if(empty($Country)){
                return returnJson(1, "data error" );
            }
            $delivery_country = $Country["name"];
            $delivery_country_iso2 = $Country["iso2"];
            $delivery_country_iso3 = $Country["iso3"];

            $Zone = Zone::where(["id"=>$delivery_province_id,"country_id"=>$delivery_country_id])->find();
            if(empty($Zone)){
                return returnJson(1, "data error" );
            }
            $delivery_province = $Zone["name"];
            $delivery_province_code = $Zone["code"];

            if($Country["is_post"] == 1){
                if(empty($delivery_postcode)){
                    return returnJson(1, "postcode not empty(Delivery Details)" );
                }
            }

            //保存用户
            $d = User::where(["email"=>$email])->find();
            if(!empty($d)){
                $user_id = $d["id"];
                $UserGroup = UserGroup::where(["id"=>$d["group_id"]])->find();
                //return returnJson(5, "email account is exist, please login" );
            }else{
                $UserGroup = UserGroup::where(["is_default"=>1])->find();
                $user_data = [
                    "group_id" => $UserGroup["id"],
                    "first_name" => $delivery_first_name,
                    "last_name" => $delivery_last_name,
                    "email" => $email,
                    "thumb" => "/static/images/defaultAvatar.jpg",
                    "int_mobile_id" => $delivery_intmobile_id,
                    "mobile" => $delivery_mobile,
                    "password" => md5($this->pwd_harsh."123456"),
                    "desc" => "",
                ];
                $user_model = new User();
                $user_model->save($user_data);

                $user_id = $user_model->id;
                $token = md5($user_id.$this->user_token_harsh);
                User::where(["id"=>$user_id])->update(["token"=>$token]);
            }
//            $d = User::where(["mobile"=>$delivery_mobile])->find();
//            if(!empty($d)){
//                return returnJson(1, "mobile account is exist, please login" );
//            }


            $no = $common->randOrderNo();

            //邮费
            $express = Express::where(["id"=>$express_id])->find();
            $express_price = round($express["price"],2);

            //币代码
            $currency = "USD";
            $coin = CoinSign::where(["is_default"=>1])->find();
            if(!empty($coin)){
                $currency = $coin["currency"]?$coin["currency"]:"USD";
                $currency = strtoupper($currency);
            }

            $data = [
                "no" => $no,
                "currency" => $currency,
                "express_id" => $express_id,
                "express_price" => $express_price,
                "user_id" => $user_id,
                "user_group_id" => $UserGroup["id"],
                "user_group_value" => $UserGroup["name"],
                "user_first_name" => $delivery_first_name,
                "user_last_name" => $delivery_last_name,
                "user_email" => $email,
                "user_intmobile_id" => $delivery_intmobile_id,
                "user_intmobile_value" => $delivery_intmobile_value,
                "user_mobile" => $delivery_mobile,
                "delivery_first_name" => $delivery_first_name,
                "delivery_last_name" => $delivery_last_name,
                "delivery_intmobile_value" => $delivery_intmobile_value,
                "delivery_mobile" => $delivery_mobile,
                "delivery_company" => $delivery_company,
                "delivery_country" => $delivery_country,
                "delivery_country_iso2" => $delivery_country_iso2,
                "delivery_country_iso3" => $delivery_country_iso3,
                "delivery_province" => $delivery_province,
                "delivery_province_code" => $delivery_province_code,
                "delivery_city" => $delivery_city,
                "delivery_district" => $delivery_district?$delivery_district:'',
                "delivery_address" => $delivery_address,
                "delivery_street" => $delivery_street,
                "delivery_postcode" => $delivery_postcode,
            ];

            //默认订单状态
            $OrderStatus = OrderStatus::where(["is_default"=>1])->find();
            $data["order_status_id"] = $OrderStatus["id"];

            //支付信息
            $is_same = $post["is_same"];
            if($is_same == 1){
                $data_merge = [
                    "billing_first_name" => $delivery_first_name,
                    "billing_last_name" => $delivery_last_name,
                    "billing_intmobile_value" => $delivery_intmobile_value,
                    "billing_mobile" => $delivery_mobile,
                    "billing_company" => $delivery_company,
                    "billing_country" => $delivery_country,
                    "billing_country_iso2" => $delivery_country_iso2,
                    "billing_country_iso3" => $delivery_country_iso3,
                    "billing_province" => $delivery_province,
                    "billing_province_code" => $delivery_province_code,
                    "billing_city" => $delivery_city,
                    "billing_district" => $delivery_district?$delivery_district:'',
                    "billing_address" => $delivery_address,
                    "billing_street" => $delivery_street,
                    "billing_postcode" => $delivery_postcode,
                ];
                $data = array_merge($data,$data_merge);
            }else{
                $billing_first_name = $post["billing_first_name"];
                $billing_last_name = $post["billing_last_name"];
                $billing_intmobile_id = $post["billing_intmobile_id"];
                $billing_mobile = $post["billing_mobile"];
                $billing_company = $post["billing_company"];
                $billing_country_id = $post["billing_country_id"];
                $billing_province_id = $post["billing_province_id"];
                $billing_city = $post["billing_city"];
                $billing_district = $post["billing_district"];
                $billing_address = $post["billing_address"];
                $billing_street = $post["billing_street"];
                $billing_postcode = $post["billing_postcode"];

                if(empty($billing_intmobile_id)){
                    return returnJson(1, "please select country calling codes(Billing Details)" );
                }
                if(empty($billing_first_name)){
                    return returnJson(1, "please fill in first name(Billing Details)" );
                }
                if(empty($billing_last_name)){
                    return returnJson(1, "please fill in last name(Billing Details)" );
                }
                if(empty($billing_mobile)){
                    return returnJson(1, "please fill in mobile(Billing Details)" );
                }
                preg_match_all('/[^\d]/is',$billing_mobile,$match);
                if(!empty($match[0])){
                    return returnJson(1, "mobile incorrect(Billing Details)" );
                }
                if(empty($billing_country_id)){
                    return returnJson(1, "please select country(Billing Details)" );
                }
                if(empty($billing_province_id)){
                    return returnJson(1, "please select zone(Billing Details)" );
                }
                if(empty($billing_address)){
                    return returnJson(1, "please fill in address detail(Billing Details)" );
                }

                $IntMobile = IntMobile::where(["id"=>$billing_intmobile_id])->find();
                if(empty($IntMobile)){
                    return returnJson(1, "data error" );
                }
                $billing_intmobile_value = $IntMobile["number"];

                $Country = Country::where(["id"=>$billing_country_id])->find();
                if(empty($Country)){
                    return returnJson(1, "data error" );
                }
                $billing_country = $Country["name"];
                $billing_country_iso2 = $Country["iso2"];
                $billing_country_iso3 = $Country["iso3"];

                $Zone = Zone::where(["id"=>$billing_province_id,"country_id"=>$billing_country_id])->find();
                if(empty($Zone)){
                    return returnJson(1, "data error" );
                }
                $billing_province = $Zone["name"];
                $billing_province_code = $Zone["code"];

                if($Country["is_post"] == 1){
                    if(empty($billing_postcode)){
                        return returnJson(1, "postcode not empty(Billing Details)" );
                    }
                }

                $data_merge = [
                    "billing_first_name" => $billing_first_name,
                    "billing_last_name" => $billing_last_name,
                    "billing_intmobile_value" => $billing_intmobile_value,
                    "billing_mobile" => $billing_mobile,
                    "billing_company" => $billing_company,
                    "billing_country" => $billing_country,
                    "billing_country_iso2" => $billing_country_iso2,
                    "billing_country_iso3" => $billing_country_iso3,
                    "billing_province" => $billing_province,
                    "billing_province_code" => $billing_province_code,
                    "billing_city" => $billing_city,
                    "billing_district" => $billing_district?$billing_district:'',
                    "billing_address" => $billing_address,
                    "billing_street" => $billing_street,
                    "billing_postcode" => $billing_postcode,
                ];

                $data = array_merge($data,$data_merge);
            }

            $order_model = new ModelOrder();
            $order_model->save($data);

            $order_id = $order_model->id;

            //订单详情
            $datas = $post["datas"];
            $datas = htmlspecialchars_decode($datas);
            $datas = stripslashes($datas);
            $datas = json_decode($datas,true);

            if(empty($datas)){
                $datas = $post["datas"];
                $datas = htmlspecialchars_decode($datas);
                $datas = json_decode($datas,true);
                if(empty($datas)){
                    return returnJson(1, 'datas error');
                }
            }
            //订单总额
            $all_total_price = 0;

            //处理库存
            $i = 0;
            $wstock_arr = array();
            foreach($datas as $k=>$v){
                $num = intval($v["num"]);
                $goods_id = intval($v["goods_id"]);
                $opt = $v["opt"];

                //选项数据处理
                $_opt = $common->webDealingOptions($opt);
                $wstock_arr[] = [
                    "i" => $i,
                    "goods_id" => $goods_id,
                    "num" => $num,
                    "opt" => $_opt,
                ];
                $i++;
            }
            //判断库存
            $res = $common->wstockTheMoreGoods($wstock_arr);
            if($res["code"] == 1){
                return returnJson(1, $res["msg"]);
            }
            //修改商品和选项数量
            $common->wstockTheChangeGoods($wstock_arr);

            //处理订单详情信息
            $res = $this->dealOrderDetailPart($datas,$user_id,$order_id,$all_total_price,$dtime);
            $all_total_price = $res["all_total_price"];
            $total_weight = $res["total_weight"];
            $total_integral = $res["total_integral"];
            $detail_arr = $res["detail_arr"];

            foreach($detail_arr as $k=>$v){
                $order_detail_model = new OrderDetail();
                $order_detail_model->save($v);
            }
            //OrderDetail::insertAll($datas);


            //添加邮费
            $all_total_price = round(($all_total_price+$express_price),2);
            //修改订单信息
            $order = ModelOrder::where(["id"=>$order_id])->find();
            $order->total_price = $all_total_price;
            $order->pay_price = $all_total_price;
            $order->weight = $total_weight;
            $order->integral = $total_integral;
            $order->save();

            //删除购物车
            $cart = $post["cart"];
            $cart = json_decode($cart,true);
            if(!empty($cart)){
                Cart::where([["id","in",$cart]])->delete();
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return returnJson(1, 'error'.$e->getMessage());
        }


        return returnJson(0, 'success', $order_id);
    }

    public function UserMsg($token){
        $user = User::where(["token"=>$token])->find();
        $res = [
            "id" => $user["id"],
            "first_name" => $user["first_name"],
            "last_name" => $user["last_name"],
            "int_mobile_id" => $user["int_mobile_id"],
            "mobile" => $user["mobile"],
            "email" => $user["email"],
            "thumb" => $this->host.$user["thumb"],
            "token" => $user["token"],
            "desc" => $user["desc"],
        ];

        $res["group_id"] = $group_id = $user["group_id"];
        $UserGroup = UserGroup::where(["id"=>$group_id])->find();
        $res["group_name"] = $UserGroup["name_en"];
        $int_mobile_id = $user["int_mobile_id"];
        $IntMobile = IntMobile::where(["id"=>$int_mobile_id])->find();
        $res["intmobile_name"] = $IntMobile["name"];
        $res["intmobile_number"] = $IntMobile["number"];

        return $res;
    }

    //处理订单详情信息
    public function dealOrderDetailPart($datas,$user_id,$order_id,$all_total_price,$dtime){
        $common = new Common();

        $total_weight = 0;
        $total_integral = 0;
        $detail_arr = array();
        $i = 0;
        foreach($datas as $k=>$v){
            $num = intval($v["num"]);
            $goods_id = intval($v["goods_id"]);
            $opt = $v["opt"];
            //选项数据处理
            $opt = $common->webDealingOptions($opt);

            //处理价格
            $wstock = [
                "i" => $i,
                "goods_id" => $goods_id,
                "num" => $num,
                "opt" => $opt,
            ];
            $res = $common->wstockTheGoods($wstock,$user_id);

            $single_price = round($res["single_price"],2);
            $total_price = round($res["total_price"],2);
            $origin_price = round($res["origin_price"],2);
            $add_price = round($res["add_price"],2);
            $special_price = round($res["special_price"],2);
            $special_type = $res["special_type"];
            $all_total_price = round(($all_total_price+$total_price),2);


            $goods = Goods::where(["id"=>$goods_id])->find();

            $goods_name = $goods["name"];
            $goods_name_en = $goods["name_en"];
            $goods_no = $goods["no"];
            $goods_sku = $goods["sku"];
            $goods_long = $goods["long"];
            $goods_wide = $goods["wide"];
            $goods_high = $goods["high"];
            $goods_weight = round($goods["weight"],8);

            $LengthUnit = LengthUnit::where(["id"=>$goods["length_unit_id"]])->find();
            $goods_length_unit_value = round($LengthUnit["value"],8);
            $WeightUnit = WeightUnit::where(["id"=>$goods["weight_unit_id"]])->find();
            $goods_weight_unit_value = round($WeightUnit["value"],8);


            $add_weight = 0;
            $add_integral = 0;
            $ii = 0;
            foreach($opt as $k1=>$v1){
                $GoodsOpt = GoodsOpt::where(["id"=>$v1["opt_id"]])->find();
                $options[$ii]["id"] = $GoodsOpt["id"];
                $options[$ii]["opt_id"] = $GoodsOpt["opt_id"];
                $options[$ii]["ptype"] = $GoodsOpt["ptype"];
                $options[$ii]["is_must"] = $GoodsOpt["is_must"];

                $Opt = Opt::where(["id"=>$GoodsOpt["opt_id"]])->find();

                $options[$ii]["opt_name"] = $Opt["name"];
                $options[$ii]["opt_name_en"] = $Opt["name_en"];

                $GoodsOptData = GoodsOptData::where(["id"=>$v1["opt_options_id"]])->find();
                $options[$ii]["options"]["id"] = $GoodsOptData["id"];
                $options[$ii]["options"]["opt_options_id"] = $GoodsOptData["opt_options_id"];
                $options[$ii]["options"]["is_minus"] = $GoodsOptData["is_minus"];
                $options[$ii]["options"]["alg_p"] = $GoodsOptData["alg_p"];
                $options[$ii]["options"]["price"] = $GoodsOptData["price"];
                $options[$ii]["options"]["alg_w"] = $GoodsOptData["alg_w"];
                $options[$ii]["options"]["weight"] = $GoodsOptData["weight"];
                $options[$ii]["options"]["alg_i"] = $GoodsOptData["alg_i"];
                $options[$ii]["options"]["integral"] = $GoodsOptData["integral"];

                if($GoodsOptData["alg_w"] == 0){
                    $add_weight = round(($add_weight+round($GoodsOptData["weight"],8)),8);
                }
                if($GoodsOptData["alg_w"] == -1){
                    $add_weight = round(($add_weight-round($GoodsOptData["weight"],8)),8);
                }
                if($GoodsOptData["alg_i"] == 0){
                    $add_integral = round(($add_integral+round($GoodsOptData["integral"],2)),2);
                }
                if($GoodsOptData["alg_i"] == -1){
                    $add_integral = round(($add_integral-round($GoodsOptData["integral"],2)),2);
                }

                $OptOptions = OptOptions::where(["id"=>$GoodsOptData["opt_options_id"]])->find();
                $options[$ii]["options"]["options_name"] = $OptOptions["name"];
                $options[$ii]["options"]["options_name_en"] = $OptOptions["name_en"];

                $ii++;
            }

            $goods_t_weight = 0;
            $_goods_weight = round(($goods_weight+$add_weight),8);
            if($_goods_weight > 0 && $goods_weight_unit_value > 0){
                $goods_t_weight = round(($_goods_weight/$goods_weight_unit_value),8);
            }

            $total_weight = round(($total_weight+$goods_t_weight),8);
            $total_integral = round(($total_integral+$add_integral),2);

            $detail_arr[$i]["order_id"] = $order_id;
            $detail_arr[$i]["goods_id"] = $goods_id;
            $detail_arr[$i]["goods_name"] = $goods_name;
            $detail_arr[$i]["goods_name_en"] = $goods_name_en;
            $detail_arr[$i]["num"] = $num;
            $detail_arr[$i]["price"] = $single_price;
            $detail_arr[$i]["total_price"] = $total_price;
            $detail_arr[$i]["origin_price"] = $origin_price;
            $detail_arr[$i]["add_price"] = $add_price;
            $detail_arr[$i]["special_price"] = $special_price;
            $detail_arr[$i]["special_type"] = $special_type;
            $detail_arr[$i]["add_weight"] = $add_weight;
            $detail_arr[$i]["add_integral"] = $add_integral;
            $detail_arr[$i]["options"] = json_encode($options);
            $detail_arr[$i]["no"] = $goods_no;
            $detail_arr[$i]["sku"] = $goods_sku;
            $detail_arr[$i]["long"] = $goods_long;
            $detail_arr[$i]["wide"] = $goods_wide;
            $detail_arr[$i]["high"] = $goods_high;
            $detail_arr[$i]["length_unit_value"] = $goods_length_unit_value;
            $detail_arr[$i]["weight"] = $goods_weight;
            $detail_arr[$i]["weight_unit_value"] = $goods_weight_unit_value;
            $detail_arr[$i]["t_weight"] = $goods_t_weight;
            $detail_arr[$i]["create_time"] = $dtime;
            $detail_arr[$i]["update_time"] = $dtime;
            $i++;
        }

        return [
            "all_total_price"=>$all_total_price,
            "total_weight"=>$total_weight,
            "total_integral"=>$total_integral,
            "detail_arr"=>$detail_arr,
        ];
    }


    //下单(已登录)
    public function loginMakeOrder(){
        $post = $this->post;
        $common = new Common();
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);


        $resArr = array();
        Db::startTrans();
        try {
            $user_id = $this->authUser();

            $delivery_id = $post["delivery_id"];
            $billing_id = $post["billing_id"];

            if(empty($delivery_id)){
                return returnJson(1, 'please add Delivery Detail');
            }
            if(empty($billing_id)){
                return returnJson(1, 'please add Billing Detail');
            }

            $user = User::where(["id"=>$user_id])->find();
            $UserGroup = UserGroup::where(["id"=>$user["group_id"]])->find();
            $IntMobile = IntMobile::where(["id"=>$user["int_mobile_id"]])->find();

            $email = $user["email"];
            $express_id = $post["express_id"];
            if(empty($email)){
                return returnJson(1, 'E-Mail not empty');
            }
            if(empty($express_id)){
                return returnJson(1, 'express_id not empty');
            }
            //配送信息
            $delivery = UserAddress::where(["id"=>$delivery_id])->find();
            $DevIntMobile = IntMobile::where(["id"=>$delivery["int_mobile_id"]])->find();
            $DevCountry = Country::where(["id"=>$delivery["country_id"]])->find();
            $DevZone = Zone::where(["id"=>$delivery["province_id"]])->find();


            $no = $common->randOrderNo();

            //邮费
            $express = Express::where(["id"=>$express_id])->find();
            $express_price = round($express["price"],2);

            //币代码
            $currency = "USD";
            $coin = CoinSign::where(["is_default"=>1])->find();
            if(!empty($coin)){
                $currency = $coin["currency"]?$coin["currency"]:"USD";
                $currency = strtoupper($currency);
            }

            $data = [
                "no" => $no,
                "currency" => $currency,
                "express_id" => $express_id,
                "express_price" => $express_price,
                "user_id" => $user_id,
                "user_group_id" => $UserGroup["id"],
                "user_group_value" => $UserGroup["name"],
                "user_first_name" => $user["first_name"],
                "user_last_name" => $user["last_name"],
                "user_email" => $email,
                "user_intmobile_id" => $user["int_mobile_id"],
                "user_intmobile_value" => $IntMobile["name"]?$IntMobile["name"]:'',
                "user_mobile" => $user["mobile"],
                "delivery_first_name" => $delivery["first_name"],
                "delivery_last_name" => $delivery["last_name"],
                "delivery_intmobile_value" => $DevIntMobile["number"],
                "delivery_mobile" => $delivery["mobile"],
                "delivery_company" => $delivery["company"],
                "delivery_country" => $DevCountry["name"],
                "delivery_country_iso2" => $DevCountry["iso2"],
                "delivery_country_iso3" => $DevCountry["iso3"],
                "delivery_province" => $DevZone["name"],
                "delivery_province_code" => $DevZone["code"],
                "delivery_city" => $delivery["city"],
                "delivery_district" => $delivery["district"],
                "delivery_address" => $delivery["address_detail"],
                "delivery_street" => $delivery["street_number"],
                "delivery_postcode" => $delivery["postcode"],
            ];

            //默认订单状态
            $OrderStatus = OrderStatus::where(["is_default"=>1])->find();
            $data["order_status_id"] = $OrderStatus["id"];

            //支付信息
            $billing = UserAddress::where(["id"=>$billing_id])->find();
            $BillIntMobile = IntMobile::where(["id"=>$billing["int_mobile_id"]])->find();
            $BillCountry = Country::where(["id"=>$billing["country_id"]])->find();
            $BillZone = Zone::where(["id"=>$billing["province_id"]])->find();
            $data_merge = [
                "billing_first_name" => $billing["first_name"],
                "billing_last_name" => $billing["last_name"],
                "billing_intmobile_value" => $BillIntMobile["number"],
                "billing_mobile" => $billing["mobile"],
                "billing_company" => $billing["company"],
                "billing_country" => $BillCountry["name"],
                "billing_country_iso2" => $BillCountry["iso2"],
                "billing_country_iso3" => $BillCountry["iso3"],
                "billing_province" => $BillZone["name"],
                "billing_province_code" => $BillZone["code"],
                "billing_city" => $billing["city"],
                "billing_district" => $billing["district"],
                "billing_address" => $billing["address_detail"],
                "billing_street" => $billing["street_number"],
                "billing_postcode" => $billing["postcode"],
            ];

            $data = array_merge($data,$data_merge);

            $order_model = new ModelOrder();
            $order_model->save($data);

            $order_id = $order_model->id;

            //订单详情
            $datas = $post["datas"];
            $datas = htmlspecialchars_decode($datas);
            $datas = stripslashes($datas);
            $datas = json_decode($datas,true);
            if(empty($datas)){
                $datas = $post["datas"];
                $datas = htmlspecialchars_decode($datas);
                $datas = json_decode($datas,true);
                if(empty($datas)){
                    return returnJson(1, 'datas error');
                }
            }
            //订单总额
            $all_total_price = 0;

            //处理库存
            $i = 0;
            $wstock_arr = array();
            foreach($datas as $k=>$v){
                $num = intval($v["num"]);
                $goods_id = intval($v["goods_id"]);
                $opt = $v["opt"];

                //选项数据处理
                $_opt = $common->webDealingOptions($opt);
                $wstock_arr[] = [
                    "i" => $i,
                    "goods_id" => $goods_id,
                    "num" => $num,
                    "opt" => $_opt,
                ];
                $i++;
            }
            //判断库存
            $res = $common->wstockTheMoreGoods($wstock_arr);
            if($res["code"] == 1){
                return returnJson(1, $res["msg"]);
            }
            //修改商品和选项数量
            $common->wstockTheChangeGoods($wstock_arr);

            //处理订单详情信息
            $res = $this->dealOrderDetailPart($datas,$user_id,$order_id,$all_total_price,$dtime);
            $all_total_price = $res["all_total_price"];
            $total_weight = $res["total_weight"];
            $total_integral = $res["total_integral"];
            $detail_arr = $res["detail_arr"];

            foreach($detail_arr as $k=>$v){
                $order_detail_model = new OrderDetail();
                $order_detail_model->save($v);
            }
            //OrderDetail::insertAll($datas);


            //添加邮费
            $all_total_price = round(($all_total_price+$express_price),2);
            //修改订单信息
            $order = ModelOrder::where(["id"=>$order_id])->find();
            $order->total_price = $all_total_price;
            $order->pay_price = $all_total_price;
            $order->weight = $total_weight;
            $order->integral = $total_integral;
            $order->save();

            //删除购物车
            $cart = $post["cart"];
            $cart = json_decode($cart,true);
            if(!empty($cart)){
                Cart::where([["id","in",$cart]])->delete();
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return returnJson(1, 'error'.$e->getMessage());
        }

        return returnJson(0, 'success', $order_id);
    }


    //支付订单
    public function payOrder(){
        $common = new Common();
        $post = $this->post;
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);

        //$user_id = $this->authUser();

        $order_id = $post["order_id"];
        $card_id = $post["card_id"];
        $y = $post["y"];
        $m = $post["m"];
        $mmyy = $post["mmyy"];
        $code = $post["code"];
        $first_name = $post["first_name"];
        $last_name = $post["last_name"];

        $_currency = $post["currency"];

        $mmyy= explode('/',$mmyy);
        if(!empty($mmyy)){
            $y = trim($mmyy[1]);
            $m = trim($mmyy[0]);
        }

        $card_id = preg_replace('# #','',$card_id);

        if (empty($order_id)) {
            return returnJson(1, 'order_id not empty');
        }

        $order = ModelOrder::where(["id"=>$order_id])->find();
        if(empty($order)){
            return returnJson(1, 'order not exists');
        }
        if($order["is_delete"]==1){
            return returnJson(1, 'order is delete');
        }
        if($order["status"]==-1){
            return returnJson(1, 'order is cancel');
        }
        if($order["status"]==1){
            return returnJson(1, 'order is complete');
        }
        if($order["is_pay"]==1){
            return returnJson(1, 'order is pay');
        }

        if(empty($card_id)){
            return returnJson(1, "please fill in card ID" );
        }
        if(empty($y)){
            return returnJson(1, "please fill in card expire year" );
        }
        if(empty($m)){
            return returnJson(1, "please fill in card expire month" );
        }
        if(empty($code)){
            return returnJson(1, "please fill in card secure code" );
        }
        if(empty($first_name)){
            return returnJson(1, "please fill in card first name" );
        }
        if(empty($last_name)){
            return returnJson(1, "please fill in card last name" );
        }

        $pay_no = $common->randOrderPayNo();
        $order->pay_no = $pay_no;
        $res = $order->save();
        if(!$res){
            return returnJson(1, 'system error');
        }

        $resArr = array();
        Db::startTrans();
        try {

            $items = "";
            $OrderDetail = OrderDetail::where(["order_id"=>$order["id"]])->select();
            foreach($OrderDetail as $k=>$v){
                $goods_id = $v["goods_id"];
                $goods = Goods::where(["id"=>$goods_id])->find();
                if($k!=0){
                    $items .= '#;#';
                }
                $items .= substr($goods["name_en"],0,100);
                $items .= '#,#'.$v["id"];
                $items .= '#,#'.$v["total_price"];
                $items .= '#,#'.$v["num"];
            }


            $user = User::where(["id"=>$order["user_id"]])->find();
            $m = sprintf("%02d",$m);


            $pay = Pay::where(["is_default"=>1])->find();
            if(empty($pay)){
                return returnJson(1, 'pay setting error');
            }

            $ApiUrl = "https://checkout.welomall.com/v1/authorise";
            if(strpos($pay["name"],"测试")!==false){
                $ApiUrl = "https://testcheckout.welomall.com/v1/authorise";
            }

            if(strpos($this->host,'kuchuangnet.com')!==false){
                $this->host = 'http://kuajing.kuchuangnet.com:88/';
            }

            //多币汇率
            $order_currency = $order["currency"];
            $pay_price = $order["pay_price"];

            $rate = 0;
            $pay_currency = $order_currency;
            $pay_currency_price = $pay_price;

            $res = $this->payCurrencyChange($_currency,$pay_currency,$pay_currency_price,$pay_price,$rate,$items);
            if($res["code"] == 1){
                return returnJson(1, $res["msg"]);
            }
            $rate = $res["rate"];
            $pay_currency = $res["pay_currency"];
            $pay_currency_price = $res["pay_currency_price"];
            $items = $res["items"];

            $merchant_id = $pay["mch_id"];
            $account_id = $pay["sub_id"];
            $order_no = $pay_no;
            $currency = $pay_currency;
            $amount = "".$pay_currency_price;
            $notify_url = $this->host."/api/paynotify/order";
            $sign_key = $pay["key"];
            $handling = "0";  //手续费
            $website = $this->host;
            $shopper_id = $pay["id"];
            $shopper_email = $user["email"];
            $shopper_ip = $this->request->ip();
            $card = $card_id;
            $expiration_year = $y;
            $expiration_month = $m;
            $security_code = $code;


//            var_dump($merchant_id,$account_id,$order_no,$currency,$amount,$first_name,$last_name,$card,$expiration_year,
//                        $expiration_month,$security_code,$shopper_email,$sign_key);die;
            $encryption_data = hash('sha256',$merchant_id.$account_id.$order_no.$currency.$amount.$first_name.$last_name.$card.$expiration_year.
                $expiration_month.$security_code.$shopper_email.$sign_key);


            $post["encryption_data"] = $encryption_data;

            //$notify_url = "https://www.showluggage.com:88/api/paynotify/order";
            //$website = "https://www.showluggage.com:88/";

            $billing_country = substr($currency,0,2);

            $params = [
                "billing_country" => $billing_country,
                "merchant_id" => $merchant_id,
                "account_id" => $account_id,
                "order_no" => $order_no,
                "currency" => $currency,
                "amount" => $amount,
                "notify_url" => $notify_url,
                "sign_key" => $sign_key,
                "handling" => $handling,
                "website" => $website,
                "shopper_id" => $shopper_id,
                "shopper_email" => $shopper_email,
                "shopper_ip" => $shopper_ip,
                "items" => $items,
                "card" => $card,
                "expiration_month" => $expiration_month,
                "expiration_year" => $expiration_year,
                "security_code" => $security_code,
                "first_name" => $first_name,
                "last_name" => $last_name,
                "encryption_data" => $encryption_data,
            ];
            //var_dump($ApiUrl,$params);die;
            $result = $common->send_post($ApiUrl,$params);

            $common->log(json_encode($result),"pay/");
            if(!$result){
                return returnJson(1, 'pay error',array($result,$ApiUrl,$params));
                //throw new \Exception('pay error');
            }

            $no = $result["order_no"];
            $d = ModelOrder::where(["pay_no"=>$no])->find();

            if(empty($d)){
                throw new \Exception('order error');
            }
            if($d->is_pay == 1){
                throw new \Exception('order is pay');
            }

            if ($result['order_status'] == 1) {  //支付成功
                $common->log(json_encode($result),"pay_success/");

                $d->rate = $rate;
                $d->pay_currency = $pay_currency;
                $d->pay_currency_price = $pay_currency_price;

                $d->user_card_id = 0;
                $d->user_card_no = $card_id;

                //订单状态
                $d->order_status_id = 9;

                $d->is_pay = 1;
                $d->pay_no = $pay_no;
                $d->pay_id = $pay["id"];
                $d->pay_time = $dtime;
                $d->transaction_id = $result["transaction_id"];
                $d->pay_result = json_encode($result);
                $d->save();

                $model = new OrderPay();
                $model->order_id = $order["id"];
                $model->transaction_id = $result["transaction_id"];
                $model->pay_id = $pay["id"];
                $model->mch_id = $pay["mch_id"];
                $model->sub_id = $pay["sub_id"];
                $model->pay_no = $pay_no;
                $model->user_card_id = 0;
                $model->user_card_no = $card_id;
                $model->connector = $result["connector"]?$result["connector"]:'';
                $model->save();
            } else {  //支付失败
                throw new \Exception("pay card data error! ".$result['result_info']);
            }

            if(!empty($resArr)){
                foreach($resArr as $res){
                    if(empty($res)){
                        throw new \Exception('error');
                    }
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $order->order_status_id = 5;
            $order->pay_result = json_encode($result);
            $order->save();
            return returnJson(1, 'error! '.$e->getMessage(),$result);
        }

        $Web = Web::where(["id"=>1])->find();
        $notice = $Web["pay_notice_en"];
        $res = [
            "order_id" => $order_id,
            "notice" => $notice,
        ];

        return returnJson(0, 'success', $res);
    }

    public function payCurrencyChange($currency,$pay_currency,$pay_currency_price,$pay_price,$rate,$items){
        $common = new Common();

        if(!empty($currency)){
            $currency = strtoupper($currency);
            $coin = CoinSign::where(["currency"=>$currency])->find();
            if(empty($coin)){
                return ["code"=>1,"msg"=>"params error"];
            }
            $dict = Dict::where(["key"=>"mxnzp_app_id"])->find();
            $mxnzp_app_id = $dict["value"];
            $dict = Dict::where(["key"=>"mxnzp_app_secret"])->find();
            $mxnzp_app_secret = $dict["value"];

            if(empty($mxnzp_app_id) || empty($mxnzp_app_secret)){
                return ["code"=>1,"msg"=>"params error"];
            }

            $coin = CoinSign::where(["is_default"=>1])->find();
            $defaultCurrency = strtoupper($coin["currency"]);

            if($currency != $defaultCurrency){
                $url = "https://www.mxnzp.com/api/exchange_rate/aim";
                $params = [
                    "app_id" => $mxnzp_app_id,
                    "app_secret" => $mxnzp_app_secret,
                    "from" => $defaultCurrency,
                    "to" => $currency,
                ];
                $res = $common->request("POST",$url,$params);
                if(!is_array($res)){
                    $res = json_decode($res,true);
                }
                if($res["code"] != 1){
                    return ["code"=>1,"msg"=>"params error"];
                }

                $pay_currency = $currency;
                $rate = floatval($res["data"]["price"]);
                $pay_currency_price = round((round($pay_price,2)*$rate),2);
                $items = $common->rateGoodsItems($pay_currency_price,$items,$rate);
            }
        }

        return [
            "code" => 0,
            "pay_currency" => $pay_currency,
            "pay_currency_price" => $pay_currency_price,
            "rate" => $rate,
            "items" => $items,
        ];
    }

    //订单支付(跳转)
    public function payRedirect(){
        $post = $this->post;
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);

        $common = new Common();

        $order_id = $post["order_id"];

        $_currency = $post["currency"];

        if (empty($order_id)) {
            return returnJson(1, 'order_id not empty');
        }

        $order = ModelOrder::where(["id"=>$order_id])->find();
        if(empty($order)){
            return returnJson(1, 'order not exists');
        }
        if($order["is_delete"]==1){
            return returnJson(1, 'order is delete');
        }
        if($order["status"]==-1){
            return returnJson(1, 'order is cancel');
        }
        if($order["status"]==1){
            return returnJson(1, 'order is complete');
        }
        if($order["is_pay"]==1){
            return returnJson(1, 'order is pay');
        }

        $pay_no = $common->randOrderPayNo();

        $pay = Pay::where(["is_default"=>1])->find();
        if(empty($pay)){
            return returnJson(1, 'pay setting error');
        }

        $ApiUrl = "https://checkout.welomall.com/v1/checkout";
        if(strpos($pay["name"],"测试")!==false){
            $ApiUrl = "https://testcheckout.welomall.com/v1/checkout";
        }


        $items = "";
        $OrderDetail = OrderDetail::where(["order_id"=>$order["id"]])->select();
        foreach($OrderDetail as $k=>$v){
            $goods_id = $v["goods_id"];
            $goods = Goods::where(["id"=>$goods_id])->find();
            if($k!=0){
                $items .= '#;#';
            }
            $items .= substr($goods["name_en"],0,100);
            $items .= '#,#'.$v["id"];
            $items .= '#,#'.$v["total_price"];
            $items .= '#,#'.$v["num"];
        }

        $user = User::where(["id"=>$order["user_id"]])->find();

        $web_host = str_replace(':88','',$this->host);

        //多币汇率
        $order_currency = $order["currency"];
        $pay_price = $order["pay_price"];

        $rate = 0;
        $pay_currency = $order_currency;
        $pay_currency_price = $pay_price;

        $res = $this->payCurrencyChange($_currency,$pay_currency,$pay_currency_price,$pay_price,$rate,$items);
        if($res["code"] == 1){
            return returnJson(1, $res["msg"]);
        }
        $rate = $res["rate"];
        $pay_currency = $res["pay_currency"];
        $pay_currency_price = $res["pay_currency_price"];
        $items = $res["items"];

        //保存汇率支付
        $order = ModelOrder::where(["id"=>$order["id"]])->find();
        $order->pay_id = $pay["id"];
        $order->pay_no = $pay_no;
        $order->rate = $rate;
        $order->pay_currency = $pay_currency;
        $order->pay_currency_price = $pay_currency_price;
        $res = $order->save();
        if(!$res){
            return returnJson(1, 'system error');
        }


        $merchant_id = $pay["mch_id"];
        $account_id = $pay["sub_id"];
        $currency = $pay_currency;
        $amount = "".$pay_currency_price;
        $return_url = $web_host."/payResult/id=".$order["id"];
        $notify_url = $this->host."/api/paynotify/redirectNotify";
        $cancel_url = $this->host."/api/paynotify/redirectCancel";
        $shopper_id = "a".$pay["id"];
        $shopper_email = $user["email"];
        $shopper_phone = $user["mobile"];
        $shopper_ip = $this->request->ip();
        $sign_key = $pay["key"];

        $encryption_data = hash('sha256',$merchant_id.$account_id.$pay_no.$currency.$amount.$return_url.$sign_key);

        if(empty($shopper_phone)){
            $shopper_phone = $order["delivery_mobile"];
        }
        if(!empty($shopper_phone)){
            preg_match_all('/\d/is',$shopper_phone,$match);
            $shopper_phone = implode("",$match[0]);
        }
        if(empty($shopper_phone)){
            $shopper_phone = $user["id"];
        }


        $params = [
            "url" => $ApiUrl,
            "merchant_id" => $merchant_id,
            "account_id" => $account_id,
            "order_no" => $pay_no,
            "currency" => $pay_currency,  //CNY,USD
            "amount" => "".$pay_currency_price,
            "handling" => "0",
            "shopper_id" => $shopper_id,
            "shopper_email" => $shopper_email,
            "shopper_phone" => $shopper_phone,
            "items" => $items,
            "return_url" => $return_url,
            "notify_url" => $notify_url,
            "cancel_url" => $cancel_url,
            "encryption_data" => $encryption_data,

            "first_name" => $order["delivery_first_name"],
            "last_name" => $order["delivery_last_name"],
            "billing_country" => $order["delivery_country_iso2"],
            "billing_state" => $order["delivery_province"],
            "billing_city" => $order["delivery_city"],
            "billing_address" => $order["delivery_address"],
            "billing_postal_code" => $order["delivery_postcode"],

            "delivery_firstname" => $order["billing_first_name"],
            "delivery_lastname" => $order["billing_last_name"],
            "delivery_country" => $order["billing_country_iso2"],
            "delivery_state" => $order["billing_province"],
            "delivery_city" => $order["billing_city"],
            "delivery_address" => $order["billing_address"],
            "delivery_postal_code" => $order["billing_postcode"],

            //"open3d" => "no3DS",
            //"default_lang" => "en_US",
            //"verify_billing_address" => "NO",
        ];

        return returnJson(0, 'success',$params);
    }


    //订单列表
    public function orderList(){
        $post = $this->post;
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);

        $page = $post["page"];
        $limit = $post["limit"];
        $page = $page?$page:1;
        $limit = $limit?$limit:10;

        $status = $post["status"];
        if(!is_numeric($status)){
            $status = false;
        }
        $is_pay = $post["is_pay"];
        if(!is_numeric($is_pay)){
            $is_pay = false;
        }
        $is_transport = $post["is_transport"];
        if(!is_numeric($is_transport)){
            $is_transport = false;
        }

        $user_id = $this->authUser();

        $query = new ModelOrder();
        $query = $query->where(["user_id"=>$user_id,"is_delete"=>0]);


        if($status !== false){
            $query = $query->where(["status"=>$status]);
        }
        if($is_pay !== false){
            $query = $query->where(["is_pay"=>$is_pay]);
        }
        if($is_transport !== false){
            $query = $query->where(["is_transport"=>$is_transport]);
        }


        $query = $query->order("id desc");
        $data = $query->paginate($limit);
        $count = $data->total();
        $list = $data->items();

        $arr = array();
        foreach($list as $k=>$v){
            $arr[$k]["id"] = $v["id"];
            $arr[$k]["no"] = $v["no"];
            $arr[$k]["currency"] = $v["currency"];
            $arr[$k]["status"] = $v["status"];
            $order_status_id = $v["order_status_id"];
            $OrderStatus = OrderStatus::where(["id"=>$order_status_id])->find();
            $arr[$k]["order_status_name"] = $OrderStatus["name_en"];
            $arr[$k]["total_price"] = $v["total_price"];
            $arr[$k]["pay_price"] = $v["pay_price"];
            $arr[$k]["express_price"] = $v["express_price"];
            $arr[$k]["pay_no"] = $v["pay_no"];
            $arr[$k]["is_pay"] = $v["is_pay"];
            $arr[$k]["pay_time"] = $v["pay_time"]?$v["pay_time"]:'';
            $arr[$k]["is_transport"] = $v["is_transport"];
            $arr[$k]["transport_time"] = $v["transport_time"]?$v["transport_time"]:'';
            $arr[$k]["is_refund"] = $v["is_refund"];
            $arr[$k]["refund_time"] = $v["refund_time"]?$v["refund_time"]:'';
            $arr[$k]["apply_refund"] = $v["apply_refund"];
            $arr[$k]["apply_time"] = $v["apply_time"]?$v["apply_time"]:'';
            $arr[$k]["refund_desc"] = $v["refund_desc"]?$v["refund_desc"]:'';
            $arr[$k]["remarks"] = $v["remarks_en"]?$v["remarks_en"]:'';
            $arr[$k]["complete_time"] = $v["complete_time"]?$v["complete_time"]:'';
            $arr[$k]["create_time"] = $v["create_time"];

            $user = array();
            $user["id"] = $v["user_id"];
            $user["user_group_value"] = $v["user_group_value"];
            $user["first_name"] = $v["user_first_name"];
            $user["last_name"] = $v["user_last_name"];
            $user["email"] = $v["user_email"];
            $user["intmobile_value"] = $v["user_intmobile_value"];
            $user["mobile"] = $v["user_mobile"];
            $arr[$k]["user"] = $user;

            $billing = array();
            $billing["first_name"] = $v["billing_first_name"];
            $billing["last_name"] = $v["billing_last_name"];
            $billing["intmobile_value"] = $v["billing_intmobile_value"];
            $billing["mobile"] = $v["billing_mobile"];
            $billing["company"] = $v["billing_company"];
            $billing["country"] = $v["billing_country"];
            $billing["province"] = $v["billing_province"];
            $billing["city"] = $v["billing_city"];
            $billing["district"] = $v["billing_district"];
            $billing["address"] = $v["billing_address"];
            $billing["street"] = $v["billing_street"];
            $billing["postcode"] = $v["billing_postcode"];
            $arr[$k]["billing"] = $billing;

            $delivery = array();
            $delivery["first_name"] = $v["delivery_first_name"];
            $delivery["last_name"] = $v["delivery_last_name"];
            $delivery["intmobile_value"] = $v["delivery_intmobile_value"];
            $delivery["mobile"] = $v["delivery_mobile"];
            $delivery["company"] = $v["delivery_company"];
            $delivery["country"] = $v["delivery_country"];
            $delivery["province"] = $v["delivery_province"];
            $delivery["city"] = $v["delivery_city"];
            $delivery["district"] = $v["delivery_district"];
            $delivery["address"] = $v["delivery_address"];
            $delivery["street"] = $v["delivery_street"];
            $delivery["postcode"] = $v["delivery_postcode"];
            $arr[$k]["delivery"] = $delivery;

            $detail = array();
            $OrderDetail = OrderDetail::where(["order_id"=>$v["id"]])->select();
            foreach($OrderDetail as $k1=>$v1){
                $detail[$k1]["id"] = $v1["id"];
                $detail[$k1]["goods_id"] = $goods_id = $v1["goods_id"];
                $goods = Goods::where(["id"=>$goods_id])->find();
                $detail[$k1]["goods_name"] = $v1["goods_name_en"];
                $detail[$k1]["pic"] = $this->host.$goods["pic"];
                $detail[$k1]["thumb"] = $this->host.$goods["thumb"];
                $detail[$k1]["num"] = $v1["num"];
                $detail[$k1]["price"] = $v1["price"];
                $detail[$k1]["total_price"] = $v1["total_price"];
                $detail[$k1]["no"] = $v1["no"];
                $detail[$k1]["sku"] = $v1["sku"];

                $options = $v1["options"];
                $options = json_decode($options,true);
                $options_arr = array();
                foreach($options as $k2=>$v2){
                    $options_arr[$k2]["opt_name_en"] = $v2["opt_name_en"];

                    $options_arr[$k2]["options_name_en"] = $v2["options"]["options_name_en"];

                    $options_arr[$k2]["str"] = $options_arr[$k2]["opt_name_en"].': '.$options_arr[$k2]["options_name_en"];
                }
                $detail[$k1]["options"] = $options_arr;
            }
            $arr[$k]["detail"] = $detail;
        }

        $res = [
            'row_count' => $count,
            'page_count' => $data->lastPage(),
            'list' => $arr,
        ];

        return returnJson(0, "success", $res);
    }


    //订单详情
    public function orderDetail(){
        $post = $this->post;
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);

        $common = new Common();

        $page = $post["page"];
        $limit = $post["limit"];
        $page = $page?$page:1;
        $limit = $limit?$limit:10;

        $user_id = $this->authUser();

        $order_id = $post["order_id"];
        if(empty($order_id)){
            return returnJson(1, "order_id not empty");
        }

        $order = ModelOrder::where(["id"=>$order_id,"user_id"=>$user_id,"is_delete"=>0])->find();
        if(empty($order)){
            return returnJson(1, "order not exists");
        }

        $arr = array();
        $arr["id"] = $order["id"];
        $arr["no"] = $order["no"];
        $arr["currency"] = $order["currency"];
        $arr["status"] = $order["status"];
        $order_status_id = $order["order_status_id"];
        $OrderStatus = OrderStatus::where(["id"=>$order_status_id])->find();
        $arr["order_status_name"] = $OrderStatus["name_en"];
        $arr["total_price"] = $order["total_price"];
        $arr["pay_price"] = $order["pay_price"];
        $arr["express_price"] = $order["express_price"];
        $arr["pay_no"] = $order["pay_no"];
        $arr["is_pay"] = $order["is_pay"];
        $arr["pay_time"] = $order["pay_time"]?$order["pay_time"]:'';
        $arr["is_transport"] = $order["is_transport"];
        $arr["transport_time"] = $order["transport_time"]?$order["transport_time"]:'';
        $arr["is_refund"] = $order["is_refund"];
        $arr["refund_time"] = $order["refund_time"]?$order["refund_time"]:'';
        $arr["apply_refund"] = $order["apply_refund"];
        $arr["apply_time"] = $order["apply_time"]?$order["apply_time"]:'';
        $arr["refund_desc"] = $order["refund_desc"]?$order["refund_desc"]:'';
        $arr["remarks"] = $order["remarks_en"]?$order["remarks_en"]:'';
        $arr["complete_time"] = $order["complete_time"]?$order["complete_time"]:'';
        $arr["create_time"] = $order["create_time"];

        $user = array();
        $user["id"] = $order["user_id"];
        $user["user_group_value"] = $order["user_group_value"];
        $user["first_name"] = $order["user_first_name"];
        $user["last_name"] = $order["user_last_name"];
        $user["email"] = $order["user_email"];
        $user["intmobile_value"] = $order["user_intmobile_value"];
        $user["mobile"] = $order["user_mobile"];
        $arr["user"] = $user;

        $billing = array();
        $billing["first_name"] = $order["billing_first_name"];
        $billing["last_name"] = $order["billing_last_name"];
        $billing["intmobile_value"] = $order["billing_intmobile_value"];
        $billing["mobile"] = $order["billing_mobile"];
        $billing["company"] = $order["billing_company"];
        $billing["country"] = $order["billing_country"];
        $billing["province"] = $order["billing_province"];
        $billing["city"] = $order["billing_city"];
        $billing["district"] = $order["billing_district"];
        $billing["address"] = $order["billing_address"];
        $billing["street"] = $order["billing_street"];
        $billing["postcode"] = $order["billing_postcode"];
        $arr["billing"] = $billing;

        $delivery = array();
        $delivery["first_name"] = $order["delivery_first_name"];
        $delivery["last_name"] = $order["delivery_last_name"];
        $delivery["intmobile_value"] = $order["delivery_intmobile_value"];
        $delivery["mobile"] = $order["delivery_mobile"];
        $delivery["company"] = $order["delivery_company"];
        $delivery["country"] = $order["delivery_country"];
        $delivery["province"] = $order["delivery_province"];
        $delivery["city"] = $order["delivery_city"];
        $delivery["district"] = $order["delivery_district"];
        $delivery["address"] = $order["delivery_address"];
        $delivery["street"] = $order["delivery_street"];
        $delivery["postcode"] = $order["delivery_postcode"];
        $arr["delivery"] = $delivery;

        $detail = array();
        $OrderDetail = OrderDetail::where(["order_id"=>$order["id"]])->select();
        foreach($OrderDetail as $k1=>$v1){
            $detail[$k1]["id"] = $v1["id"];
            $detail[$k1]["goods_id"] = $goods_id = $v1["goods_id"];
            $goods = Goods::where(["id"=>$goods_id])->find();
            $detail[$k1]["goods_name"] = $v1["goods_name_en"];
            $detail[$k1]["pic"] = $this->host.$goods["pic"];
            $detail[$k1]["thumb"] = $this->host.$goods["thumb"];
            $detail[$k1]["num"] = $v1["num"];
            $detail[$k1]["price"] = $v1["price"];
            $detail[$k1]["total_price"] = $v1["total_price"];
            $detail[$k1]["no"] = $v1["no"];
            $detail[$k1]["sku"] = $v1["sku"];

            $options = $v1["options"];
            $options = json_decode($options,true);
            $options_arr = array();
            foreach($options as $k2=>$v2){
                $options_arr[$k2]["opt_name_en"] = $v2["opt_name_en"];

                $options_arr[$k2]["options_name_en"] = $v2["options"]["options_name_en"];

                $options_arr[$k2]["str"] = $options_arr[$k2]["opt_name_en"].': '.$options_arr[$k2]["options_name_en"];
            }
            $detail[$k1]["options"] = $options_arr;
        }
        $arr["detail"] = $detail;

        //物流轨迹
        $shipperCode = $order["shipperCode"];
        $trace = array();
        if(!empty($shipperCode)){
            $res = $this->funcTrace($shipperCode);
            if($res["code"] == 0){
                $trace = $res["data"];
            }
        }
        $arr["trace"] = $trace;

        //支付跳转方式
        $d = Web::where(["id"=>1])->find();
        $pay_type = intval($d["welopay_paytype"]);
        $arr["pay_type"] = $pay_type;

        //跳转支付参数
        $pay_parrams = array();
        if($order["is_pay"]==0){
            $pay_no = $common->randOrderPayNo();

            $pay = Pay::where(["is_default"=>1])->find();
            if(empty($pay)){
                return returnJson(1, 'pay setting error');
            }

            $ApiUrl = "https://checkout.welomall.com/v1/checkout";
            if(strpos($pay["name"],"测试")!==false){
                $ApiUrl = "https://testcheckout.welomall.com/v1/checkout";
            }

            $order->pay_id = $pay->id;
            $order->pay_no = $pay_no;
            $res = $order->save();
            if(!$res){
                return returnJson(1, 'system error');
            }

            $items = "";
            $OrderDetail = OrderDetail::where(["order_id"=>$order["id"]])->select();
            foreach($OrderDetail as $k=>$v){
                $goods_id = $v["goods_id"];
                $goods = Goods::where(["id"=>$goods_id])->find();
                if($k!=0){
                    $items .= '#;#';
                }
                $items .= substr($goods["name_en"],0,100);
                $items .= '#,#'.$v["id"];
                $items .= '#,#'.$v["total_price"];
                $items .= '#,#'.$v["num"];
            }

            $user = User::where(["id"=>$order["user_id"]])->find();

            $web_host = str_replace(':88','',$this->host);

            $merchant_id = $pay["mch_id"];
            $account_id = $pay["sub_id"];
            $currency = $order["currency"];
            $amount = "".$order["pay_price"];
            $return_url = $web_host."/payResult/id=".$order["id"];
            $notify_url = $this->host."/api/paynotify/redirectNotify";
            $cancel_url = $this->host."/api/paynotify/redirectCancel";
            $shopper_id = $pay["id"];
            $shopper_email = $user["email"];
            $shopper_ip = $this->request->ip();
            $sign_key = $pay["key"];

            $encryption_data = hash('sha256',$merchant_id.$account_id.$pay_no.$currency.$amount.$return_url.$sign_key);

            $pay_parrams = [
                "url" => $ApiUrl,
                "merchant_id" => $merchant_id,
                "account_id" => $account_id,
                "order_no" => $pay_no,
                "currency" => $currency,  //CNY,USD
                "amount" => $amount,
                "handling" => "0",
                "shopper_id" => $shopper_id,
                "shopper_email" => $shopper_email,
                "items" => $items,
                "return_url" => $return_url,
                "notify_url" => $notify_url,
                "cancel_url" => $cancel_url,
                "encryption_data" => $encryption_data,
            ];
        }
        $arr["pay_parrams"] = $pay_parrams;


        return returnJson(0, "success", $arr);
    }

    //取消订单
    public function orderCancel(){
        $post = $this->post;
        $common = new Common();
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);
        $arr = array();

        $order_id = $post["order_id"];
        if(empty($order_id)){
            return returnJson(1, 'order_id not empty');
        }

        $user_id = $this->authUser();

        $data= ModelOrder::where(["user_id"=>$user_id,"id"=>$order_id])->find();
        if (empty($data)) {
            return returnJson(1, 'order not exists');
        }
        if($data["status"] != 0){
            return returnJson(1, "order is complete, can't cancel");
        }
        if($data["is_pay"] == 1){
            return returnJson(1, "order is pay, can't cancel");
        }

        $resArr = array();
        Db::startTrans();
        try {
            $data->order_status_id = 7;
            $data->status = -1;
            $data->cancel_time = $dtime;
            $data->save();

            //恢复库存
            $common->restoreOrderStock($order_id);

            if(!empty($resArr)){
                foreach($resArr as $res){
                    if(empty($res)){
                        throw new \Exception('error');
                    }
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return returnJson(1, 'error'.$e->getMessage());
        }

        return returnJson(0, 'success');

    }


    //删除订单
    public function orderDelete(){
        $post = $this->post;
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);
        $arr = array();

        $order_id = $post["order_id"];
        if(empty($order_id)){
            return returnJson(1, 'order_id not empty');
        }

        $user_id = $this->authUser();

        $data= ModelOrder::where(["user_id"=>$user_id,"id"=>$order_id])->find();
        if (empty($data)) {
            return returnJson(1, 'order not exists');
        }
        if($data["status"] == 0){
            return returnJson(1, "order not complete, can't delete");
        }

        $resArr = array();
        Db::startTrans();
        try {
            $data->is_delete = 1;
            $data->deletetime = $dtime;
            $data->save();

            if(!empty($resArr)){
                foreach($resArr as $res){
                    if(empty($res)){
                        throw new \Exception('error');
                    }
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return returnJson(1, 'error'.$e->getMessage());
        }

        return returnJson(0, 'success');
    }


    //申请撤销订单
    public function orderApplyRefund(){
        $post = $this->post;
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);
        $arr = array();

        $order_id = $post["order_id"];
        $refund_desc = $post["desc"];

        if(empty($order_id)){
            return returnJson(1, 'order_id not empty');
        }

        $user_id = $this->authUser();

        $data= ModelOrder::where(["user_id"=>$user_id,"id"=>$order_id])->find();
        if (empty($data)) {
            return returnJson(1, 'order not exists');
        }
        if($data["status"] != 0){
            return returnJson(1, "order is complete, can't apply refund");
        }
        if($data["is_pay"] == 0){
            return returnJson(1, "order not pay, can't apply refund");
        }
        if($data["is_transport"] == 1){
            return returnJson(1, "order in transit, can't apply refund");
        }
        if($data["apply_refund"] == 1){
            return returnJson(1, "order is apply");
        }

        $resArr = array();
        Db::startTrans();
        try {
            $data->apply_refund = 1;
            $data->apply_time = $dtime;
            $data->refund_desc = $refund_desc?$refund_desc:'';
            $data->save();

            if(!empty($resArr)){
                foreach($resArr as $res){
                    if(empty($res)){
                        throw new \Exception('error');
                    }
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return returnJson(1, 'error'.$e->getMessage());
        }

        return returnJson(0, 'success');

    }

    //查询物流轨迹
    public function orderTrace(){
        $post = $this->post;
        $common = new Common();
        $time = time();
        $dtime = date("Y-m-d H:i:s", $time);
        $arr = array();

        $order_id = $post["order_id"];

        if(empty($order_id)){
            return returnJson(1, 'order_id not empty');
        }

        $user_id = $this->authUser();

        $data= ModelOrder::where(["user_id"=>$user_id,"id"=>$order_id])->find();
        if (empty($data)) {
            return returnJson(1, 'order not exists');
        }
        if($data["is_transport"] == 0){
            return returnJson(1, "order not delivery");
        }

        $shipperCode = $data["shipperCode"];


        $res = $this->funcTrace($shipperCode);
        if($res["code"] == 1){
            return returnJson(1,$res["msg"]);
        }

        $list = $res["data"];

        return returnJson(0, 'success',$list);
    }

    public function funcTrace($shipperCode){
        $common = new Common();

        $ApiUrl = 'http://47.119.160.247:6210/api/OrderInterface/QueryTrack';

        $params = [
            "shipperCode"=>$shipperCode,
        ];

        $res = $res_str = $common->https_request($ApiUrl,$params);

        if(!is_array($res)){
            $res = json_decode($res,true);
        }

        if($res["IsSuccess"] !== true){
            return ["code"=>1,"msg"=>"error:".$res["Message"]];
        }

        $list = $res["Data"];

        return ["code"=>0,"data"=>$list];
    }

}