<?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>
 * 会员账号余额
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\common\facade\WechatPay;
use app\common\facade\Inform;
use app\common\event\User;
use app\common\model\SystemMemberSms;
use app\common\model\SystemUserBank;
use app\allwin\model\Bank as AppBank;
use app\allwin\model\BankBill;
use app\allwin\model\BankRecharge;
use app\allwin\model\BankCash;
use app\allwin\model\AllwinConfig;
use app\allwin\model\MchId;
use think\helper\Time;

class Bank extends Base{
    
    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }

     /**
     * 帐号余额
     */   
    public function index(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(500,'签名验证失败');
        }
        if(!$this->user->phone_uid){
            return json(['code'=>302,'msg'=>'请先绑定手机号','url'=>'/pages/helper/bindphone']);
        }
        //判断是否关联的公众号账户和输入提现信息
        $setting = AllwinConfig::getConfig($this->miniapp_id);
        if($setting->is_wechat_touser == 1){
            if(empty($this->user->official_uid)){
                return json(['code'=>302,'msg'=>'我的钱包,需先绑定公众号帐号','url'=>'/pages/helper/startup']);
            }
        }else{
            $bankInfo = SystemUserBank::where(['user_id' => $this->user->id])->find();
            if(empty($bankInfo)){
                return json(['code'=>302,'msg'=>'请先完善您的实名信息','url'=>'/pages/helper/bindbank']);
            }
        }
        //查询提现金额
        $info = AppBank::where(['user_id' => $this->user->id])->find();
        if(empty($info)){
            return json(['code'=>204,'msg'=>'empty']);
        }else{
            $data['money']         = money($info->money/100);        //帐号余额
            $data['income_money']  = money($info->income_money/100); //获得收益
            $data['lack_money']    = money($info->lack_money/100);   //锁定中
            $data['save_money']    = money($info->save_money/100); //共省钱
            $data['shop_money']    = intval($info->shop_money);  //积分
            return json(['code'=>200,'msg'=>'success','data' => $data]);
        }
    }

     /**
     * 帐号余额
     */   
    public function chickAccount(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(500,'签名验证失败');
        }
        //判断是否关联的公众号账户和输入提现信息
        $setting = AllwinConfig::getConfig($this->miniapp_id);
        if($setting->is_wechat_touser == 1){
            if(empty($this->user->official_uid)){
                return json(['code'=>302,'msg'=>'我的钱包,需先绑定公众号帐号','url'=>'/pages/helper/startup']);
            }
        }else{
            $bankInfo = SystemUserBank::where(['user_id' => $this->user->id])->find();
            if(empty($bankInfo)){
                return json(['code'=>302,'msg'=>'请先完善您的实名信息','url'=>'/pages/helper/bindbank']);
            }
        }
        if(!$this->user->phone_uid){
            return json(['code'=>302,'msg'=>'请先绑定手机号','url'=>'/pages/helper/bindphone']);
        }
    }

   /**
     * 账单
     */
    public function bill(){
        $param['today'] = $this->request->param('today/d',0);
        $param['page']  = $this->request->param('page/d',1);
        $param['sign']  = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(500,'签名验证失败');
        }
        $condition[] = ['user_id','=',$this->user->id];
        $times = Time::today();
        if($param['today']){
            $condition[] = ['update_time','<',$times[1]]; //历史
        }else{  
            $condition[] = ['update_time','>',$times[0]]; //今天
        }
        $info = BankBill::with(['user'	=> function($query) {
            $query->field('id,face,nickname');
        }])->where($condition)->order('id desc')->paginate(10)->toArray();
        if(empty($info['data'])){
            return json(['code'=>204,'msg'=>'empty']);
        }else{
            $list = [];
            foreach ($info['data'] as $key => $value) {
               $list[$key] = $value;
               $list[$key]['update_time'] = date('Y-m-d H:i:s',$value['update_time']);
               $list[$key]['money'] = money($value['money']);
               $list[$key]['user'] = empty($value['user']) ? [] : $value['user'];
            }
            return json(['code'=>200,'msg'=>'success','data' => $list]);
        }
    } 

 /**
     * 提现申请
     **/ 
    public function cash(){
        if (request()->isPost()) {
            $data = [
                'money'             => input('post.money/f', '', 'htmlspecialchars'),
                'safepassword'      => input('post.safepassword/s', '','htmlspecialchars'),
                'user_id'           => $this->user->id,
                'member_miniapp_id' => $this->miniapp_id,
            ];
            $validate = $this->validate($data, 'Bank.getcash');
            if (true !== $validate) {
                return json(['code'=>403,'msg'=>$validate]);
            }
            if($data['money'] < 0){
                return json(['code'=>403,'msg'=>'申请不能小于 0 元']);
            }
            //判断安全密码是否正确
            if(!password_verify(md5($data['safepassword']),$this->user->safe_password)) {
                return json(['code'=>403,'msg'=>'安全密码不正确']);
            }
            //判断是否关联的公众号账户和输入提现信息
            $setting = model('AllwinConfig')->getConfig($this->miniapp_id);
            if($setting->is_wechat_touser == 1){
                if(empty($this->user->official_uid)){
                    return json(['code'=>302,'msg'=>'余额转出,请先【授权登录】','url'=>'/pages/helper/startup']);
                }
            }else{
                $bankInfo = model('SystemUserBank')->where(['user_id' => $this->user->id])->find();
                if(empty($bankInfo)){
                    return json(['code'=>302,'msg'=>'请先完善您的个人信息','url'=>'/pages/helper/bindbank']);
                }
            }
            //判断提现周期
            $bankCash = BankCash::where(['user_id' => $this->user->id])->field('state,update_time')->order('id desc')->find();
            if(!empty($bankCash)){
                if($bankCash->state == 0){
                    return json(['code'=>403,'msg'=>'上次申请还未到账,禁止连续提现']);
                }
            }
            //减少
            $info =AppBank::cash($this->miniapp_id,$this->user->id,$data['money']);
            if(!$info){
                return json(['code'=>403,'msg'=>"金额不足"]);
            }
            //增加申请记录
            $cash['member_miniapp_id'] = $data['member_miniapp_id'];
            $cash['user_id']           = $data['user_id']; 
            $cash['money']             = $data['money'];
            $cash['realmoney']         = 0;
            $cash['state']             = 0;
            $cash['update_time']       = time();
            $rel = BankCash::insert($cash);
            if($rel){
                BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => 0,'uid'=>$this->user->id,'pay_uid' => $this->user->id,'money'=>-$data['money']],'[待审]申请转出');
                //后台通知
                SystemMemberSms::sms($this->miniapp_id,'您有一条提现待审核',url('allwin/bank/cash'));
                //申请者微信通知
                Inform::sms($this->user->id,$this->miniapp_id,['title' =>'业务进展通知','type' => '提现申请','content' =>'您的提现申请正在审核中']);
                //后台管理员微信通知
                Inform::sms(User::isFounder($this->miniapp_id)->user_id,$this->miniapp_id,['title' =>'业务进展通知','type' => '提现申请','content' =>'您有一条新的提现申请待审核']);
                return enjson(200,"申请已提交,请等待审核.");
            }
            return enjson(403,"金额不足");
        }
    }

    /**
     * 帐号充值
     * @access public
     */
    public function recharge(){
        if(request()->isPost()){
            $data = [
                'money'             => input('post.money/d', '','htmlspecialchars'),
                'safepassword'      => input('post.safepassword/s','','htmlspecialchars'),
                'user_id'           => $this->user->id,
                'member_miniapp_id' => $this->miniapp_id,
            ];
            if($data['money'] < 100){
                return json(['code'=>403,'msg'=>'充值金额最小100元']);
            }
            $validate = $this->validate($data, 'Bank.getcash');
            if (true !== $validate) {
                return json(['code'=>403,'msg'=>$validate]);
            }
            //判断安全密码是否正确
            if(!password_verify(md5($data['safepassword']),$this->user->safe_password)) {
                return json(['code'=>403,'msg'=>'安全密码不正确']);
            }
            $order_no = 'RE_'.$this->user->invite_code.order_no();
            $rel = BankRecharge::insert(['state'=>0,'money' => $data['money'],'order_no' => $order_no,'update_time'=>time(),'user_id' => $this->user->id,'member_miniapp_id' => $this->miniapp_id]);
            if($rel){
                $payparm = [
                    'openid'     => $this->user->miniapp_uid,
                    'miniapp_id' => $this->miniapp_id,
                    'name'       => '会员积分充值',
                    'order_no'   => $order_no,
                    'total_fee'  => $data['money']*100,
                    'notify_url' => api(4,'allwin/banknotify/index',$this->miniapp_id),
                ];
                //读取配置
                $setting = AllwinConfig::getConfig($this->miniapp_id);
                if($setting->is_psp == 1){
                    $default_mchid = MchId::getMch(0,$this->miniapp_id);  //默认收款账户
                    if (empty($default_mchid)) {
                        return json(['code'=>403,'msg'=>'未找到默认商户号']);
                    }
                    $payparm['mchid'] = $default_mchid->mchid;  
                }
                $ispay = WechatPay::orderPay($payparm);
                if($ispay['code'] == 0){
                    return json(['code'=>403,'msg'=>$ispay['msg']]);
                }
                return enjson(200,"成功",$ispay['data']);
            }
            return enjson(403,"充值失败,请重试");
        }
    } 
}