<?php
namespace app\api\controller\coin;

use app\models\coin\UserCoinTransfer;
use app\models\redis\UserHash;
use app\models\store\StoreOrderCartInfo;
use app\models\system\DictCoin;
use app\models\user\UserCoin;
use app\Request;
use crmeb\services\{UtilService, JsonService};
use think\facade\Config;

class UserCoinController {
    public function status(Request $request) {
        
    }

    /**
     * 启动
     */
    public function boot(Request $request) {
        $uid = $request->uid();
        // 是否开启活动
        $symbol = Config::get('app.mining_symbo');
        if (!$symbol) {
            return app('json')->fail('本活动未开启');
        }
        // 是否已经开启
        $mining = UserHash::mining_get($uid);
        if ($mining) {
            if (isset($mining['progress']) && $mining['progress'] > 0.0) {
                return app('json')->fail('已启动');
            }
        }

        // 是否有订单
        $orderId = StoreOrderCartInfo::getMiningOrderId($uid);
        if (!$orderId) {
            return app('json')->fail('下单后可启动');
        }
        // 标记订单
        if (!StoreOrderCartInfo::setMining($orderId)) {
            return app('json')->fail('执行失败');
        }
        // 开启
        $secs_unit = Config::get('app.mining_sec_unit');
        $reward_unit = Config::get('app.mining_num_per_unit');
        $progress = floatval(bcdiv($reward_unit, $secs_unit, 8));
        $icon = DictCoin::getIcon($symbol);
        $balance = UserCoin::where('uid', $uid)->where('symbol', $symbol)->value('balance') ?? 0.0;

        $suc = UserHash::mining_set($uid, [
            'symbol'=> $symbol,
            'icon' => $icon,
            'price' => 0,
            'progress' => $progress,
            'total' => $balance,
            'ts' => time(),
            'order_id' => $orderId,
        ]);

        if ($suc != 0 && $suc != 1) {
            StoreOrderCartInfo::setMining($orderId, 0);
            return app('json')->fail('未成功执行');
        }

        return app('json')->successful([
            "symbol" => $symbol,
            'icon' => $icon,
            'price' => 0,
            'step' => $progress,
            'progress' => $progress,
            'total' => $balance,
        ]);
    }

    /**
     * 请求转账记录
     */
    public function history(Request $request) {
        [$page, $limit] = UtilService::getMore([
            ['page', 1],
            ['limit', 20],
        ], $request, true);
        $uid = $request->uid();
        $rows = UserCoinTransfer::getUserTransferred($uid, $page, $limit);
        return app('json')->successful($rows);
    }

    /*
     * 更新钱包地址
     */
    public function updateAddr(Request $request) {
        list($symbol, $addr) = UtilService::postMore([
            ['symbol', ''],
            ['addr', ''],
        ], $request, true);
        if (!$symbol || !$addr) {
            return app('json')->fail('参数不可为空');
        }
        if (!DictCoin::where('symbol', $symbol)->select()->toArray()) {
            return app('json')->fail('未找到目标');
        }

        $uid = $request->uid();
        $suc = UserCoin::upsertAddr($uid, $symbol, $addr);
        if (!$suc) {
            return app('json')->fail('执行失败');
        }
        return app('json')->successful();
    }

    /*
     * 提现
     */
    public function transfer(Request $request) {
        list($symbol, $amount) = UtilService::postMore([
            ['symbol', ''],
            ['amount', 0.0]
        ], $request, true);

        if(!$symbol) {
            return app('json')->fail('参数不可为空');
        }
        $meta = DictCoin::where('symbol', $symbol)->find();
        if (!$meta) {
            return app('json')->fail('未找到目标');
        }
        $meta = $meta->toArray();
        if ($amount < $meta['min_withdrawal']){
            return app('json')->fail('未达到最低限额');
        }
        $uid = $request->uid();
        $userCoin = UserCoin::where(['uid'=>$uid, 'symbol'=>$symbol])->find();
        if (!$userCoin) {
            return app('json')->fail('不适用的用户');
        }
        $userCoin = $userCoin->toArray();
        if(!$userCoin['addr']) {
            return app('json')->fail('地址未设置');
        }
        if ($userCoin['balance'] < $amount) {
            return app('json')->fail('余额不足');
        }
        $transferred = UserCoinTransfer::hasTransferred($uid, $symbol, $userCoin['addr']);
        if (!$transferred) {
            return app('json')->fail('首次操作需联系客服进行');
        }
        // transfer
        UserCoin::beginTrans();
        $left = bcsub($userCoin['balance'], $amount, 8);
        $res1 = UserCoin::where(['uid'=>$uid, 'symbol'=>$symbol])->update(['balance'=>$left]);
        $res2 = UserCoinTransfer::withdrawal($uid, $symbol, $userCoin['addr'], $amount);

        $ok = $res1 && $res2;
        UserCoin::checkTrans($ok);
        if (!$ok) {
            return app('json')->fail('执行失败');
        }
        return app('json')->successful('成功,已开始审核');
    }
}