<?php

namespace app\api\controller\user;

use app\admin\model\system\SystemConfig;
use app\models\store\StoreOrder;
use app\models\user\User;
use app\models\user\UserBill;
use app\models\user\UserExtract;
use app\models\user\UserTransfer;
use app\Request;
use crmeb\services\UtilService;

/**
 * 提现类
 * Class UserExtractController
 * @package app\api\controller\user
 */
class UserExtractController
{
    /**
     * 提现银行
     * @param Request $request
     * @return mixed
     */
    public function bank(Request $request)
    {
        $user = $request->user();
        $broken_time = intval(sys_config('extract_time'));
        $search_time = time() - 86400 * $broken_time;
        //可提现佣金
        //返佣 +
        $brokerage_commission = UserBill::where(['uid' => $user['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
            ->where('add_time', '>', $search_time)
            ->where('pm', 1)
            ->sum('number');
        //退款退的佣金 -
        $refund_commission = UserBill::where(['uid' => $user['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
            ->where('add_time', '>', $search_time)
            ->where('pm', 0)
            ->sum('number');
        $data['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
        if ($data['broken_commission'] < 0)
            $data['broken_commission'] = 0;
//        return $data;
        $data['brokerage_price'] = $user['brokerage_price'];
        //可提现佣金
        $data['commissionCount'] = $data['brokerage_price'] - $data['broken_commission'];
        $extractBank = sys_config('user_extract_bank') ?? []; //提现银行
        $extractBank = str_replace("\r\n", "\n", $extractBank);//防止不兼容
        $data['extractBank'] = explode("\n", is_array($extractBank) ? (isset($extractBank[0]) ? $extractBank[0] : $extractBank) : $extractBank);
        $data['minPrice'] = sys_config('user_extract_min_price');//提现最低金额
        return app('json')->successful($data);
    }

    /**
     * 提现申请
     * @param Request $request
     * @return mixed
     */
    public function cash(Request $request)
    {
        $extractInfo = UtilService::postMore([
            ['alipay_code', ''],
            ['extract_type', ''],
            ['money', 0],
            ['name', ''],
            ['bankname', ''],
            ['cardnum', ''],
            ['weixin', ''],
        ], $request);
        if (!preg_match('/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/', $extractInfo['money'])) return app('json')->fail('提现金额输入有误');
        //提现设置最低金额
        if($extractInfo['money'] < sys_config('user_extract_min_price')) return app('json')->fail('金额小于最低提现金额');
        $user = $request->user();
        $broken_time = intval(sys_config('extract_time'));
        $search_time = time() - 86400 * $broken_time;
        //可提现佣金
        //返佣 +
        $brokerage_commission = UserBill::where(['uid' => $user['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
            ->where('add_time', '>', $search_time)
            ->where('pm', 1)
            ->sum('number');
        //退款退的佣金 -
        $refund_commission = UserBill::where(['uid' => $user['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
            ->where('add_time', '>', $search_time)
            ->where('pm', 0)
            ->sum('number');
        $data['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
        if ($data['broken_commission'] < 0)
            $data['broken_commission'] = 0;
        $data['brokerage_price'] = $user['brokerage_price'];
        //可提现佣金
        $commissionCount = $data['brokerage_price'] - $data['broken_commission'];
        if ($extractInfo['money'] > $commissionCount) return app('json')->fail('可提现佣金不足');
        if (!$extractInfo['cardnum'] == '')
            if (!preg_match('/^([1-9]{1})(\d{14}|\d{18})$/', $extractInfo['cardnum']))
                return app('json')->fail('银行卡号输入有误');
        if (UserExtract::userExtract($request->user(), $extractInfo))
            return app('json')->successful('申请提现成功!');
        else
            return app('json')->fail(UserExtract::getErrorInfo('提现失败'));
    }
    /**
     * 余额转账
     * @param Request $request
     */
    public function transfer(Request $request)
    {
        list($to_uid,$pass,$merber,$type) = UtilService::postMore([
            ['to_uid',''],
            ['pass',''],
            ['merber',0],
            ['type',0],
        ],$request,true);
        if(!User::be(['uid'=>$to_uid])) return app('json')->fail('用户不存在');
        if(strlen($pass)!=6) return app('json')->fail('交易密码只能输入6位数字');
        $user = $request->user();
        $money = $user['now_money'];$in = "转出余额";$out = "转入余额";$field="now_money";
        if($type==1)
        {
            $money = $user['consume'];
            $in = "转入钻石";$out = "转出钻石";
            $field = "consume";
        }
        if(md5(md5($user['salt'].$pass).$user['salt'])!=$user['transaction'])return app('json')->fail('交易密码错误');
        if(bcsub($money,$merber,2)>=0)
        {
            $user = User::where('uid',$request->uid())->lock(true)->find();
            User::where('uid',$request->uid())->dec($field,$merber)->update();
            $touser =  User::where('uid',$to_uid)->find();
            User::where('uid',$to_uid)->inc($field,$merber)->update();
            $data['uid'] = $request->uid();
            $data['touid'] = $touser['uid'];
            $data['money'] = $merber;
            $data['order_id'] = UserTransfer::getNewOrderId();
            $data['add_time'] = time();
            $data['type'] = $type;
            $data['paid'] =1;
            UserTransfer::create($data);
            UserBill::expend($out,$request->uid(),'now_money','transfer_out',$merber,0,bcsub($user['now_money'],$merber,2),'转给'.$touser['nickname']."用户",1);
            UserBill::income($in,$touser['uid'],'now_money','transfer_in',$merber,0,bcadd($touser['now_money'],$merber,2),'收到用户'.$user['uid'].'转账号');
            return app('json')->successful('转账成功!');
        }
        else
        {
            return app('json')->fail($out.'不足');
        }
    }

    /**
     * 转账记录
     * @param Request $request
     */
    public function transfer_list(Request $request)
    {
        list($page,$limit,$pm,$type) = UtilService::postMore([
            ['page',1],
            ['limit',20],
            ['pm',0],
            ['type',0]
        ],$request,true);
        if($pm==0)
        {
            $count = UserTransfer::where('uid',$request->uid())->where('type',$type)->count();
            $data =  UserTransfer::where('uid',$request->uid())->where('type',$type)->page($page,$limit)->order("id desc")->select();
            foreach ($data as &$v)
            {
                $v['to_user'] = User::where('uid',$v['touid'])->value('nickname');
                $v['_add_time'] = date("Y-m-d H:i:s",$v['add_time']);
            }
        }
        else
        {
            $count = UserTransfer::where('touid',$request->uid())->where('type',$type)->count();
            $data =  UserTransfer::where('touid',$request->uid())->where('type',$type)->page($page,$limit)->order("id desc")->select();
            foreach ($data as &$v)
            {
                $v['to_user'] = User::where('uid',$v['uid'])->value('nickname');
                $v['_add_time'] = date("Y-m-d H:i:s",$v['add_time']);
            }
        }
        return app('json')->successful(compact('count','data'));
    }
}