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

namespace app\admin\controller\bbfxshop\order;

use app\admin\controller\bbfxshop\Base;
use think\Db;

use app\common\model\bbfxshop\FenxiaoLevel;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\CloudWarehouse;
use app\common\model\bbfxshop\Goods;

class Create extends Base 
{
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Order;
    }

    public function confirm(){
        global $_W;
        $set = $_W['base'];
        $params = $this->param();
        
        $coupon_id = $params['coupon_id'];
        $address = $params['address'];

        $user = User::getInfo($params['user_id'][0]);
        if(empty($user)){
            __error("请选择下单用户");
        }

        $goods_all = $params['goods'];
        if(empty($goods_all)){
            __error("请选择下单商品");
        }
        
        $goods_ids = [];
        foreach($goods_all as $key => $val){
            $goods_ids[] = $val['id'];
        }
        $goods_list = Db::name("bbfx_goods")->where(['id'=>['in',$goods_ids],'status'=>1])->select();
        
        if(empty($goods_list)){
            __error("下单商品信息错误");
        }

        $goods_list = array_skey($goods_list,"id");
        $goods = [];
        foreach($goods_all as $key => $val){
            if(empty($goods_list[$val['id']])){
                __error("下单商品信息错误");
            }
            
            $info = $goods_list[$val['id']];
            $info['total'] = $val['total'];
            if($info['is_spec'] == 1){
                $sku = Db::name("bbfx_goods_spec_sku")->where(['id'=>$val['sku_id']])->find();
                if(empty($sku)){
                    __error("请选择规格");
                }
                if(!empty($sku['thumb'])){
                    $info['thumb'] = cdnurl($sku['thumb']);
                }
                $info['sku'] = $sku;
                $info['sku_id'] = $sku['id'];
                $info['price'] = $sku['price'];
                $info['sku_name'] = $sku['sku_name'];
                
            }
            $goods[] = $info;
        }
        
        if(empty($goods)){
            __error("下单商品信息错误");
        }
        
        
        
        $delivery_method_list = [];
        $delivery_method = 0;
        if($goods[0]['type'] == 2){
            $g_delivery_method = $goods[0]['delivery_method'];
            $delivery_method = intval($params['delivery_method']);
            $arr = [];
            if($g_delivery_method == 1 || $g_delivery_method == 3){
                $delivery_method_list[] = ['name'=>'快递配送','value'=>1];
                $arr[] = 1;
            }
            if($g_delivery_method == 2 || $g_delivery_method == 3){
                $delivery_method_list[] = ['name'=>'门店核销','value'=>2];
                $arr[] = 2;
            }
            if(!in_array($delivery_method,$arr)){
                $delivery_method = $arr[0];
            }
            if(empty($delivery_method)){
                $delivery_method = 1;
            }
        }
        else if(($goods[0]['type'] == 4 && $goods[0]['is_hexiao'] == 1) || $goods[0]['type'] == 3){
            $delivery_method = 2;
            $delivery_method_list[] = ['name'=>'门店核销','value'=>2];
        }
        $is_gift_goods = 0;
        $hexiao_info_required = 0;
        foreach($goods as $key => $val){
            $plugin =  iunserializer($val['plugin']);
            if($plugin['gift']['status'] == 1){
                $is_gift_goods = 1;
            }
            if($val['hexiao_info_required'] == 1){
                $hexiao_info_required = 1;
            }
        }
        
        $result = $this->model->calculateMoney($goods,$user,$coupon_id,$delivery_method,$address);
        
        $total_fee = $result['total_price'];
        $total_price = $result['total_price'];
        $totalNum = $result['totalNum'];
        $express_fee = $result['express_fee'];
        $discount_price = $result['discount_price'];
        $original_price = $result['original_price'];
        $total_fee = round($total_price + $express_fee,2);
        foreach ($goods as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
        }
        unset($val);
        
        $order_repurchase_currency = 0;
        // $repurchase_currency = floatval($user['repurchase_currency']);
        // if($repurchase_currency > 0 && $set['is_repurchase_currency_deduct'] == 1){
        //     if($total_fee > $repurchase_currency){
        //         $order_repurchase_currency = $repurchase_currency;
        //         $total_fee = round($total_fee - $repurchase_currency,2);
        //     }
        //     else{
        //         $order_repurchase_currency = $total_fee;
        //         $total_fee = 0;
        //     }
        // }
        
        $plugin = iunserializer($goods[0]['plugin']);
        $form_list = [];
        if($plugin['form']['status'] == 1){
            $form_list = $plugin['form']['list'];
        }
        
        $data = array(
            'form_list'=>$form_list,
            'goods'=>$goods,
            'total_fee'=>$total_fee,
            'order_repurchase_currency'=>$order_repurchase_currency,
            'original_price'=>$original_price,
            'discount_price'=>$discount_price,
            'discount_vip_price'=>$result['discount_vip_price'],
            'discount_coupon_price'=>$result['discount_coupon_price'],
            'totalNum'=>$totalNum,
            'total_price'=>$total_price,
            'delivery_method_list'=>$delivery_method_list,
            'delivery_method'=>$delivery_method,
            'express_fee'=>$express_fee,
            'hexiao_info_required'=>$hexiao_info_required,
            'is_gift_goods'=>$is_gift_goods
        );
        if(!empty($result['coupon'])){
            $data['coupon'] = $result['coupon'];
        }
        
        __success("操作成功",$data);
    }
    
    public function submit(){
        $params = $this->param();
        $user_ids = $params['user_id'];
        $paytype = $params['paytype'];

        foreach($user_ids as $key => $user_id){
            $params['user_id'] = $user_id;
            $params['create_type'] = 99;
            $result = \app\common\model\bbfxshop\OrderCreate::create($params);
            if($result['code'] == 1){
                $order_no = $result['data']['order_no'];
                $order_id = $result['data']['order_id'];

                $order = Db::name("bbfx_order")->where(['id'=>$order_id])->find();

                $real_price = max(0,round($order['price'] - $order['repurchase_currency'],2));
                $order_trade_no = date('YmdHis').random(8,true);
                $pay_order = array(
                    "uniacid"=>UNIACID,
                    "openid"=>'',
                    "order_trade_no"=>$order_trade_no,
                    "order_no"=>$order_no,
                    "order_id"=>$order_id,
                    "price"=>$real_price,
                    "order_type"=>1,
                    "platform"=>'admin',
                    "createtime"=>time()
                );

                Db::name("bbfx_pay_order")->insert($pay_order);
                
                $is_pay = true;
                if($paytype == 2){
                    $res = User::setUserMoney($order['user_id'],-$real_price,1,1,"后台录单商品支付",$order);
                    if(empty($res)){
                        $is_pay = false;
                    }
                }
                if($is_pay){
                    $this->model->payResult($order_trade_no,$paytype);
                }
            }
            else{
                __result($result);
            }
        }
        
        __success("操作成功");
    }
    
    public function getGoodsDetail(){
        $goods_id = $this->param("goods_id/d");
        $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'status'=>1,'id'=>$goods_id])->find();
        if(empty($goods)){
            __error("商品信息错误");
        }

        if($goods['is_spec'] == 1){
            $suk_list = Db::name("bbfx_goods_spec_sku")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->select();
            $goods['sku_list'] = $suk_list;
        }

        __success("操作成功",['goods'=>$goods]);
    }

    public function getStoreList(){
        $goods_ids = $this->param("goods_ids/s");
        $page = $this->param("page/d");
        $is_reservation = $this->param("is_reservation/d");
        $keyword = $this->param("keyword/s");
        $lat = $this->param("lat/f");
        $lng = $this->param("lng/f");
        $goods_type = $this->param("goods_type/d");
        $page = max(1,$page);
        $limit = 10;
        
        
        $list = [];
        if(!empty($goods_ids)){
            
            $where = ['uniacid'=>UNIACID,'status'=>1];
            
            if(!empty($keyword)){
                $where['name'] = ['like','%'.$keyword.'%'];
            }
            
            
            $goods_ids = explode(",",$goods_ids);
            if($goods_type == 1){
                $goods = Db::name("bbfx_scoreshop_goods")->where(['uniacid'=>UNIACID,'status'=>1,'type'=>['in',[2,4]],'id'=>['in',$goods_ids]])->field("id,type,delivery_method,is_hexiao,hexiao_store_type")->select();
                $where['mid'] = 0;
            }
            else if($goods_type == 2){
                $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>['in',$goods_ids]])->select();
                $goods_ids = array_column($pintuan_goods,"goods_id");
                $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'status'=>1,'type'=>['in',[2,4]],'id'=>['in',$goods_ids]])->field("id,type,delivery_method,is_hexiao,hexiao_store_type")->select();
                $where['mid'] = 0;
            }
            else{
                $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'status'=>1,'type'=>['in',[2,4]],'id'=>['in',$goods_ids]])->field("id,mid,type,delivery_method,is_hexiao,hexiao_store_type")->select();
                
                $mid = 0;
                if(!empty($goods)){
                    foreach ($goods as $k => $v){
                        if($v['mid'] > 0){
                            $mid = $v['mid'];
                        }
                    }
                }
                
                $where['mid'] = $mid;
            }
            
            
            
            $store_list = Db::name("bbfx_store")->where($where)->order("sort desc")->field("id,user_id,name,logo,realname,mobile,yy_time,province,city,area,address,lng,lat,is_reservation,score,introduction")->select();
            
            
            foreach ($store_list as $key => $val){
                $flag = true;
                foreach ($goods as $k => $v){
                    if(($v['type'] == 2 && ($v['delivery_method'] == 2 || $v['delivery_method'] == 3)) || ($v['type'] == 4 && $v['is_hexiao'] == 1)){
                        
                        if($v['hexiao_store_type'] == 1){
                            if($goods_type == 1){
                                $store_goods = Db::name("bbfx_scoreshop_store_goods")->where(['uniacid'=>UNIACID,'goods_id'=>$v['id'],'store_id'=>$val['id']])->find();
                            }
                            else{
                                $store_goods = Db::name("bbfx_store_goods")->where(['uniacid'=>UNIACID,'goods_id'=>$v['id'],'store_id'=>$val['id']])->find();
                            }
                            
                            if(empty($store_goods)){
                                $flag = false;
                            }
                        
                        }
                    }
                }
                if($flag){
                    $list[] = $val;
                }
            }
            $total = count($list);
        }
        else{
            
            $where = ['uniacid'=>UNIACID,'mid'=>0,'status'=>1,'is_reservation'=>$is_reservation];
            
            if(!empty($keyword)){
                $where['name'] = ['like','%'.$keyword.'%'];
            }
            
            $list = Db::name("bbfx_store")->where($where)->order("sort desc")->field("id,user_id,name,logo,realname,mobile,yy_time,province,city,area,address,lng,lat,is_reservation,score,introduction")->select();
            $total = Db::name("bbfx_store")->where($where)->count();
            
        }
        
        foreach ($list as $key => &$val){
            $val['logo'] = cdnurl($val['logo']);
            $distance = 9999999;
            if(!empty($lng) || !empty($lat) || !empty($val['lng']) || !empty($val['lat'])){
                $distance = getdistance($lng,$lat,$val['lng'],$val['lat']);
            }
            $val['distance'] = $distance;
            $val['distanceText'] = "";
            if($distance != 9999999){
                $val['distanceText'] = $distance."km";
            }
        }
        unset($val);
        
        $distances = array_column($list,'distance');
        array_multisort($distances,SORT_ASC,$list);
        
        $list = array_slice($list, ($page-1)*$limit, $limit);
        
        __success("操作成功",['list'=>$list,'total'=>$total]);
    }
}