<?php
namespace app\shared\logic\user;
use app\shared\model\User;
use app\shared\model\GoodsOrder;
use app\shared\model\GoodsOrderDetail;
use app\shared\model\Goods;
use app\shared\model\App;
use wechatpay\WechatPay;
use app\shared\model\Store;
use app\shared\model\Coupon;
use app\shared\model\CouponUser;
use app\shared\model\StoreCoupon;
use app\shared\model\StoreCouponUser;
use app\shared\model\CardUserOrder;
use app\shared\model\Card;
use app\shared\model\CardUser;
use app\shared\model\Option;
use app\shared\model\GoodsAttr;
use think\exception\ValidateException;
use app\BaseController;
class GoodsOrderForm extends  UserForm
{
  //列表
  public function list(){
      $status=input('status');
      $query=GoodsOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'is_delete'=>0]);
      if($status!='-10'){
         $query->where(['status'=>$status]);
      }
      $list=$query->page($this->page)->limit(10)->field('id,store_id,pay_price,name,mobile,address,order_no,status,create_time,snapshot')->order('id DESC')->select();
      $status_arr=[0=>'待付款',1=>'已付款',2=>'已发货',3=>'已完成',-1=>'已取消',-2=>'已退款'];
      $app=App::where(['id'=>$this->acid])->field('id,logo,name')->find();
      $app['name']="平台商城";
      $app['logo']=get_file_url($app['logo']);
      foreach ($list as $key => &$value) {
          $snapshot=json_decode($value['snapshot'],1);
          $value['snapshot']=$snapshot;
          if($value['store_id']==0){
             $value['store_info']=$app;
          }else{
             $store=Store::where(['acid'=>$this->acid,'id'=>$value['store_id']])->field('id,logo,name')->find();
             $store['logo']=get_file_url($store['logo']);
             $value['store_info']=$store;
          }
         
          $value['status_title']=$status_arr[$value['status']];
          $value['goods_num']=array_sum(array_column($value['snapshot'], 'num'));

      }
      return fetchJson($list);
  }
  //提交预览
  public function submitPreview(){
     try {
          $data=request()->post();
          $rule = [
              'cart_list|购物车列表' => 'require',
              'store_id|商户ID'=>'require',
          ];
          $this->validate($data,$rule);
       }catch (ValidateException $e){
          return fetchJson([],$e->getError(),1);
       }
       $cart_list=json_decode($data['cart_list'],1);
       $buy_cart_list_all=[];
       $pay_price=0;
       foreach ($cart_list as &$cart) {
            $goodsAttrObj=Goods::where(['id'=>$cart['id']])->field('cover,name,attribe_list')->find();
            if(!$goodsAttrObj){
                return fetchJson([],'暂无商品',1);
            }
            $goodsAttribe_list=$goodsAttrObj->attribe_list;
            $goodsAttr=GoodsAttr::where(['is_delete'=>0,'goods_id'=>$cart['id']])->order('index ASC')->column('attr_list,price,stock,integral,index');

            $goodsAttribe_list=json_decode($goodsAttribe_list,1);
            $goodsAttrArr=[];
            $goodsAttrArrStr=[];
            $goodsAttrStock=[];
            foreach ($goodsAttr as $goodsAttrV) {
                $goodsAttrV_attr_list=array_column(json_decode($goodsAttrV['attr_list'],1),'attr_id');
                $goodsAttrArr[implode('_', $goodsAttrV_attr_list)]=$goodsAttrV['price'];
                $goodsAttrStock[implode('_', $goodsAttrV_attr_list)]=$goodsAttrV['stock'];
            }
            if($cart['use_property']==1){
              $attr_id_node=implode('_', $cart['props']);
            }else{
              $attr_id_node=1;
            }
           
            $buy_cart_list['price']=$goodsAttrArr[$attr_id_node];
            $stock=$goodsAttrStock[$attr_id_node];
            if($stock<$cart['number']){
               return fetchJson([],"【{$cart['name']}】".'暂无库存',1);
            }
            
            $select_attr_str=[];
            foreach ($goodsAttribe_list as $key=> $goodsAttribe_listV) {
                $select_attr=array_column($goodsAttribe_listV['attr_list'],'attr_name','attr_id');
                 if($cart['use_property']==1){
                   $select_attr_str[]=$goodsAttribe_listV['attr_group_name'].':'.$select_attr[$cart['props'][$key]];
                  }else{
                    $select_attr_str[]=$goodsAttribe_listV['attr_group_name'].':'.$select_attr[1];
                  }
            }
            $buy_cart_list['attr_str']=implode(',', $select_attr_str);
            $buy_cart_list['goods_id']=$cart['id'];
            $buy_cart_list['cover']=get_file_url($goodsAttrObj->cover);
            $buy_cart_list['name']=$goodsAttrObj['name'];
            $buy_cart_list['num']=$cart['number'];
            $pay_price+=$cart['number']*$buy_cart_list['price'];
            $buy_cart_list_all[]=$buy_cart_list;
       }
       $coupon_user_id=input('coupon_user_id');
       if($coupon_user_id){
          $coupon_id=CouponUser::where(['id'=>$coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_GOODS,'user_id'=>$this->user_id])->value('coupon_id');
          $coupon=Coupon::where('id',$coupon_id)->find();
          if($coupon){
              if($coupon['full_price']<=$pay_price){
                $pay_price-=$coupon['price'];
              }
          }
       }
       $store_coupon_user_id=input('store_coupon_user_id');
       if($store_coupon_user_id){
          $coupon_id=StoreCouponUser::where(['id'=>$store_coupon_user_id,'is_use'=>0,'type'=>StoreCoupon::TYPE_GOODS,'user_id'=>$this->user_id])->value('coupon_id');
          $coupon=StoreCoupon::where('id',$coupon_id)->find();
          if($coupon){
              if($coupon['full_price']<=$pay_price){
                $pay_price-=$coupon['price'];
              }
          }
       }
       $time=time();
       $card_ids=Card::where(['acid'=>$this->acid,'is_delete'=>0])->column('id');

       $cardUser=CardUser::where(['status'=>1,'user_id'=>$this->user_id])->where('card_id','in',$card_ids)->where('start_time','<',$time)->where('end_time','>',strtotime(date('Y-m-d',$time+86400)));
       $card_user_id=input('card_user_id');
       if($card_user_id){
          $cardUser=$cardUser->where('id',$card_user_id);
       }
       $cardUser=$cardUser->order('level DESC')->find();
       $discount=-1;
       $feePrice=0;
       $payPrice=$pay_price;
       if($cardUser){
          $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0])->find();
          if($card){
              if($pay_price>0){
                  $discount=$card['discount'];
                  $payPrice=$pay_price*$discount/10;
                  $feePrice=$pay_price-$payPrice;
              }
          }
       }
       if($data['store_id']==0){
            $store=App::where(['id'=>$this->acid,'id'=>$data['store_id']])->field('id,logo,name')->find();
            $store['logo']=get_file_url($store['logo']);
       }else{
          $store=Store::where(['acid'=>$this->acid,'id'=>$data['store_id']])->field('id,logo,name')->find();
          $store['logo']=get_file_url($store['logo']);
       }
     
       return fetchJson([
          'store'=>$store,
          'price'=>$payPrice,
          'discount'=>$discount,
          'feePrice'=>$feePrice
       ]);
  }
  //确认订单
  public function confirm(){
      $order_id=input('order_id');
      $order=GoodsOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'id'=>$order_id,'status'=>2])->find();
      if(!$order){
        return fetchJson([],'暂无订单',1);
      }
      $order->status=3;
      $order->save();
      return fetchJson([],'确认成功');
  }
  //取消订单
  public function cancel(){
      $order_id=input('order_id');
      $order=GoodsOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'id'=>$order_id])->where('status','in','0')->find();
      if(!$order){
        return fetchJson([],'暂无订单',1);
      }
      
      $order->status=-1;
      $userCoupon=CouponUser::where(['id'=>$order->coupon_user_id,'is_use'=>0])->find();
      if($userCoupon){
         $order->total_price+=$userCoupon['discounts_price'];
         $order->pay_price+=$userCoupon['discounts_price'];
      }
      $order->coupon_user_id=0;
      $order->save();
      return fetchJson([],'取消订单');
  }
  //提交订单
  public function submit(){
      try {
          $data=request()->post();
          $rule = [
              'cart_list|购物车列表' => 'require',
              'store_id|商户ID'=>'require',
              'name|姓名'=>'require',
              'mobile|手机号码'=>'require',
              'address|地址'=>'require',
          ];
          $this->validate($data,$rule);
       }catch (ValidateException $e){
          return fetchJson([],$e->getError(),1);
       }
       $cart_list=json_decode($data['cart_list'],1);
       $buy_cart_list_all=[];
       $pay_price=0;
       foreach ($cart_list as &$cart) {
            $goodsAttrObj=Goods::where(['id'=>$cart['id']])->field('cover,name,attribe_list')->find();
            if(!$goodsAttrObj){
                return fetchJson([],'暂无商品',1);
            }
            $goodsAttribe_list=$goodsAttrObj->attribe_list;
            $goodsAttr=GoodsAttr::where(['is_delete'=>0,'goods_id'=>$cart['id']])->order('index ASC')->column('attr_list,price,stock,integral,index');

            $goodsAttribe_list=json_decode($goodsAttribe_list,1);
            $goodsAttrArr=[];
            $goodsAttrArrStr=[];
            $goodsAttrStock=[];
            foreach ($goodsAttr as $goodsAttrV) {
                $goodsAttrV_attr_list=array_column(json_decode($goodsAttrV['attr_list'],1),'attr_id');
                $goodsAttrArr[implode('_', $goodsAttrV_attr_list)]=$goodsAttrV['price'];
                $goodsAttrStock[implode('_', $goodsAttrV_attr_list)]=$goodsAttrV['stock'];
            }
            if($cart['use_property']==1){
              $attr_id_node=implode('_', $cart['props']);
            }else{
              $attr_id_node=1;
            }
           
            $buy_cart_list['price']=$goodsAttrArr[$attr_id_node];
            $stock=$goodsAttrStock[$attr_id_node];
            if($stock<$cart['number']){
               return fetchJson([],"【{$cart['name']}】".'暂无库存',1);
            }
            
            $select_attr_str=[];
            foreach ($goodsAttribe_list as $key=> $goodsAttribe_listV) {
                $select_attr=array_column($goodsAttribe_listV['attr_list'],'attr_name','attr_id');
                 if($cart['use_property']==1){
                   $select_attr_str[]=$goodsAttribe_listV['attr_group_name'].':'.$select_attr[$cart['props'][$key]];
                  }else{
                    $select_attr_str[]=$goodsAttribe_listV['attr_group_name'].':'.$select_attr[1];
                  }
            }
            $buy_cart_list['attr_str']=implode(',', $select_attr_str);
            $buy_cart_list['goods_id']=$cart['id'];
            $buy_cart_list['cover']=get_file_url($goodsAttrObj->cover);
            $buy_cart_list['name']=$goodsAttrObj['name'];
            $buy_cart_list['num']=$cart['number'];
            $pay_price+=$cart['number']*$buy_cart_list['price'];
            $buy_cart_list_all[]=$buy_cart_list;
       }

       $order=new GoodsOrder();
       $order->order_no=GoodsOrder::crateOrderNo();
       $order->acid=$this->acid;
       $order->user_id=$this->user_id;
       $order->store_id=$data['store_id'];
       //优惠券
       $coupon_user_id=input('coupon_user_id');
       if($coupon_user_id){
          if(GoodsOrder::where(['coupon_user_id'=>$coupon_user_id,'acid'=>$this->acid,'store_id'=>$data['store_id']])->where('status','<>',-1)->count()){
              return fetchJson([],'该优惠券已被使用',1);
          }
          $userCoupon=CouponUser::where(['id'=>$coupon_user_id,'is_use'=>0,'type'=>Coupon::TYPE_GOODS,'user_id'=>$this->user_id])->find();
          $coupon=Coupon::where('id',$userCoupon['coupon_id'])->find();
          if($coupon){
              if($coupon['full_price']<=$pay_price){
                $pay_price-=$coupon['price'];
                $userCoupon->discounts_price=$coupon['price'];
                $userCoupon->save();
                $order->coupon_user_id=$coupon_user_id;
              }
          }
       }
       $store_coupon_user_id=input('store_coupon_user_id');
       if($store_coupon_user_id){
          if(GoodsOrder::where(['store_coupon_user_id'=>$store_coupon_user_id,'acid'=>$this->acid,'store_id'=>$data['store_id']])->where('status','<>',-1)->count()){
              return fetchJson([],'该优惠券已被使用',1);
          }
          $storeUserCoupon=StoreCouponUser::where(['id'=>$store_coupon_user_id,'is_use'=>0,'type'=>StoreCoupon::TYPE_GOODS,'user_id'=>$this->user_id])->find();
          $storeCoupon=StoreCoupon::where('id',$storeUserCoupon['coupon_id'])->find();
          if($storeCoupon){
              if($storeCoupon['full_price']<=$pay_price){
                $pay_price-=$storeCoupon['price'];
                $storeUserCoupon->discounts_price=$storeCoupon['price'];
                $storeUserCoupon->save();
                $order->store_coupon_user_id=$store_coupon_user_id;
              }
          }
       }  
       $order->remark=input('remark');
       $order->snapshot=json_encode($buy_cart_list_all);
       $order->name=$data['name'];
       $order->mobile=$data['mobile'];
       $order->address=$data['address'];
       $order->is_postage=input('is_postage')?1:0;
       $order->save();
       $time=time();
       $card_ids=Card::where(['acid'=>$this->acid,'is_delete'=>0])->column('id');

       $cardUser=CardUser::where(['status'=>1,'user_id'=>$this->user_id])->where('card_id','in',$card_ids)->where('start_time','<',$time)->where('end_time','>',strtotime(date('Y-m-d',$time+86400)));
       $card_user_id=input('card_user_id');
       if($card_user_id){
          $cardUser=$cardUser->where('id',$card_user_id);
       }
       $cardUser=$cardUser->order('level DESC')->find();
       $discount=-1;
       $feePrice=0;

       if($cardUser){
          $card=Card::where(['id'=>$cardUser['card_id'],'is_delete'=>0])->find();
          if($card){
              if($pay_price>0){
                  $discount=$card['discount'];
                  $payPrice=$pay_price*$discount/10;
                  $feePrice=$pay_price-$payPrice;
                  $pay_price=$payPrice;
                  (new CardUserOrder())->save([
                    'acid'=>$this->acid,
                    'order_id'=>$order->id,
                    'type'=>2,//商品购买
                    'user_id'=>$this->user_id,
                    'card_user_id'=>$cardUser->id,
                    'price'=>$feePrice,
                    'hour'=>0,
                    'discount'=>$discount
                  ]);
              }
          }
       }
       $order->total_price=$pay_price;
       $order->pay_price=$pay_price;
       $order->save();
       $buy_cart_list_all=json_decode($order->snapshot,1);
       foreach ($buy_cart_list_all as $key => $value) {
          $form=new GoodsOrderDetail();
          $form->order_id=$order->id;
          $form->price=$value['price']*1;
          $form->attr_str=$value['attr_str'];
          $form->goods_id=$value['goods_id'];
          $form->cover_img=$value['cover'];
          $form->name=$value['name'];
          $form->num=$value['num'];
          $form->status=0;
          $form->save();
       }
       return fetchJson($order);
  }
  //订单详情
  public function details(){
      $order_id=input('order_id');
      $order=GoodsOrder::where(['acid'=>$this->acid,'user_id'=>$this->user_id,'id'=>$order_id])->find();
      if(!$order){
        return fetchJson([],'暂无订单',1);
      }

      if($order['store_id']==0){
        $order['store']=[
          'name'=>App::where(['id'=>$this->acid])->value('name'),
          'address'=>'平台地址',
          'tel'=>'平台电话'
        ];
      }else{
         $order['store']=Store::where(['id'=>$order->store_id])->field('name,address,tel')->find();
      }
      $order['detailsList']=GoodsOrderDetail::where('order_id',$order->id)->order('status ASC')->column('name,attr_str,num,price');
      $order['payType']=$order['pay_type'];
      $order['pay_type']=$order['pay_type']==0?'微信支付':'余额支付';
      $order['pay_time']=$order['is_pay']==1?date('Y-m-d H:i:s',$order['pay_time']):'';
      $order['snapshot']=json_decode($order['snapshot']);
      $card_user_order=CardUserOrder::alias('cuo')
          ->leftJoin([CardUser::getTable()=>'cu'],'cuo.card_user_id=cu.id')
          ->leftJoin([Card::getTable()=>'c'],'cu.card_id=c.id')
          ->where(['cuo.type'=>2,'cuo.order_id'=>$order->id,'cuo.user_id'=>$this->user_id])
          ->field('cuo.price,cuo.hour,cuo.discount,cuo.status,cuo.type,c.title')
          ->find();
      $order['card_user_order']=$card_user_order;
      $discounts_price=CouponUser::where(['id'=>$order->coupon_user_id,'type'=>Coupon::TYPE_GOODS,'user_id'=>$this->user_id])->value('discounts_price');
      $order['discounts_price']=$discounts_price>0?$discounts_price:0;
      $store_discounts_price=StoreCouponUser::where(['id'=>$order->store_coupon_user_id,'type'=>StoreCoupon::TYPE_GOODS,'user_id'=>$this->user_id])->value('discounts_price');
      $order['store_discounts_price']=$store_discounts_price>0?$store_discounts_price:0;
      return fetchJson($order);
  }
 //支付订单
  public function orderPay(){
       $order_id=input('order_id');
       $order=GoodsOrder::where(['id'=>$order_id,'user_id'=>$this->user_id,'is_pay'=>0])->find();
       if(!$order){
          return fetchJson([],'暂无订单',1);
       }
       $order->order_no=GoodsOrder::crateOrderNo();
       $pay_type=input('pay_type')?input('pay_type'):1;
       $order->pay_type=$pay_type;
       $order->save();
        //判断是否用余额支付
       if($pay_type==2){
           $res=self::balancePayment($order);
           return fetchJson(['order_id'=>$order_id],$res['msg'],$res['code']);
       }
       $app=App::find($this->acid);
       $appid=$app->wxapp_app_id;
       $app_secret=$app->wxapp_app_secret;
       $openid=$this->user->wxapp_open_id;
       if(input('is_weixin')==1){
          $appid=$app->wx_app_id;
          $app_secret=$app->wx_app_secret;
          $openid=$this->user->wx_open_id;
       }
       if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            $appConfig=Option::get_data($this->acid,'platform','app_config');
            $appConfig=json_decode($appConfig);
            $appid=isset($appConfig->appid)?$appConfig->appid:'';
            $app_secret=isset($appConfig->app_secret)?$appConfig->app_secret:'';
       }
       $wx_config=[
            'appid'=>$appid,
            'appsecret'=>$app_secret,
            'mchid'=>$app->wx_mch_id,
            'key'=>$app->wx_key,
            'sslcert'=>$app->wx_cert_pem,
            'sslkey'=>$app->wx_key_pem,
       ];
       if(isset($app->wx_pay_type)){
          $storeWx=Store::where('id',$order->store_id)->field('wx_mch_id,wx_key,wx_sslcert,wx_sslkey')->find();
          //服务商模式
          if($app->wx_pay_type==2){
             $wx_config=[
                  'appid'=>$appid,
                  'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                  'wx_server_appid'=>$app->wx_server_appid,
                  'appsecret'=>$app_secret,
                  'wx_server_mch_id'=>$app->wx_server_mch_id,
                  'key'=>$app->wx_server_key,
                  'sslcert'=>$app->wx_server_cert_pem,
                  'sslkey'=>$app->wx_server_key_pem,
                  'sub_appid'=>$appid,
                  'sub_mch_id'=>$app->wx_mch_id,
                  'wx_pay_type'=>$app->wx_pay_type,
                  'wx_profit_sharing'=>$app->wx_profit_sharing
             ];
          }else{
             if($storeWx['wx_mch_id']){
                $wx_config=[
                      'appid'=>$appid,
                      'appsecret'=>$app_secret,
                      'mchid'=>$storeWx['wx_mch_id']!=0?$storeWx['wx_mch_id']:$app->wx_mch_id,
                      'key'=>$storeWx['wx_key']?$storeWx['wx_key']:$app->wx_key,
                      'sslcert'=>$storeWx['wx_sslcert']!=0?$storeWx['wx_sslcert']:$app->wx_cert_pem,
                      'sslkey'=>$storeWx['wx_sslkey']!=0?$storeWx['wx_sslkey']:$app->wx_key_pem,
                      'wx_profit_sharing'=>$app->wx_profit_sharing
                 ];
             }
          }
       }
       $wechatPay=new WechatPay($wx_config);
       $notify_url=request()->domain().str_replace('index.php', 'pay_shared.php',request()->baseFile());
       $paydata = [
            'body' =>$order->house_title.'购买商品',
            'out_trade_no' => $order->order_no,
            'total_fee' => round($order->pay_price,2)* 100,
            'notify_url' =>$notify_url ,
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ];
       //字节跳动支付
       if($this->platform=='ttapp'){
             $paydata=[
                'body' =>$order->house_title.'购买商品',
                'appid'=>$app->wx_app_id,
                'attach'=>'购买商品',
                'mch_id'=>$app->mch_id,
                'notify_url' =>$notify_url ,
                'out_trade_no' => $order->order_no,
                'total_fee' => round($order->pay_price,2)* 100,
                'trade_type' => 'MWEB',
                'openid' => $openid,
                'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
            ];
            $ttapp=Option::get_data($this->acid,'platform','ttapp_config');
            $ttapp=json_decode($ttapp);
            $res=$wechatPay->toutiaoh5pay($paydata,$ttapp);
            if($res['code']==0){
              return fetchJson($res);
            }else{
              return fetchJson([],$res['msg'],1);
            }
       }
        //微信外部支付
       if($this->platform=='h5'&&input('is_weixin')==0){
            $paydata=[
              'body' =>$order->house_title.'购买商品',
              'appid'=>$app->wx_app_id,
              'attach'=>'购买商品',
              'mch_id'=>$app->mch_id,
              'notify_url' =>$notify_url ,
              'out_trade_no' => $order->order_no,
              'total_fee' => round($order->pay_price,2)* 100,
              'trade_type' => 'MWEB',
              'openid' => $openid,
              'scene_info'=>'{"h5_info":{"type":"Wap","wap_url":"'.request()->domain().'","wap_name":"测试支付"}}'
            ];
            $rest['order_id']=$order->id;
            $res=$wechatPay->h5pay($paydata);
            if($res['code']==0){
              $rest['mweb_url']=$res['data'];
              return fetchJson($rest);
            }else{
              return fetchJson([],$res['msg'],1);
            }
       }
       if($this->platform=='app'||$this->platform=='ios'||$this->platform=='android'){
            unset($paydata['openid']);
            $paydata['trade_type']="APP";
            $res=$wechatPay->appPay($paydata);
       }else{
          $res=$wechatPay->pay($paydata);
       }
       $res['order_id']=$order->id;
       return fetchJson($res);
    }
   //余额支付
    private function balancePayment($order=[]){
         $user=User::where('id',$order['user_id'])->find();
         if($user->money<$order->pay_price){
            return [
              'msg'=>'余额不足',
              'code'=>1
            ];
         }
         $form=new \app\shared\logic\pay\GoodsOrderForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'余额支付错误',
          'code'=>1
        ];
    }
    //开房

}