<?php
namespace app\shared\logic\user;
use app\shared\model\Partner;
use app\shared\model\PartnerOrder;
use app\shared\model\App;
use app\shared\model\User;
use app\shared\model\Bill;
use app\shared\model\PartnerUser;
use app\shared\model\PartnerUserBill;
use app\shared\model\PartnerWithdraw;
use wechatpay\WechatPay;
use think\exception\ValidateException;
use app\BaseController;
class PartnerForm extends  UserForm
{

   //合伙人列表
	  public function index(){
         $query=Partner::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1]);
         $list=$query
         ->order('price ASC')
         ->select();
         return fetchJson($list);
    }
    //详情
    public function details(){
         $id=input('id');
         $find=Partner::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1,'id'=>$id])->find();
         return fetchJson($find);
    }
    //购买
    public function pay(){
         $id=input('id');
         $partner=Partner::where(['acid'=>$this->acid,'is_delete'=>0,'status'=>1,'id'=>$id,'type'=>1])->find();
         if(!$partner){
            return fetchJson([],'暂无合伙人',1);
         }
         $order=new PartnerOrder();
         $order->order_no=PartnerOrder::crateOrderNo();
         $order->acid=$this->acid;
         $order->user_id=$this->user_id;
         $order->tea_price=$partner->tea_price;
         $order->money=$partner->money;
         $order->everyday_hour=$partner->everyday_hour;
         $order->sum_lngot=$partner->sum_lngot;
         $order->everyday_lngot=$partner->everyday_lngot;
         $order->type=$partner->type;
         $order->first_lngot=$partner->type;
         $order->price=$partner->price;
         $order->partner_id=$partner->id;
         $order->month=$partner->month;
         $order->title=$partner->title;
         $order->level=$partner->level;
         $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']);
         }
         $order->save();
         $app=App::find($this->acid);
         $appid=$app->wxapp_app_id;
         $app_secret=$app->wxapp_app_secret;
         $openid=$this->user->wxapp_open_id;
         //App
         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,
         ];
         $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\PartnerOrderForm();
         $res=$form->saveOrder($order->order_no);
         if($res=='success'){
            return [
              'msg'=>'支付成功',
              'code'=>0
            ];
         }
        return [
          'msg'=>'余额支付错误',
          'code'=>1
        ];
    }
    //用户账单
    public function userBill(){
       $type=input('type');
       $query=PartnerUserBill::alias('u_b')
       ->leftJoin([PartnerUser::getTable()=>'u'],'u_b.user_id=u.id')
       ->where([
          'u_b.acid'=>$this->acid,
          'u.user_id'=>$this->user_id,
       ]);
       if($type){
          $query->where('u_b.type',$type);
       }
       $list=$query->order('u_b.id DESC')
       ->page($this->page)
       ->limit(10)
       ->field('u_b.*')
       ->select();
       return fetchJson($list);
    }
    //提现列表
    public function withdrawList(){
       $partnerUser=PartnerUser::where(['acid'=>$this->acid,'user_id'=>$this->user_id])->find();
        if($partnerUser){
           $asset_type=input('asset_type');
           $list=PartnerWithdraw::where(['acid'=>$this->acid,'user_id'=>$partnerUser->id,'asset_type'=>$asset_type])
                ->page($this->page)
                ->order('id DESC')
                ->limit(10)
                ->select();
                $type=[1=>'余额',2=>'微信',3=>'银行卡'];
                $status=[0=>'提现中',1=>'提现成功',2=>'提现失败'];
                $color=['#fbbd08','#FF7651','#39b54a'];
                foreach ($list as $key => &$value) {
                    $value['type_title']=$type[$value['type']];
                    if($value['type']!=3){
                        $value['bank']='';
                        $value['open_bank']='';
                    }
                    $value['status_name']=$status[$value['status']];
                    $value['status_color']=$color[$value['status']];
                }
                return fetchJson([
                    'list'=>$list
                ]);
        }else{
          return fetchJson([],"您不是合伙人",1);
        }
      
    }
    //申请提现
    public function applyWithdraw(){
        $partnerUser=PartnerUser::where(['acid'=>$this->acid,'user_id'=>$this->user_id])->find();
        if($partnerUser){
           try {
              $data=request()->post();
                $rule = [
                    'type|类型'   => 'require|in:1,2,3',
                    'username|姓名'   => 'length:1,20',
                    'account|账号'   => 'length:5,50',
                    'money|金额'   => 'require|>=:50|float',
                    'asset_type|资金类型'   => 'require|in:1,2',
                ];
                $this->validate($data,$rule);
            }catch (ValidateException $e){
                return fetchJson([],$e->getError(),1);
            }
            $form=PartnerWithdraw::where(['acid'=>$this->acid,'user_id'=>$partnerUser->id,'status'=>0,'asset_type'=>$data['asset_type'],'type'=>$data['type']])->find();
            if($form){
               return fetchJson(['status'=>1],'已有提交，请等待平台审核');
            }
            if($data['asset_type']==1){
              if($partnerUser->price<$data['money']){
                 return fetchJson([],'提现佣金不足',1);
              }
            }
            if($data['asset_type']==2){
              if($partnerUser->sum_lngot<$data['money']){
                 return fetchJson([],'茶元宝不足',1);
              }
            }
            $form=new PartnerWithdraw();
            $form->acid=$this->acid;
            $form->user_id=$partnerUser->id;
            $form->asset_type=$data['asset_type'];
            $form->save($data);
            //提现到余额
            if($data['type']==1){
                if($data['asset_type']==1){
                   $partnerUser->price-=$data['money'];
                }
                if($data['asset_type']==2){
                   $partnerUser->sum_lngot-=$data['money'];
                }
                $user=User::where('id',$this->user_id)->find();
                $partnerUser->save();
                $form->account=$user->account;
                $form->status=1;
                $form->save();
                (new PartnerUserBill())->save([
                    'acid'=>$this->acid,
                    'user_id'=>$partnerUser->id,
                    'order_id'=>$form->id,
                    'title'=>$form->asset_type==1?"合伙人分销佣金提现":"合伙人分销茶元宝提现",
                    'lngot'=>$form->asset_type==2?$data['money']:0,
                    'price'=>$form->asset_type==1?$data['money']:0,
                    'status'=>-1,
                    'type'=>3
                ]);
               
                $user->money+=$data['money'];
                $user->save();
                (new Bill())->save([
                    'acid'=>$this->acid,
                    'type'=>Bill::TYPE_WITHDRAW,
                    'account_type'=>Bill::ACCOUNT_TYPE_USER,
                    'form_id'=>$this->user_id,
                    'order_id'=>$form->id,
                    'price'=>$data['money'],
                    'integral'=>0,
                    'price_type'=>2,
                    'status'=>1,
                    'des'=>$data['asset_type']==1?'合伙人提现金额到余额':'合伙人提现茶元宝到余额',
               ]);
              return fetchJson(['status'=>1],'提现成功');
            }
            
            return fetchJson(['status'=>1],'提交成功');
        }
        return fetchJson(['status'=>1],'暂无合伙人',1);
      
    }
    //推荐团队
    public function team(){
          $partnerUser=PartnerUser::where(['acid'=>$this->acid,'user_id'=>$this->user_id])->find();
          if($partnerUser){
                $level=input('level');
                if($level==0){
                    $level=2;
                    $is_all=1;
                }else{
                    $is_all=0;
                }
                $list=PartnerUser::childAll($partnerUser->id,$level,'id,parent_id,create_time',$this->page,$is_all);
                $ids=array_column($list, 'id');
                $clevels=array_column($list,'clevel','id');
                $query=PartnerUser::alias('p_u')
                ->leftJoin([User::getTable()=>'u'],'p_u.user_id=u.id')
                ->where('p_u.id','in',$ids)
                ->field('p_u.id,p_u.start_time,p_u.end_time,u.nickname,u.avatar_url')
                ->select()->toArray();
                foreach ($query as $key=>&$value) {
                   $value['start_time']=date('Y-m-d',$value['start_time']);
                   $value['end_time']=$value['end_time']==-1?"永久":date('Y-m-d',$value['end_time']);
                   $value['clevel']=$clevels[$value['id']];
                }
                return fetchJson([
                  'list'=>$query
                ]);
          }else{
            return fetchJson([],'您不是合伙人',1);
          }
      
    }

}