<?php
namespace app\shared\logic\user;
use app\shared\model\Card;
use app\shared\model\App;
use app\shared\model\User;
use app\shared\model\CardOrder;
use app\shared\model\House;
use app\shared\model\CardUser;
use app\shared\model\PartnerUser;
use think\exception\ValidateException;
use app\BaseController;
use wechatpay\WechatPay;
//会员卡管理
class CardForm extends  UserForm
{	
    //我的会员卡
    public function mycard(){
        $pay_type=input('pay_type');
        $query=CardUser::alias('c_u')
        ->leftJoin([Card::getTable()=>'c'],'c_u.card_id=c.id');
        if($pay_type==2){
           $query->where(['c.is_balance'=>1]);
        }
        $partnerUser=PartnerUser::where([
          'user_id'=>$this->user_id,
          'acid'=>$this->acid,
          'status'=>1
        ])->find();
        if($partnerUser){
          return fetchJson();
        }
        $list=$query
        ->where(['c_u.acid'=>$this->acid,'c_u.user_id'=>$this->user_id,'c.is_delete'=>0])
        ->order('c.level ASC')
        ->field('c_u.*,c.title,c.level,c.cover,c.discount,c.house_price,c.house_ids,c.type')
        ->select();
        foreach ($list as $key => &$value) {
           if($value->end_time<time()){
               $value->status=0;
               $value->save();
           }
           $value['house_list']=House::where('id','in',$value['house_ids'])->column('id,name');
           $value['house_list']=$value['type']==2?$value['house_list']:[];
           $value['cover_url']=get_file_url($value['cover']);
           $value['start_time']=date('Y-m-d',$value['start_time']);
           $value['end_time']=date('Y-m-d',$value['end_time']);
        }
        return fetchJson($list);
    }
    public function list(){
    	$list=Card::where(['acid'=>$this->acid,'is_delete'=>0])->order('level ASC')->column('id,title,price,cover,dec,discount,house_price,month,hour,type');
    	foreach ($list as $key => &$value) {
          $value['cover_url']=get_file_url($value['cover']);
      }
    	return fetchJson($list);
    }
    //详情
    public function details(){
    	$id=input('id');
    	$form=Card::where(['acid'=>$this->acid,'is_delete'=>0,'id'=>$id])->find();
    	if(!$form)return fetchJson([],'暂无数据');
    	$form['cover_url']=get_file_url($form['cover']);
    	return fetchJson($form);
    }
    //支付卡
    public function pay(){
    	$id=input('id');
    	$card=Card::where(['acid'=>$this->acid,'is_delete'=>0,'id'=>$id])->field('id,title,equity,price,help,cover')->find();
    	if(!$card){
    		 return fetchJson([],'暂无该卡',1);
    	}
      // if($card->num<=0){
      //    return fetchJson([],'该卡已销售完',1);
      // }
    	$order=new CardOrder();
    	$order->acid=$this->acid;
    	$order->order_no=CardOrder::crateOrderNo();
    	$order->price=$card->price<=0?0.01:$card->price;
    	$order->user_id=$this->user_id;
    	$order->card_id=$card->id;
        $pay_type=input('pay_type');
        $pay_type=$pay_type==1?1:2;
        $order->pay_type=$pay_type;
        $order->save();
        if($pay_type==2){
            $res=self::balancePayment($order);
            return fetchJson([],$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;
    	$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,
        ];
    	$wechatPay=new WechatPay($wx_config);
    	$notify_url=request()->domain().str_replace('index.php', 'pay_shared.php',request()->baseFile());
    	$paydata = [
            'body' =>'购买会员卡',
            'out_trade_no' => $order->order_no,
            'total_fee' => round($order->price,2)* 100,
            'notify_url' =>$notify_url ,
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ];
    	$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->price){
            return [
              'msg'=>'余额不足',
              'code'=>1
            ];
         }
         $form=new \app\shared\logic\pay\CardOrderForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'余额支付错误',
          'code'=>1
        ];
    }
}