<?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 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 my_jewel_log(){
        $type = input_post('type',0);

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

        $list = Db::name('user_jewel_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 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['exchange_rate'] = 100; //固定100
        $return_data['min'] = config('site.withdraw_min_money');
        $return_data['list'] = $list;

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


    //提现
    public function withdrawal() {

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

        if (!$id && !$freemoney) {
            $this->error('请选择或填写提现金额');
        }

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

        if ($this->auth->idcard_status != 1) {
            $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 = $withdrawal_config['money'];
            //实际获得金额
            $real_money = $withdrawal_config['real_money'];
        }
        if ($freemoney > 0) {
            //扣除金额
            $money = floatval($freemoney);

            $withdraw_min_money = config('site.withdraw_min_money');
            if($money < $withdraw_min_money){
                $this->error('最低提现'.$withdraw_min_money.'积分');
            }

            //平台手续费
            $withdrawal_rate = config('site.withdrawal_rate') >= 0 ? config('site.withdrawal_rate') : 10;
            $plat_money = bcdiv(bcmul($money,$withdrawal_rate,2),100,2);

            //减去手续费,得实得金额
            $real_money = bcdiv(bcsub($money,$plat_money,2),100,2);
        }

        if ($money <= 0 || $real_money <= 0) {
            $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('可提现余额不足');
        }

        $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'];



        $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
        ];

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

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

        //扣除money
        $rs_wallet = model('Wallet')->lockChangeAccountRemain($this->auth->id,0,'money',-$data['number'],15,'提现(审核中)','take_cash',$log_id);
        if($rs_wallet['status']===false)
        {
            Db::rollback();
            $this->error($rs_wallet['msg']);
        }

        Db::commit();

        $this->success($msg);
    }



    //每日数据
    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);
    }

    //用户之间钻石转赠
    public function jewel_transfer(){
        $jewel = input('jewel',0,'intval');
        $user_id = input('user_id',0,'trim');

        if(!$jewel || !$user_id){
            $this->error();
        }

        if($jewel < 0){
            $this->error('输入数量为0');
        }

        $find_user = Db::name('user')->where('id|mobile',$user_id)->find();
        if(!$find_user){
            $this->error('不存在的用户');
        }
        $user_id = $find_user['id'];

        Db::startTrans();

        $wallet_rs = model('wallet')->lockChangeAccountRemain($this->auth->id,0,'jewel',-$jewel,36,'钻石转赠');
        if($wallet_rs['status'] === false){
            Db::rollback();
            $this->error($wallet_rs['msg']);
        }

        $wallet_rs = model('wallet')->lockChangeAccountRemain($user_id,0,'jewel',$jewel,37,'钻石获赠');
        if($wallet_rs['status'] === false){
            Db::rollback();
            $this->error($wallet_rs['msg']);
        }

        Db::commit();

        $this->success();

    }
}