<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
//use app\common\model\wallet;
/**
 * 用户钱包
 */
class Userwallet extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    //我的钱包余额
    public function my_wallet(){
        $wallet = model('wallet')->getwallet($this->auth->id);
        $this->success('success',$wallet);
    }



    //充值记录
    public function gold_recharge_log(){
        $map = [
            'user_id' => $this->auth->id,
            'log_type'=> 10,
        ];
        $list = Db::name('user_gold_log')->field('id,change_value,remain,createtime')->where($map)->order('id desc')->autopage()->select();

        $this->success('success',$list);
    }

    //我的收益,三个数据
    public function my_income_count(){
        //累计收益,不计来源
        $map = [
            'user_id' => $this->auth->id,
            //'log_type'=> ['IN',[21,22,23]],
        ];
        $income_sum = Db::name('user_money_log')->where($map)->sum('change_value');

        //可提现总收益
        $money_remain = model('wallet')->getwallet($this->auth->id,'money');

        //今日收益
        $start = strtotime(date('Y-m-d'));
        $end = $start + 86399;
        $map['createtime'] = ['between',[$start,$end]];
        $today_income_sum = Db::name('user_money_log')->where($map)->sum('change_value');

        $result = [
            'income_sum' => $income_sum,
            'money_remain' => $money_remain,
            'today_income_sum' => $today_income_sum,
        ];

        $this->success('success',$result);
    }

    //追加log_text
    private function list_appen_logtext($list){
        if(!empty($list)){
            $conf = config('wallet.logtype');
            foreach($list as $key => $val){
                $list[$key]['createtime'] = date('Y.m.d H:i');
                $list[$key]['log_text'] = isset($conf[$val['log_type']]) ? $conf[$val['log_type']] : '';
            }
        }
        return $list;
    }

    //互动收益,打视频,语音,文字聊天,聊天送礼物
    public function hudong_money(){
        $map = [
            'user_id' => $this->auth->id,
            'log_type'=> ['IN',[21,22,23,54]],
        ];
        $list = Db::name('user_money_log')
            ->field('id,log_type,change_value,remain,remark,createtime')
            ->where($map)->order('id desc')->autopage()->select();

        $list = $this->list_appen_logtext($list);
        $this->success('success',$list);
    }
    //音聊收益,语聊间礼物
    public function party_money(){
        $map = [
            'user_id' => $this->auth->id,
            'log_type'=> 52,
        ];
        $list = Db::name('user_money_log')
            ->field('id,log_type,change_value,remain,remark,createtime')
            ->where($map)->order('id desc')->autopage()->select();

        $list = $this->list_appen_logtext($list);
        $this->success('success',$list);
    }
    //直播收益,直播间礼物
    public function livebc_money(){
        $map = [
            'user_id' => $this->auth->id,
            'log_type'=> 56,
        ];
        $list = Db::name('user_money_log')
            ->field('id,log_type,change_value,remain,remark,createtime')
            ->where($map)->order('id desc')->autopage()->select();

        $list = $this->list_appen_logtext($list);
        $this->success('success',$list);
    }

    //我的余额日志
    public function my_money_log(){
        $type = input_post('type',0);

        $map = [
           'user_id' => $this->auth->id,
        ];
//        if($type){
//            $map['log_type'] = $type;
//        }

        $list = Db::name('user_money_log')
            ->field('id,log_type,change_value,remain,remark,createtime, remark log_text')
            ->where($map)->order('id desc')->autopage()->select();
//        $list = $this->list_appen_logtext($list);
        if(!empty($list)){
            foreach($list as $key => $val){
                $list[$key]['createtime'] = date('Y.m.d H:i', $val['createtime']);
            }
        }

        $this->success('success',$list);
    }

    //金币日志
    public function my_gold_log(){
        $type = input_post('type',0);

        $map = [
            'user_id' => $this->auth->id,
        ];
        if($type == 19){
            $map['log_type'] = $type;
        }

        $list = Db::name('user_gold_log')->field('id,log_type,change_value,remain,createtime, remark log_text')->where($map)->order('id desc')->autopage()->select();
//        $list = $this->list_appen_logtext($list);
        if(!empty($list)){
            foreach($list as $key => $val){
                $list[$key]['createtime'] = date('Y.m.d H:i', $val['createtime']);
            }
        }

        $this->success('success',$list);
    }

    //提现配置
    public function take_cash_config(){
        $idcard_confirm = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->find();

        $data = [
            'money' => model('wallet')->getwallet($this->auth->id,'money'),
            'alipay_account' => ($this->auth->idcard_status == 1 && isset($idcard_confirm['alipay_account'])) ? $idcard_confirm['alipay_account'] : '',
            'min' => 1,
            'max' => 1000,
        ];

        $this->success('success',$data);
    }

    //提现
    public function take_cash(){
        $money = floatval(input_post('money',0));

        if(empty($money)){
            $this->error();
        }

        if(empty($this->auth->idcard_status)){
            $this->error('请先完成实名认证');
        }

        $check = Db::name('take_cash')->where(['user_id'=>$this->auth->id,'status'=>0])->find();
        if($check){
            $this->error('您已经申请了提现,请等待审核');
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'money');
        if($money > $user_money){
            $this->error('提现金额不能大于可提现余额');
        }

        $idcard_confirm = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->find();
        $data = [
            'user_id' => $this->auth->id,
            'number' => $money,
            'alipay_account' => $idcard_confirm['alipay_account'],
            'status' => 0,
            'createtime' => time(),
            'updatetime' => time(),
        ];

        Db::name('take_cash')->insertGetId($data);

        //审核时候再扣,或者这里先扣,等需求方确认
        $this->success('申请成功请等待审核');
    }

    //提现记录
    public function take_cash_log(){
        $list = Db::name('take_cash')->field('id, number, status, createtime')->where(['user_id'=>$this->auth->id])->autopage()->order('id desc')->select();

        if ($list) {
            foreach ($list as &$v) {
                $v['title'] = '余额提现';
                $v['number'] = '-' . $v['number'];
                $v['createtime'] = date('Y.m.d H:i', $v['createtime']);
            }
        }

        $this->success('success',$list);
    }

    //提现金额配置
    public function withdrawal_config() {
        $show = config('site.withdrawal_show');
        $list = Db::name('withdrawal_config')->where('is_show',1)->order('weight asc,id asc')->select();
        if ($list) {
            $arr = [
                'id' => -1,
                'money' => 0,
                'real_money' => 0,
                'type' => 0,
                'is_show' => 1,
                'weight' => 1
            ];

            array_push($list, $arr);
        }

        $return_data['show'] = $show;
        $return_data['withdrawal_rate'] = config('site.withdrawal_rate') > 0 ? config('site.withdrawal_rate') : 10;
        $return_data['list'] = $list;

        $this->success('success',$return_data);
    }
    
    //提现(废弃)
    public function withdrawal_feiqi() {
        if ($this->auth->idcard_status != 1) {
            $this->error('请先完成实名认证~');
        }

        $id = input('id', 0, 'intval');
        $type = input('type', 0, 'intval'); //账户类型:1=微信,2=支付宝
        if (!$id) {
            $this->error('您的网络开小差啦~');
        }
        $withdrawal_config = Db::name('withdrawal_config')->find($id);
        if (!$withdrawal_config) {
            $this->error('提现金额不存在~');
        }
        if ($withdrawal_config['is_show'] != 1) {
            $this->error('提现金额暂未开放~');
        }
        if ($withdrawal_config['money'] <= 0 || $withdrawal_config['real_money'] <= 0 || $withdrawal_config['money'] < $withdrawal_config['real_money']) {
            $this->error('提现金额异常~');
        }
        if (!in_array($type, [1, 2])) {
            $this->error('请选择提现账户~');
        }
        if ($type != 2) {
            $this->error('提现方式请选择支付宝');
        }

        //扣除金额
        $money = floatval($withdrawal_config['money']);

        $check = Db::name('take_cash')->where(['user_id'=>$this->auth->id,'status'=>0])->find();
        if($check){
            $this->error('您已经申请了提现,请等待审核');
        }
        $time = strtotime(date('Y-m-d'));
        $check = Db::name('take_cash')->where(['user_id'=>$this->auth->id, 'wallet_id'=>$id, 'createtime' => ['egt', $time]])->find();
        if($check){
            $this->error('您今日已经提现过该额度');
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'money');
        if($money > $user_money){
            $this->error('可提现余额不足');
        }

        if ($type == 1) { //微信
            $alipay_account = '';
        } else { //支付宝
            $user_bank_info = Db::name('user_bank')->where(['user_id' => $this->auth->id, 'type' => 1])->find();
            if (!$user_bank_info) {
                $this->error('请先绑定支付宝');
            }
            $alipay_account = $user_bank_info['banknumber'];
            $realname = $user_bank_info['realname'];

            /*$idcard_confirm = Db::name('user_idconfirm')->where('user_id', $this->auth->id)->find();
            $alipay_account = $idcard_confirm['alipay_account'];*/
        }
        $data = [
            'user_id' => $this->auth->id,
            'wallet_id' => $id,
            'number' => $money,
            'money' => $withdrawal_config['real_money'],
            'alipay_account' => $alipay_account,
            'status' => 0,
            'createtime' => time(),
            'updatetime' => time(),
            'type' => $type,
            'realname' => $realname
        ];
        //计算上级可获得金额
        if ($this->auth->intro_uid) {
            $data['intro_uid'] = $this->auth->intro_uid;
            //获取返利比率
            $intro_withdrawal_rebate_rate = (int)config('site.intro_withdrawal_rebate_rate');
            if ($intro_withdrawal_rebate_rate > 0 && $intro_withdrawal_rebate_rate <= 100) {
                //上级获得金额数量
                $intro_uid_money = number_format($money * $intro_withdrawal_rebate_rate / 100, 2, '.', '');
                if ($intro_uid_money > 0) {
                    $data['intro_money'] = $intro_uid_money;
                }
            }
        }

        $msg = '申请成功请等待审核';

        //开启事务
        Db::startTrans();
        $log_id = Db::name('take_cash')->insertGetId($data);
        if (!$log_id) {
            Db::rollback();
            $this->error('您的网络开小差啦~');
        }
        if ($withdrawal_config['type'] == 1) { //秒到账,无需审核
            $info = Db::name('take_cash')->find($log_id);
            //扣钱
            $wallet_rs = model('wallet')->lockChangeAccountRemain($info['user_id'],0,'money',-$info['number'],15,'提现:'.$info['number'],'take_cash',$info['id']);
            if($wallet_rs['status'] === false){
                Db::rollback();
                $this->error($wallet_rs['msg']);
            }
            //上级返利
            if ($info['intro_uid'] && $info['intro_money'] > 0) {
                $wallet_rs = model('wallet')->lockChangeAccountRemain($info['intro_uid'],$info['user_id'],'money',$info['intro_money'],66,'邀请人提现奖励:'.$info['number'],'take_cash',$info['id']);
                if($wallet_rs['status'] === false){
                    Db::rollback();
                    $this->error($wallet_rs['msg']);
                }
            }
            //自动打款
            if ($info['type'] == 1) { //微信

            } elseif ($info['type'] == 2) { //支付宝
                $dakuanrs = $this->withdraw($info);
                if (!$dakuanrs) {
                    Db::rollback();
                    $this->error('打款失败');
                }
            }
            //修改提现记录状态
            $take_cash_result = Db::name('take_cash')->where(['id' => $log_id, 'status' => 0])->setField('status', 1);
            if (!$take_cash_result) {
                Db::rollback();
                $this->error('打款失败');
            }

            //系统消息
            $msg_id = \app\common\model\Message::addMessage($info['user_id'],'提现','您的提现已经到账');

            $msg = '提现成功';
        }

        Db::commit();
        //审核时候再扣,或者这里先扣,等需求方确认
        $this->success($msg);
    }

    //提现
    public function withdrawal() {
        if ($this->auth->idcard_status != 1) {
            $this->error('请先完成实名认证~');
        }

        $id = input('id', 0, 'intval');
        $type = input('type', 0, 'intval'); //账户类型:1=支付宝,2=银行卡
        $freemoney = input_post('freemoney', 0, 'intval'); //自定义金额

        if (!$id && !$freemoney) {
            $this->error('请选择或填写提现金额');
        }
        if ($id > 0) {
            $withdrawal_config = Db::name('withdrawal_config')->find($id);
            if (!$withdrawal_config) {
                $this->error('提现金额不存在~');
            }
            if ($withdrawal_config['is_show'] != 1) {
                $this->error('提现金额暂未开放~');
            }
            if ($withdrawal_config['money'] <= 0 || $withdrawal_config['real_money'] <= 0 || $withdrawal_config['money'] < $withdrawal_config['real_money']) {
                $this->error('提现金额异常~');
            }

            //扣除金额
            $money = floatval($withdrawal_config['money']);
            //实际获得金额
            $real_money = $withdrawal_config['real_money'];
        }
        if ($freemoney > 0) {
            //扣除金额
            $money = $freemoney;
            //实际获得金额
            $bili = config('site.withdrawal_rate') >= 0 ? config('site.withdrawal_rate') : 10;
            $real_money = number_format($money * (100 - $bili) / 100, 2, '.', '');
        }

        if ($money <= 0) {
            $this->error('提现金额异常');
        }

        if (!in_array($type, [1, 2])) {
            $this->error('请选择提现账户~');
        }

        $check = Db::name('take_cash')->where(['user_id'=>$this->auth->id,'status'=>0])->find();
        if($check){
            $this->error('您有一笔提现在审核中,待审核通过后再申请提现。');
        }
        $time = strtotime(date('Y-m-d'));
        $check = Db::name('take_cash')->where(['user_id'=>$this->auth->id, 'wallet_id'=>$id, 'createtime' => ['egt', $time]])->find();
        if($check){
            $this->error('您今日已经提现过该额度');
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'money');
        if($money > $user_money){
            $this->error('可提现余额不足');
        }

        $user_bank_info = Db::name('user_bank')->where(['user_id' => $this->auth->id, 'type' => $type])->find();
        if (!$user_bank_info) {
            $this->error('请先添加提现方式');
        }
        $alipay_account = $user_bank_info['banknumber'];
        $realname = $user_bank_info['realname'];

        /*$idcard_confirm = Db::name('user_idconfirm')->where('user_id', $this->auth->id)->find();
        $alipay_account = $idcard_confirm['alipay_account'];*/

        $data = [
            'user_id' => $this->auth->id,
            'wallet_id' => $freemoney > 0 ? 0 : $id,
            'number' => $money,
            'money' => $real_money,
            'alipay_account' => $alipay_account,
            'status' => 0,
            'createtime' => time(),
            'updatetime' => time(),
            'type' => $type,
            'realname' => $realname
        ];
        //计算上级可获得金额
        /*if ($this->auth->intro_uid) {
            $data['intro_uid'] = $this->auth->intro_uid;
            //获取返利比率
            $intro_withdrawal_rebate_rate = (int)config('site.intro_withdrawal_rebate_rate');
            if ($intro_withdrawal_rebate_rate > 0 && $intro_withdrawal_rebate_rate <= 100) {
                //上级获得金额数量
                $intro_uid_money = number_format($money * $intro_withdrawal_rebate_rate / 100, 2, '.', '');
                if ($intro_uid_money > 0) {
                    $data['intro_money'] = $intro_uid_money;
                }
            }
        }*/

        $msg = '申请成功请等待审核';

        //开启事务
        Db::startTrans();
        $log_id = Db::name('take_cash')->insertGetId($data);
        if (!$log_id) {
            Db::rollback();
            $this->error('您的网络开小差啦~');
        }

        Db::commit();
        //审核时候再扣,或者这里先扣,等需求方确认
        $this->success($msg);
    }

    //提现转账(新版2020-01-01)
    public function withdraw($info) {
        $data['out_biz_no'] = getMillisecond() . mt_rand(1, 1000); //商户订单号
        $data['trans_amount'] = $info['money']; //订单总金额,单位为元,精确到小数点后两位
        $data['product_code'] = 'TRANS_ACCOUNT_NO_PWD';//业务产品码,收发现金红包固定为:STD_RED_PACKET;单笔无密转账到支付宝账户固定为:TRANS_ACCOUNT_NO_PWD;单笔无密转账到银行卡固定为:TRANS_BANKCARD_NO_PWD
        $data['biz_scene'] = 'DIRECT_TRANSFER'; //描述特定的业务场景,可传的参数如下:PERSONAL_COLLECTION:C2C现金红包-领红包;DIRECT_TRANSFER:B2C现金红包、单笔无密转账到支付宝/银行卡
        $data['order_title'] = '知音佣金发放'; //转账业务的标题,用于在支付宝用户的账单里显示

        $data['payee_info']['identity'] = $info['alipay_account'];//收款方支付宝id或支付宝账户

        /*if ($info['alipay_type'] == 1) { //支付宝账户
            $data['payee_info']['identity_type'] = 'ALIPAY_LOGON_ID';
            //收款支付宝账号真实姓名, 不为空时支付宝会验证
            $data['payee_info']['name'] = $info['name'];
        } else { //支付宝id
            $data['payee_info']['identity_type'] = 'ALIPAY_USER_ID';
            $data['payee_info']['name'] = '';
        }*/
        //支付宝id
        $data['payee_info']['identity_type'] = 'ALIPAY_USER_ID';
        $data['payee_info']['name'] = '';

        //转账备注(支持200个英文/100个汉字)。当付款方为企业账户,且转账金额达到(大于等于)50000元,remark不能为空。收款方可见,会展示在收款用户的收支详情中。
        $data['remark'] = '知音佣金发放';
        require_once("../extend/AliPay/AliPay.php");
        $alipay =new \AliPay();
        $result =$alipay->AliPayWithdraw($data);
        return $result;
    }

    //每日数据
    public function todayincome() {
        $start = input('time', 0, 'strtotime'); //时间: 2022-09-30
        if (!$start) {
            $start = strtotime(date('Y-m-d')); //默认今日
        }
        $end = $start + 86399;

        //收益type
        $profit_type = [21,22,23,54,58,60,67];

        //今日收益
        $today_map = [
            'log_type' => ['IN',$profit_type],
            'user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
        ];
        $today_profit = Db::name('user_money_log')->where($today_map)->sum('change_value');

        //今日视频时长/收益/人数
        $map = [
            'to_user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
        ];
        $today_video_min = Db::name('user_match_video_log')->where($map)->sum('call_minutes');

        $today_video_income = Db::name('user_match_video_log')->where($map)->sum('money');
        $today_video_income = $today_video_income ? : 0;

        $today_video_user = Db::name('user_match_video_log')->where($map)->column('user_id');
        $today_video_user = array_unique($today_video_user);
        $today_video_user_num = count($today_video_user);
        //今日语音时长/收益/人数
        $today_audio_min = Db::name('user_match_audio_log')->where($map)->sum('call_minutes');

        $today_audio_income = Db::name('user_match_audio_log')->where($map)->sum('money');
        $today_audio_income = $today_audio_income ? : 0;

        $today_audio_user = Db::name('user_match_audio_log')->where($map)->column('user_id');
        $today_audio_user = array_unique($today_audio_user);
        $today_audio_user_num = count($today_audio_user);
        //今日时长/收益/人数
        $today_time = $today_video_min + $today_audio_min;
        $today_time_income = number_format($today_video_income + $today_audio_income, 2, '.', '');
        $today_user_num = $today_video_user_num + $today_audio_user_num;

        //礼物收益
        $gitft_map = [
            'log_type' => ['IN',[54, 58, 60]],
            'user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
        ];
        $today_gift_income = Db::name('user_money_log')->where($gitft_map)->sum('change_value');

        //私聊时长/收益/人数
        $today_chat_min = Db::name('user_match_typing_log')->where($map)->count('id');

        $today_chat_income = Db::name('user_match_typing_log')->where($map)->sum('money');
        $today_chat_income = $today_chat_income ? : 0;

        $today_chat_user = Db::name('user_match_typing_log')->where($map)->column('user_id');
        $today_chat_user = array_unique($today_chat_user);
        $today_chat_user_num = count($today_chat_user);

        //任务收益 客户要求由money改为gold
        $today_task_income = Db::name('user_gold_log')->where(['user_id' => $this->auth->id, 'log_type' => 67, 'createtime' => ['between',[$start,$end]]])->sum('change_value');
        $today_task_income = $today_task_income ? : 0;


        $result = [
            'today_profit' => $today_profit,
            'today_time_income' => $today_time_income,
            'today_gift_income' => $today_gift_income,
            'today_chat_income' => $today_chat_income,
            'today_task_income' => $today_task_income,
            'today_time' => $today_time,
            'today_user_num' => $today_user_num,
            'today_chat_min' => $today_chat_min,
            'today_chat_user_num' => $today_chat_user_num
        ];

        $this->success('success',$result);
    }

    //每日数据礼物列表
    public function todaygiftlist() {
        $start = input('time', 0, 'strtotime'); //时间: 09-30
        if (!$start) {
            $start = strtotime(date('Y-m-d')); //默认今日
        }
        $end = $start + 86399;

        //今日收益
        $today_map = [
            'log_type' => ['IN', [54,/*58,*/60]],
            'user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
        ];
        $list = Db::name('user_money_log')->where($today_map)->autopage()->order('id desc')->select();
        if (!$list) {
            $this->success('success', $list);
        }

        $mt_gift_user_typing = Db::name('gift_user_typing'); //54
//        $mt_gift_user_greet = Db::name('gift_user_greet'); //58
        $mt_gift_user_dongtai = Db::name('gift_user_dongtai'); //60
        foreach ($list as &$v) {
            if ($v['log_type'] == 54) {
                $table = $mt_gift_user_typing;
            }/* elseif ($v['log_type'] == 58) {
                $table = $mt_gift_user_greet;
            } */else {
                $table = $mt_gift_user_dongtai;
            }
            $info = $table->where(['id' => $v['table_id']])->find();

            $v['gift_name'] = $info['gift_name'];
            $v['number'] = $info['number'];
        }

        $this->success('success', $list);
    }
}