<?php
namespace app\shared\logic\platform;
use app\shared\model\Withdraw;
use app\shared\model\Store;
use app\shared\model\User;
use app\shared\model\WeixinUser;
use app\shared\model\Bill;
use app\shared\model\App;
use app\shared\model\TeaSpecialist;
use wechatpay\WechatPay;
use think\exception\ValidateException;
use app\BaseController;
class WithdrawForm extends  Base
{
    //获取数据
    public  function index(){
        $user_type=input('user_type');
        $status=input('status');
        $query=Withdraw::where(['acid'=>$this->acid,'is_delete'=>0]);
        if($status!=-1){
            $query->where(['status'=>$status]);
        }
        if($user_type!=-1){
            $query->where(['user_type'=>$user_type]);
        }
        $count=$query->count();
        $list=$query->page($this->page)
        ->limit($this->limit)
        ->order('id DESC')
        ->select()
        ->toArray();
        foreach ($list as &$value) {
            switch ($value['status']) {
                case Withdraw::USER_TYPE_USER:
                    $user=User::where('id',$value['user_id'])->field('nickname,avatar_url')->find();
                    $value['nickname']=$user["nickname"];
                    $value['avatar_url']=$user["avatar_url"];
                break;
                case Withdraw::USER_TYPE_STORE:
                    $sotre=Store::where('id',$value['user_id'])->field('name,logo')->find();
                    $value['nickname']=$sotre["name"];
                    $value['avatar_url']=get_file_url($sotre["logo"]);
                break;
                case Withdraw::USER_TYPE_TEASPECIALIST:
                $teaSpecialist=TeaSpecialist::where(['acid'=>$this->acid,'id'=>$form->user_id])->field('nickname,avatar_url')->find();
                    $value['nickname']=$teaSpecialist["nickname"];
                    $value['avatar_url']=$teaSpecialist["avatar_url"];
                break;
                default:
                break;
            }
        }
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]); 
    }
    private function transfersMoney($amount=1,$re_openid="",$desc='测试',$check_name=''){
        $app=App::find($this->acid);
        $appid=$app->wxapp_app_id;
        $app_secret=$app->wxapp_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);
       return $wechatPay->transfersMoney($amount,$re_openid,$desc,$check_name);
    }
    //处理
    public function handle(){
        try {
           $data=request()->post();
           $rule = [
               'id|ID' => 'require|number',
               'status|状态'=>'require|number|in:1,2',
            ];
           $this->validate($data,$rule);
        }catch (ValidateException $e){
           return fetchJson([],$e->getError(),1);
        }
        $form=Withdraw::where(['acid'=>$this->acid,'status'=>0,'id'=>$data['id']])->find();
        if(!$form){
             return fetchJson([],'暂无提现记录',1);
        }
        $remark=input('remark');
        if($data['status']==1){
            switch ($form['user_type']) {
                //用户
                case Withdraw::USER_TYPE_USER:
                        $user=User::where(['acid'=>$this->acid,'id'=>$form->user_id])->find();
                        if($user->price<$form->money){
                            return fetchJson([],'该用户佣金不足无法提现',1);
                        }
                        if($form->type==2){
                            $openid=WeixinUser::where(['acid'=>$this->acid,'mobile'=>$form->account])->value('wxapp_open_id');
                            $res=self::transfersMoney($form->money,$openid,'用户佣金',$form->username);
                            if($res['code']!=0){
                                return fetchJson([],$res['msg'],1);
                            }
                            $remark.="微信凭证"."【商户单号】{$res['data']['partner_trade_no']}【付款单号】{$res['data']['payment_no']}";
                        }
                        $user->price-=$form->money;
                        $user->save();
                        (new Bill())->save([
                            'acid'=>$this->acid,
                            'type'=>Bill::TYPE_WITHDRAW,
                            'account_type'=>Bill::ACCOUNT_TYPE_USER,
                            'form_id'=>$form->user_id,
                            'order_id'=>$form->id,
                            'price'=>$form->money,
                            'price_type'=>2,
                            'status'=>-1,
                            'des'=>'用户: '.$user->nickname."提现金额：￥{$form->money}",
                        ]);
                    break;
                //商户    
                case Withdraw::USER_TYPE_STORE:
                    $store=Store::where(['acid'=>$this->acid,'id'=>$form->user_id])->find();
                    if($store->money<$form->money){
                        return fetchJson([],'该商户账户余额不足无法提现',1);
                    }
                    if($form->type==2){
                        $openid=WeixinUser::where(['acid'=>$this->acid,'mobile'=>$form->account])->value('wxapp_open_id');
                        $res=self::transfersMoney($form->money,$openid,'商户账户提现',$form->username);
                        if($res['code']!=0){
                            return fetchJson([],$res['msg'],1);
                        }
                        $remark.="微信凭证"."【商户单号】{$res['data']['partner_trade_no']}【付款单号】{$res['data']['payment_no']}";
                    }
                    $store->money-=$form->money;
                    $fee=0;//round(($store->fee*0.01*$form->money),2);
                    $money=$form->money-$fee;
                    $store->save();
                    (new Bill())->save([
                        'acid'=>$this->acid,
                        'type'=>Bill::TYPE_WITHDRAW,
                        'account_type'=>Bill::ACCOUNT_TYPE_STORE,
                        'form_id'=>$form->user_id,
                        'order_id'=>$form->id,
                        'price'=>$money,
                        'price_type'=>2,
                        'status'=>-1,
                        'des'=>'商户: '.$store->name."提现金额：￥{$money},提现手续费扣除：￥{$fee}",
                    ]);
                    break;
                //茶艺师提现    
                case Withdraw::USER_TYPE_TEASPECIALIST:
                    $teaSpe=TeaSpecialist::where(['acid'=>$this->acid,'id'=>$form->user_id])->find();
                    if($teaSpe->price<$form->money){
                        return fetchJson([],'该茶艺师账户余额不足无法提现',1);
                    }
                    if($form->type==2){
                        $openid=WeixinUser::where(['acid'=>$this->acid,'mobile'=>$form->account])->value('wxapp_open_id');
                        $res=self::transfersMoney($form->money,$openid,'茶艺师账户提现',$form->username);
                        if($res['code']!=0){
                            return fetchJson([],$res['msg'],1);
                        }
                        $remark.="微信凭证"."【商户单号】{$res['data']['partner_trade_no']}【付款单号】{$res['data']['payment_no']}";
                    }
                    $teaSpe->price-=$form->money;
                    $fee=0;//round(($store->fee*0.01*$form->money),2);
                    $money=$form->money-$fee;
                    $teaSpe->withdrawal_price+=$money;

                    $teaSpe->save();
                    (new Bill())->save([
                        'acid'=>$this->acid,
                        'type'=>Bill::TYPE_WITHDRAW,
                        'account_type'=>Bill::ACCOUNT_TYPE_TEASPECIALIST,
                        'form_id'=>$form->user_id,
                        'order_id'=>$form->id,
                        'price'=>$money,
                        'price_type'=>2,
                        'status'=>-1,
                        'des'=>'茶艺师: '.$teaSpe->nickname."提现金额：￥{$money},提现手续费扣除：￥{$fee}",
                    ]);
                    break;    
                default:
                    break;
            }
        }
        $form->status=$data['status'];
        $form->remark=$remark;
        $form->save();
        return fetchJson([],'处理成功');
    }
}
