<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 用户银行表 Table<ai_allwin_bank>
 */
namespace app\allwin\model;
use think\Model;
use think\facade\Validate;
use app\allwin\model\AllwinStore;
use app\allwin\model\BankBill;
use app\common\facade\Inform;
use app\common\facade\WechatPay;

class Bank extends Model{
    
    protected $pk     = 'id';
    protected $table  = 'ai_allwin_bank';
    protected $autoWriteTimestamp = true;
    protected $createTime = false;
    
    //用户
    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','user_id');
    }

    /**
     * 后台在使用
     * 帐号余额
     */
    public static function bank($miniapp_id,$keyword = ''){
        $condition[] = ['allwin_bank.member_miniapp_id','=',$miniapp_id];
        if(!empty($keyword)){
            if(Validate::isMobile($keyword)){
                $condition[] = ['system_user.phone_uid','=',$keyword];
            }else{
                $condition[] = ['system_user.nickname','like','%'.$keyword.'%'];
            }
        }
        return self::view('allwin_bank','*')->view('system_user','nickname,phone_uid,face','allwin_bank.user_id = system_user.id')->where($condition);
    }

    /**
     * 根据是否提交成功结算资金
     * @param integer $uid
     * @param float $money(元)
     * @param boolean $isSuccess
     * @return boolean
     */
    protected static function isPassCash(int $uid,float $money,$is_success = true){
        $info  = self::where(['user_id' => $uid])->find();
        $money = $money*100;
        if ($info->lack_money < $money) {
            return;
        }
        $info->lack_money     = ['dec',$money];
        if($is_success == false){
            $info->due_money  = ['inc',$money];
            $info->money      = ['inc',$money];
        }
        $info->update_time    = time();
        return $info->save();
    }

    /**
     * 提现申请审核操作
     * @param array $param
     * @return boolean
     */
    public static function isPass(array $param,$member_miniapp_id){
        $id         = intval($param['id']);
        $ispass     = intval($param['ispass']);
        $miniapp_id = intval($param['miniapp_id']);
        $cash       = model('BankCash')->where(['member_miniapp_id' =>$miniapp_id,'id'=> $id,'state' => 0])->find();
        if($cash){
            $setting   = model('AllwinConfig')->getConfig($miniapp_id);
            /**
             * 判断是否好店老板
             * 是老板->不扣除提现手续费
             * 非老板->扣除提现手续费
             */
            $is_manage = AllwinStore::manageStore($cash->user_id);
            if(empty($is_manage)){
                $realmoney = money($cash->money - $cash->money*($setting->cash_charges/1000));
            }else{
                $realmoney = $cash->money;
            }
            //判断是否成功
            $is_success = false;
            $is_diy     = false; 
            $trade_no = $cash->user->invite_code.order_no().'WE';
            if($ispass){
                if($setting->is_wechat_touser && (!empty($cash->user->official_uid) || $realmoney < 5000)){
                    $trade_no .= 'WE';
                    $app = WechatPay::doPay($miniapp_id,true);
                    $rel = $app->transfer->toBalance(['partner_trade_no' => $trade_no,'openid' => $cash->user->official_uid,'check_name' => 'NO_CHECK','amount' => $realmoney*100,'desc' => '酬劳与收入']);
                    if ($rel['return_code'] === 'SUCCESS') {
                        if ($rel['result_code'] === 'SUCCESS') {
                            $state      = 1;
                            $is_success = true;
                            $is_diy     = true;
                            $message    = "[通过]申请转出已结算到微信钱包";
                        }else{
                            $message    = $rel['err_code_des'];
                        }
                    }else{
                        $message    = $rel['return_msg'];
                    }
                }else{
                    $trade_no .= 'BANK';
                    $is_diy = true;
                    $message    = "[通过]申请转出已结算到您填写的账户";
                }
                if($is_diy){
                    $bank = self::isPassCash($cash->user_id,$cash->money);
                    if($bank){
                        $state      = 1;
                        $is_success = true;
                    }
                }
            }else{
                $trade_no .= 'BANK';
                $bank = self::isPassCash($cash->user_id,$cash->money,false);
                if($bank){
                    $state      = -1;
                    $is_success = true;
                    $message    = "[失败]申请转出,已退回账户";
                }
            }
            if($is_success){
                BankBill::add(['store_id' => 0,'pay_uid' => 0,'miniapp_id'=>$miniapp_id,'uid'=>$cash->user_id,'money'=>money($realmoney)],$message);
                $data['state']      = $state;                
                $data['realmoney']  = $realmoney;
                $data['audit_time'] = time();
                $data['trade_no']   = $trade_no;
                $data['msg']        = $message;
                model('BankCash')->where(['member_miniapp_id' =>$miniapp_id,'id'=> $id])->update($data);
                 //通知申请者到微信
                if($state){
                    Inform::sms($cash->user_id,$member_miniapp_id,['title' =>'您的账户进行了一笔转账交易','type' => '个人转出','content' =>$cash->money.'元','state' => '成功']);
                }else{
                    Inform::sms($cash->user_id,$member_miniapp_id,['title' =>'您的账户进行了一笔转账交易','type' => '个人转出','content' =>$cash->money.'元','state' => '失败']);
                }
                return ['code'=>200,'msg' => $message,'url' => url('allwin/bank/cashpass',['id' => $id])];
            }else{
                return ['code'=>0,'msg'=>$message,'url' => url('allwin/bank/cashpass',['id' => $id])];
            }
        }else{
            return ['code'=>0,'msg'=>'操作失败,为找到申请提现记录.'];
        }  
    }

    /**
     * 应付款增加
     * @param integer $miniapp_id
     * @param integer $uid
     * @param integer $due_money(元)
     * @return void
     */
    public static function dueMoney(int $miniapp_id,int $uid,float $money){
        $info = self::where(['user_id' => $uid])->find();
        $money = $money*100;
        if(empty($info)){
            $data['member_miniapp_id'] = $miniapp_id;
            $data['user_id']           = $uid;
            $data['income_money']     = $money;
            $data['money']             = $money;
            $data['due_money']         = $money;
            $data['update_time']       = time();
            return self::insert($data);
        }else{
            $info->income_money  = ['inc',$money];
            $info->money          = ['inc',$money];
            $info->due_money      = ['inc',$money];
            $info->update_time    = time();
            return $info->save();
        }
    }

    /**
     * 帐号充值
     * @param integer $miniapp_id
     * @param integer $uid
     * @param integer $money（元）
     * @return void
     */
    public static function recharge(int $miniapp_id,int $uid,float $money){
        $info = self::where(['member_miniapp_id'=>$miniapp_id,'user_id' => $uid])->find();
        $money = $money * 100;
        if(empty($info)){
            $data['member_miniapp_id'] = $miniapp_id;
            $data['user_id']           = $uid;
            $data['due_money']         = $money;
            $data['money']             = $money;
            $data['update_time']       = time();
            return self::insert($data);
        }else{
            $info->due_money  = ['inc',$money];
            $info->money      = ['inc',$money];
            $info->update_time = time();
            return $info->save();
        }
    }

    /**
     * 积分增加
     * @param integer $miniapp_id
     * @param integer $uid
     * @param integer $money（元）
     * @return void
     */
    public static function rePoints(int $miniapp_id,int $uid,int $points){
        $info = self::where(['member_miniapp_id' => $miniapp_id,'user_id' => $uid])->find();
        if(empty($info)){
            $data['member_miniapp_id'] = $miniapp_id;
            $data['user_id']           = $uid;
            $data['shop_money']        = $points;
            $data['update_time']       = time();
            return self::insert($data);
        }else{
            $info->shop_money  = ['inc',$points];
            $info->update_time = time();
            return $info->save();
        }
    }

    /**
     * 提现申请(小程序API)
     * @param integer $miniapp_id
     * @param integer $uid
     * @param integer $money（元）
     * @return void
     */
    public static function cash(int $miniapp_id,int $uid,float $money){
        $info = self::where(['member_miniapp_id' => $miniapp_id,'user_id' => $uid])->find();
        if(empty($info)){
            return;
        }
        $money = $money * 100;
        if($info->due_money < $money || $info->money < $money ){
            return;
        }
        $info->due_money   = ['dec',$money];
        $info->money       = ['dec',$money];
        $info->lack_money  = ['inc',$money];
        $info->update_time = time();
        return $info->save();
    }
}