<?php
namespace app\shared\logic\pay;
use app\shared\model\HouseOrder;
use app\shared\model\ShareOrder;
use app\shared\model\WeixinUser;
use app\shared\model\User;
use app\shared\model\Option;
use app\shared\model\App;
use app\shared\model\Bill;
use app\shared\model\Store;
use app\shared\model\CouponUser;
use app\shared\model\StoreCouponUser;

use app\shared\model\Goods;
use app\shared\model\CardUserOrder;
use app\shared\model\GoodsOrder;
use app\shared\model\GoodsOrderDetail;
use app\shared\model\GoodsAttr;
use app\shared\model\PartnerOrder;
use app\shared\model\PartnerUser;
use app\shared\model\Partner;
use app\shared\model\PartnerUserBill;
use think\facade\Cache;
use app\shared\model\WxpayAccounting;
use wechatpay\WechatPay;
class GoodsOrderForm
{
     //获取数据
    public  function saveOrder($order_no='',$xml_array=[]){
    	$order=GoodsOrder::where('order_no',$order_no)->find();

        $user_parent_id=User::where(['id'=>$order->user_id])->value('parent_id');
        $parent=PartnerUser::where(['user_id'=>$user_parent_id,'status'=>1])->find();
        if(!$order)return '';
    	   if($order->is_pay==1){
           if($order->pay_type==2){
                return "success";
            }else{
                echo "success";
                exit();
            }
        }
        $order->pay_time=time();
        $order->xml_array=json_encode($xml_array);
    	  $order->status=1;
    	  $order->is_pay=1;
    	  $order->save();
        // //更新库存
        $list=GoodsOrderDetail::where(['order_id'=>$order->id])->select();
        foreach ($list as $key => $value) {
            $goods_attr=GoodsAttr::where(['goods_id'=>$value['goods_id'],'is_delete'=>0])->select();
            $attr_str_arr=explode(',', $value['attr_str']);
            $attr_arr_string=[];
            foreach ($attr_str_arr as &$attr_arr) {
               $attr_arr_string[]=explode(':', $attr_arr)[1];
            }
            $attr_arr_string=implode('_', $attr_arr_string);
            $goods=Goods::where('id',$value['goods_id'])->field('goods_num')->find();
            $goods_num=0;
            foreach ($goods_attr as &$attr) {
               $attr_list=array_column(json_decode($attr->attr_list,1),'attr_name');
               $attr_list=implode('_', $attr_list);
               if($attr_arr_string==$attr_list){
                 $attr->stock=$attr->stock-$value['num'];
                 $goods_num+=$value['num'];
                 if($attr->stock<0){
                   $attr->stock=0;
                 }
                 $attr->save();
               }
            }
            $goods->goods_num-=$goods_num;
            $goods->save();
        }
        CouponUser::where(['id'=>$order->coupon_user_id])->update(['is_use'=>1,'use_time'=>time(),'order_id'=>$order->id]);
        StoreCouponUser::where(['id'=>$order->store_coupon_user_id])->update(['is_use'=>1,'use_time'=>time(),'order_id'=>$order->id]);

        self::decUserBill($order);
        if($order->store_id!=0){
            self::addStoreBill($order);
        }
        if($parent){
            self::partnerShareBill($order,$parent);
        }else{
            self::shareOrder($order);
        }
        if($order->pay_type==2){
            return "success";
        }else{
            echo "success";
        }
    }
    //增加商户账单
    public function addStoreBill($order=[]){
       if($order['pay_type']==1){
          sleep(10);
        }
        $store=Store::where('id',$order['store_id'])->find();
        $fee=($store->fee*0.01)*$order['pay_price'];
        $fee=$fee>0?$fee:0;
        $wxpayAccounting=self::WxpayAccounting($store,$order,$order->pay_price);
        if($wxpayAccounting['code']==0){
          (new Bill())->save([
                'acid'=>$order->acid,
                'type'=>Bill::TYPE_GOODS,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order->store_id,
                'order_id'=>$order->id,
                'price'=>$wxpayAccounting['data']->total_fee,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】商品收入'.$wxpayAccounting['data']->total_fee.'分账金额'.$wxpayAccounting['data']->sub_price
            ]);
           //进行了分账
           return false;
        }
        $store->money+=$order['pay_price']-$fee;
        $store->save();          
        (new Bill())->save([
            'acid'=>$order['acid'],
            'type'=>Bill::TYPE_GOODS,
            'account_type'=>Bill::ACCOUNT_TYPE_STORE,
            'form_id'=>$order['store_id'],
            'order_id'=>$order['id'],
            'price'=>$order['pay_price']-$fee,
            'price_type'=>$order['pay_type'],
            'status'=>1,
            'fee'=>$fee,
            'balance'=>$store->money,
            'des'=>'商户: 【'.$store->name.'】商品收入'
        ]);
       
        
    }
    //减少用账单
    public function decUserBill($order=[]){
        $user=User::where('id',$order['user_id'])->find();
        if($order->pay_type==2){
            $user->money-=$order['pay_price'];
            $user->save();
        }
         $balance=$user->money;
        //更新会员卡券
        CardUserOrder::where(['order_id'=>$order['id'],'type'=>2])->update(['status'=>1]);
        (new Bill())->save([
            'acid'=>$order->acid,
            'type'=>Bill::TYPE_GOODS,
            'account_type'=>Bill::ACCOUNT_TYPE_USER,
            'form_id'=>$order['user_id'],
            'order_id'=>$order['id'],
            'price'=>$order['pay_price'],
            'pay_type'=>$order['pay_type'],
            'balance'=>$balance,
            'status'=>-1,
            'des'=>'用户: 【'.$user->nickname.'】 购买商品'
        ]);
    }
    //合伙人分销订单
    public function partnerShareBill($order=[],$parent1=[]){
        $nickname=User::where(['id'=>$order->user_id])->value('nickname');
        $partner1=Partner::where(['id'=>$parent1->partner_id])->find();
        $price=$order->pay_price*$partner1->one_level*0.01;
        $parent1->total_price+=$price;
        $parent1->price+=$price;
        $parent1->save();
        //一级分销佣金
        if($price>0){
            (new PartnerUserBill())->save([
                'acid'=>$order->acid,
                'user_id'=>$parent1->id,
                'order_id'=>$order->id,
                'title'=>$nickname.'购买商品获得一级佣金',
                'lngot'=>0,
                'price'=>$price,
                'type'=>2,
                'status'=>1
            ]);
        }
        //二级分销佣金
        $parent2=PartnerUser::where(['user_id'=>$parent1->parent_id])->find();
        if($parent2){
            $partner2=Partner::where(['id'=>$parent2->partner_id])->find();
            $price2=$order->pay_price*$partner2->two_level*0.01;
            $parent2->total_price+=$price2;
            $parent2->price+=$price2;
            $parent2->save();
            if($price2>0){
                (new PartnerUserBill())->save([
                    'acid'=>$order->acid,
                    'user_id'=>$parent2->id,
                    'order_id'=>$order->id,
                    'title'=>$nickname.'购买商品获得二级佣金',
                    'lngot'=>0,
                    'price'=>$price2,
                    'type'=>2,
                    'status'=>1
                ]);
            }
        }
    }
    public function  shareOrder($order=[]){
        $share_setting=Option::get_data($order->acid,'platform','app_share_setting');
        $share_setting=json_decode($share_setting,1);
        if(isset($share_setting['status'])){
             if($share_setting['status']){
                //一级
                $parent1_id=User::where('id',$order->user_id)->value('parent_id');
                if($share_setting['one']>0){
                    if($parent1_id){
                        $price=$share_setting['one']*0.01*$order->pay_price;
                        self::shareUserMoney($order,$parent1_id,$price,$order->user_id);
                    }
                }
                //二级
                if($share_setting['two']>0){
                    if($parent1_id){
                        $parent2_id=User::where('id',$parent1_id)->value('parent_id');
                        $price=$share_setting['one']*0.01*$order->pay_price;
                        if($parent2_id){
                            self::shareUserMoney($order,$parent2_id,$price,$parent1_id);
                        }
                    }
                }
             }
        }
    }
    public function shareUserMoney($order=[],$user_id=0,$price=0,$child_userid=0){
        if($price>0){
            $user=User::where('id',$user_id)->find();
            if(!$user){
                return false;
            }
            $user->price+=$price;
            $user->total_price+=$price;
            $user->save();
            $shareOrder=new ShareOrder();
            $shareOrder->save([
                'acid'=>$order->acid,
                'user_id'=>$user_id,
                'form_user_id'=>$child_userid,
                'user_type'=>ShareOrder::USER_TYPE_USER,
                'type'=>ShareOrder::TYPE_GOODS,
                'order_id'=>$order->id,
                'price'=>$price,
                'status'=>2,
                'pay_time'=>time()
            ]);
            (new Bill())->save([
                'acid'=>$order->acid,
                'type'=>Bill::TYPE_SHARE,
                'account_type'=>Bill::ACCOUNT_TYPE_USER,
                'form_id'=>$user_id,
                'order_id'=>$shareOrder->id,
                'price'=>$price,
                'price_type'=>$order['pay_type'],
                'status'=>1,
                'des'=>'分销佣金:商品购买'
            ]);
        }
    }
    //微信分账
    public function WxpayAccounting($store,$order,$total_fee=1){
       if(!$order){
          return ['code'=>1];
       }
       if($order['pay_type']==2){
          return ['code'=>1];
       }
       $app=App::find($order->acid);
       if($app->wx_profit_sharing==0){
          return ['code'=>1];
       }
       if($app->wx_pay_type==1){
           $wx_config=[
              'appid'=>$app->wxapp_app_id,
              'mchid'=>$store['wx_mch_id'],
              'appsecret'=>$app->wxapp_app_secret,
              'key'=>$store['wx_key'],
              'sslcert'=>$store['wx_sslcert'],
              'sslkey'=>$store['wx_sslkey'],
              'sub_mch_id'=>$app->wx_mch_id,
              'wx_pay_type'=>$app->wx_pay_type,
           ];
       }else{
           $wx_config=[
              'appid'=>$app->wxapp_app_id,
              'mchid'=>$app->wx_mch_id,
              'wx_server_appid'=>$app->wx_server_appid,
              'appsecret'=>$app->wxapp_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'=>$app->wxapp_app_id,
              'sub_mch_id'=>$app->wx_mch_id,
              'wx_pay_type'=>$app->wx_pay_type,
           ];
       }
      
       $is_server=$app->wx_pay_type==2?1:0;
       $xml_array=json_decode($order['xml_array'],1);
       $order_no=WxpayAccounting::crateOrderNo("FZ".$order->store_id."S");
         $store_fee=Store::where('id',$order->store_id)->value('fee');
         if($store_fee>30){
            //根据分账要求最多只能分账微信的百分之30
            $store_fee=29;
         }
         if($store_fee<=0){
            return ['code'=>1];
         }
         $form=new WechatPay($wx_config);
         $account=$app->wx_mch_id;
         $companyName=$app->wx_mch_name;
         $amount=$total_fee*$store_fee;//分账金额（分）
         $out_trade_no=$xml_array['out_trade_no'];//订单号
         $transaction_id=$xml_array['transaction_id'];//微信交易订单号
         $res=$form->profitsharingaddreceiver($account,$companyName,$is_server);
         if($res['code']==1){
            return ['code'=>1];
         }
         $res=$form->profitsharing($order_no,$transaction_id,$account,$amount,$companyName,$is_server);
         if($res['code']==0){
          if($res['data']['result_code']=="SUCCESS"){
            $form=new WxpayAccounting();
            $form->acid=$order->acid;
            $form->store_id=$order->store_id;
            $form->order_id=$order->id;
            $form->appid=$xml_array['appid'];
            $form->mch_id=$xml_array['mch_id'];
            $form->openid=$xml_array['openid'];
            $form->order_no=$order_no;
            $form->out_trade_no=$xml_array['out_trade_no'];
            $form->transaction_id=$xml_array['transaction_id'];
            $form->total_fee=$xml_array['total_fee']*0.01;
            $form->sub_price=$amount*0.01;
            $form->sub_account=$account;
            $form->sub_type=1;
            $form->save();
            return ['code'=>0,'data'=>$form];
          }else{
            return ['code'=>1];
          }
         }else{
           return ['code'=>1];
         }

    }
}