<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\api\controller\contribute_vadded;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\User as UserModel;

class User extends Base
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\ContributeVadded;
    }

    public function index(){
        $result = $this->model->latestData();
        $result['user'] = $this->user; 
        __success("操作成功",$result);
    }

    public function getContributeList(){
        $page = max(1,$this->param("page/d"));
        $limit = 20;

        $list = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id'],'type'=>15])->order("createtime desc,id desc")->limit(($page - 1) * $limit,$limit)->select();
        foreach($list as $key => &$value){
            $value['createtime'] = date("Y-m-d H:i:s",$value['createtime']);
            $value['money'] = bd_number($value['money']);
            $value['befores'] = bd_number($value['befores']);
            $value['afters'] = bd_number($value['afters']);
        }
        unset($value);
        __success("操作成功",['list'=>$list]);
    }

    public function exchange(){
        global $_W;
        $base = $_W['base'];
        $fenxiao = $_W['base']['fenxiao'];
        $money = $this->param("money/f");
        $user = $this->user;
        $config = $base['contribute_vadded'];
        $money = round($money,2);
        if($money <= 0){
            __error("请输入兑换".$fenxiao['texts']['contribute_vadded_score']);
        }
        if($config['withdrawal']['status'] != 1){
            __error($fenxiao['texts']['contribute_vadded_score']."兑换未开启");
        }
        if($user['contribute_vadded'] < $money){
            __error($fenxiao['texts']['contribute_vadded_score']."不足");
        }
        
        $withdrawal_limit = max(0,floatval($config['withdrawal']['min']));
        $max_withdrawal = floatval($config['withdrawal']['max']);
        $service_charge_rate = floatval($config['withdrawal']['service_charge']);
        $fixed_service_charge = max(0,floatval($config['withdrawal']['fixed_service_charge']));
        $integer = intval($config['withdrawal']['integer_multiple']);
        
        if($money < $withdrawal_limit && $withdrawal_limit > 0){
            __error("最低兑换".$withdrawal_limit);
        }
        if($money > $max_withdrawal && $max_withdrawal > 0){
            __error("最高兑换".$max_withdrawal);
        }
        if($integer > 0){
            if($money % $integer != 0){
                __error("请输入{$integer}的倍数兑换");
            }
        }
        
        try {
            Db::startTrans();
            
            $ContributeVadded_result = $this->model->latestData();
            if(empty($ContributeVadded_result)){
                throw new \Exception($fenxiao['texts']['contribute_vadded_score']."信息错误");
            }
            $current_price = floatval($ContributeVadded_result['current_price']);
            $balance_total = round($money * $current_price,6);
            if($balance_total < 0){
                throw new \Exception($fenxiao['texts']['contribute_vadded_score']."价格错误");
            }
            $balance = $balance_total;
            $service_charge = max(0,$balance_total * ($service_charge_rate / 100)) + $fixed_service_charge;
            $money += $service_charge;
            if($user['contribute_vadded'] < $money){
                throw new \Exception($fenxiao['texts']['contribute_vadded_score']."不足扣除手续费");
            }
            
            // $service_charge = max(0,$balance_total * ($service_charge_rate / 100)) + $fixed_service_charge;
            // $balance = $balance_total - $service_charge;
            if($balance <= 0){
                throw new \Exception("提现金额不足扣除手续费");
            }
            $balance_total = round($balance_total,2);
            $balance = round($balance,2);
            
            // throw new \Exception($money."，".$balance_total."，".$balance."，".$service_charge);
            
            $log = [
                'uniacid'=>UNIACID,
                'user_id'=>$user['id'],
                'type'=>1,
                'contribute_vadded'=>$money,
                'money'=>$balance_total,
                'realmoney'=>$balance,
                'service_charge'=>$service_charge,
                'createtime'=>time()
            ];
            
            $id = Db::name("bbfx_contribute_vadded_exchange_log")->insertGetId($log);
            $log['id'] = $id;
            $res = UserModel::setUserMoney($user['id'],0-$money,15,5,$fenxiao['texts']['contribute_vadded_score']."兑换",$log);
            if(empty($res)){
                throw new \Exception("操作失败");
            }
            
            $res = $this->model->setContribute(0-$balance_total,$user['id'],100001,"兑换扣除",$log);
            if(empty($res)){
                throw new \Exception("操作失败");
            }
            
            if(in_array(-10,$config['rewards'])){
                $this->model->setContribute($service_charge,$user['id'],100003,"兑换手续费",$log);
            }
            
            UserModel::setUserMoney($log['user_id'],$balance,1,5,$fenxiao['texts']['contribute_vadded_score']."兑换",$log);
            
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
        	$msg = $e->getMessage();
        	__error($msg);
        }
        
        __success("操作成功");
    }
}