<?php

namespace app\shared\logic\pay;
use app\shared\model\StoreRechargeOrder;
use think\exception\ValidateException;
use app\shared\model\User;
use app\shared\model\Store;
use app\shared\model\StoreUserMoney;
use app\shared\model\Bill;
use app\shared\model\Card;
use app\shared\model\CardUser;
use app\shared\model\Coupon;
use app\shared\model\App;
use app\shared\model\WxpayAccounting;
use app\BaseController;
use think\facade\Db;
class StoreRechargeOrderForm{
	//支付回调
	public function saveOrder($order_no=null,$xml_array=[]){
		      $order=StoreRechargeOrder::where('order_no',$order_no)->find();
          if(!$order){
            echo "success";
            exit();
          }
          if($order->is_pay==1){
            echo "success";
            exit();
          }
          $order->is_pay=1;
          $order->pay_time=time();
          $order->xml_array=json_encode($xml_array);
          $order->status=1;
          $order->save();
          $user=User::where('id',$order->user_id)->find();
          $store=Store::where('id',$order['store_id'])->find();
          $money=$order->money+$order->give_price;
          
          $storeUser=StoreUserMoney::where(['acid'=>$order->acid,'store_id'=>$order->store_id,'user_id'=>$order->user_id])->find();
          if(!$storeUser){
            $storeUser=new StoreUserMoney();
            $storeUser->acid=$order->acid;
            $storeUser->user_id=$order->user_id;
            $storeUser->store_id=$order->store_id;
            $storeUser->money=0;
          }
          $storeUser->money=$storeUser->money+$money;
          $storeUser->save();
          (new Bill())->save([
              'acid'=>$order->acid,
              'type'=>Bill::TYPE_STORE_USER_RECHARGE,
              'account_type'=>Bill::ACCOUNT_TYPE_USER,
              'form_id'=>$order->user_id,
              'order_id'=>$order->id,
              'price'=>$money,
              'price_type'=>1,
              'balance'=>$storeUser->money,
              'status'=>1,
              'des'=>"用户:【{$user['nickname']}】充值[{$store->name}] 储值卡金额"
          ]);
          
          self::addStoreBill($order,$store);
          echo "success";
	}
  //增加商户账单
  public function addStoreBill($order=[],$store=[]){
        $fee=($store->fee*0.01)*$order['money'];
        $fee=$fee>0?$fee:0;
        $wxpayAccounting=self::WxpayAccounting($store,$order,$order->money);
        if($wxpayAccounting['code']==0){
          (new Bill())->save([
                'acid'=>$order->acid,
                'type'=>Bill::TYPE_STORE_USER_RECHARGE,
                'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                'form_id'=>$order->store_id,
                'order_id'=>$order->id,
                'price'=>$wxpayAccounting['data']->total_fee,
                'price_type'=>1,
                'status'=>1,
                'fee'=>$fee,
                'des'=>'商户: 【'.$store->name.'】用户充值收入'.$wxpayAccounting['data']->total_fee.'分账金额'.$wxpayAccounting['data']->sub_price
            ]);
           //进行了分账
           return false;
        }          
        (new Bill())->save([
            'acid'=>$order['acid'],
            'type'=>Bill::TYPE_STORE_USER_RECHARGE,
            'account_type'=>Bill::ACCOUNT_TYPE_STORE,
            'form_id'=>$order['store_id'],
            'order_id'=>$order['id'],
            'price'=>$order['money']-$fee,
            'price_type'=>1,
            'status'=>1,
            'fee'=>$fee,
            'des'=>'商户: 【'.$store->name.'】用户充值余额收入'
        ]);
        $store->money+=$order['money']-$fee;
        $store->save();
    }
    //微信分账
    public function WxpayAccounting($store,$order,$total_fee=1){
       if(!$order){
          return ['code'=>1];
       }
       $app=App::find($order->acid);
       if($app->wx_profit_sharing==0){
          return ['code'=>1];
       }
       sleep(10);
       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];
         }

    }
}