<?php


namespace app\api\controller\trade;


use app\models\mining\MiningMachine;
use app\models\trade\CashTradeOrder;
use app\models\trade\CashTradeOrderPayment;
use app\models\user\User;
use app\models\user\UserMoney;
use app\Request;
use crmeb\basic\BaseModel;
use crmeb\repositories\OrderRepository;
use crmeb\services\AliPayService;
use crmeb\services\CacheService;
use crmeb\services\UtilService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CashTradeController
{
    /**
     * @param $type
     * @return bool|string
     */
    public function merged($type)
    {
//        $key = 'mx0J52sOMse4D3bE3c';
//        $sec = 'ea508c4381c84527ae892fc5cbdd674d';
        $type = strtolower($type);
//        $type = 'eth';
        $url = "https://api.huobi.de.com/market/detail/merged?symbol={$type}usdt";
//        var_dump($url);
        $res = do_request($url, [], null, false, true);
        return json_decode($res, true);
    }
    /**
     * @param Request $request
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    /**
     * @param Request $request
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function can_trade_money(Request $request)
    {
        $list = sys_data('money_type');
        $new = [];
        foreach ($list as $v) {
            if (explode('_', $v['code'])[0] == "USDT") {
                if ($v['price'] <= 0) {
                    //计算前一天成交的平均价格
                    $v['price'] = CashTradeOrder::averagePrice($v['code']);
                }
                $usdt_price = $v['price'];
            }
            if ($v['is_trade']) {
//                if ($v['price'] <= 0) {
//                    //计算前一天成交的平均价格
//                    $v['price'] = CashTradeOrder::averagePrice($v['code']);
//                }
                if ($request->uid())
                    $v['wallet'] = UserMoney::initialUserMoney($request->uid(), $v['code']);
                unset($v['cash_commission_ratio']);
                unset($v['cash_commission_type']);
                unset($v['can_cash']);
                unset($v['can_trade']);
                unset($v['is_trade']);
                $new[] = $v;

            }
        }
        foreach ($new as $k => $v) {
            $new[$k]['usdt'] = (isset($usdt_price) && $usdt_price > 0) ? bcdiv($new[$k]['price'], $usdt_price, 8) : 0;
        }
        return app('json')->success('ok', $new);
    }

    public function all_money_redis()
    {
        $list = sys_data('money_type');
        $new = [];
        foreach ($list as $v) {
            if (explode('_', $v['code'])[0] == "USDT") {
                if ($v['price'] <= 0) {
                    //计算前一天成交的平均价格
                    $v['price'] = CashTradeOrder::averagePrice($v['code']);
                }
                $usdt_price = $v['price'];
            }
            $v['has_mining'] = (MiningMachine::valid()->where('get_money_type', $v['code'])->find()) ? 1 : 0;
            $new[] = $v;
        }
        foreach ($new as $k => $v) {
            if (!(explode('_', $v['code'])[0] == "USDT")) {
                $res = $this->merged($v['code']);
                if ($res['status'] == 'error') {
                    $new[$k]['usdt'] = 0;
                    $new[$k]['price'] = 0;
                    $new[$k]['up'] = 0;
                } else {
                    $new[$k]['usdt'] = $res['tick']['close'];
                    $new[$k]['price'] = bcmul($usdt_price, $new[$k]['usdt'], 2);
                    $new[$k]['up'] = bcdiv(bcsub($res['tick']['close'], $res['tick']['open'], 8), $res['tick']['open'], 4);
                }
            } else {
                $new[$k]['usdt'] = 1;
                $new[$k]['up'] = 0;
            }
        }
        CacheService::redisHandler()->set('all_money_kp', $new);
    }

    public function all_money(Request $request)
    {
        $info = CacheService::redisHandler()->get('all_money_kp');
        if (!$info) {
            $this->all_money_redis();
            $info = CacheService::redisHandler()->get('all_money_kp');
        }

        foreach ($info as &$v) {
            if ($request->uid())
                $v['wallet'] = UserMoney::initialUserMoney($request->uid(), $v['code']);
        }
        return app('json')->success('ok', $info);
    }

    public function can_cash_money(Request $request)
    {
        $list = sys_data('money_type');
        $new = [];
        foreach ($list as $v) {
            if (explode('_', $v['code'])[0] == "USDT") {
                if ($v['price'] <= 0) {
                    //计算前一天成交的平均价格
                    $v['price'] = CashTradeOrder::averagePrice($v['code']);
                }
                $usdt_price = $v['price'];
            }
            if ($v['can_cash']) {
//                if ($v['price'] <= 0) {
//                    //计算前一天成交的平均价格
//                    $v['price'] = CashTradeOrder::averagePrice($v['code']);
//                }
                if ($request->uid())
                    $v['wallet'] = UserMoney::initialUserMoney($request->uid(), $v['code']);
                unset($v['cash_commission_ratio']);
                unset($v['cash_commission_type']);
                unset($v['can_cash']);
                unset($v['can_trade']);
                unset($v['is_trade']);
                $new[] = $v;

            }
        }
        foreach ($new as $k => $v) {
            $new[$k]['usdt'] = (isset($usdt_price) && $usdt_price > 0) ? bcdiv($new[$k]['price'], $usdt_price, 8) : 0;
        }
        return app('json')->success('ok', $new);
    }


    /**
     * @param Request $request
     * @return mixed
     */
    public function sale_list(Request $request)
    {
        $where = UtilService::getMore([
            ['money_type', ''],
            ['uid', 0],
            ['page', 1],
            ['limit', 10],
            ['status', 1],
        ], $request);
        $where['trade_type'] = 1;
        return app('json')->success('ok', CashTradeOrder::getList($where));
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function buy_list(Request $request)
    {
        $where = UtilService::getMore([
            ['money_type', ''],
            ['uid', 0],
            ['page', 1],
            ['limit', 10],
            ['status', 1],
        ], $request);
        $where['trade_type'] = 2;
        return app('json')->success('ok', CashTradeOrder::getList($where));
    }

    /**
     * 挂起
     * @param Request $request
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function hang(Request $request)
    {
        $user = $request->user();
        $uid = $user['uid'];
        list($money_type, $money_num, $price, $trade_type, $trade_way, $from, $hang_time, , $captcha) = UtilService::postMore([
            ['money_type', 'USDT_ERC20', '', '', ['not_empty_check', function ($item) {
                $moneys = sys_data('money_type');
                $new_money = [];
                foreach ($moneys as $v) {
                    if ($v['is_trade'] == 1) {
                        $new_money[] = $v['code'];
                    }
                }
                return in_array($item, $new_money);
            }], ['请选择交易的币种', '请选择支持交易的币种']],
            ['money_num', 0],
            ['price', 0],
            ['trade_type', 0, '', '', ['not_empty_check', function ($item) {
                return in_array($item, [1, 2]);
            }], '请选择挂买或挂卖'],
            ['trade_way', 'weixin'],
            ['from', 'weixin'],
            ['hang_time', 0, '', '', ['not_empty_check', function ($item) {
                return $item > 0 && $item < 1000;
            }], '请输入正确的挂出时常'],
            ['trade_psw', '', '', '', ['not_empty_check', function ($item) use ($user) {
                return md5(md5($item)) == $user['trade_pwd'];
            }], ['请输入交易密码', '交易密码错误']],
            ['captcha', '']
        ], $request, true);
        if ($money_num <= 0) {
            return app('json')->fail('请输入币数');
        }
        if ($price <= 0) {
            return app('json')->fail('请输入单价');
        }
        $sum = bcmul($money_num, $price, 2);
        if ($sum >= 10000) {
            $verifyCode = CacheService::get('code_' . $user['account']);
            if (!$verifyCode)
                return app('json')->fail('请先获取验证码');
            $verifyCode = substr($verifyCode, 0, 6);
            if ($verifyCode != $captcha)
                return app('json')->fail('验证码错误');
        }
        switch ($trade_type) {
            case 1:
                $res = CashTradeOrder::hangSale($uid, $money_type, $money_num, $price, $hang_time);
                break;
            case 2:
                $res = CashTradeOrder::hangBuy2($uid, $money_type, $money_num, $price, $hang_time);//改方式
//                $res = CashTradeOrder::hangBuy($uid, $money_type, $money_num, $price, $hang_time);
//                if ($res) {
//                    $orderId = $res['order_id'];
//                    switch ($trade_way) {
//                        case "weixin":
//                            $orderInfo = CashTradeOrderPayment::where('order_id', $orderId)->find();
//                            if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
//                            $orderInfo = $orderInfo->toArray();
//                            if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
//                            //支付金额为0
//                            if (bcsub((float)$orderInfo['pay_money'], 0, 2) <= 0) {
//                                //创建订单jspay支付
//                                $payPriceStatus = CashTradeOrderPayment::jsPayPrice($orderId, $uid);
//                                if ($payPriceStatus)//0元支付成功
//                                    return app('json')->status('success', '微信支付成功');
//                                else
//                                    return app('json')->status('pay_error', CashTradeOrderPayment::getErrorInfo());
//                            } else {
//                                try {
//                                    if ($from == 'routine') {
//                                        $jsConfig = OrderRepository::tradeJsPay($orderId); //创建订单jspay
//                                    } else if ($from == 'weixinh5') {
//                                        $jsConfig = OrderRepository::tradeH5Pay($orderId);
//                                    } else {
//                                        $jsConfig = OrderRepository::tradeWxPay($orderId);
//                                    }
//                                } catch (\Exception $e) {
//                                    return app('json')->status('pay_error', $e->getMessage());
//                                }
//                                $res['jsConfig'] = $jsConfig;
//                                if ($from == 'weixinh5') {
//                                    return app('json')->status('wechat_h5_pay', '订单创建成功', $res);
//                                } else {
//                                    return app('json')->status('wechat_pay', '订单创建成功', $res);
//                                }
//                            }
//                        case 'yue':
//                            if (CashTradeOrderPayment::yuePay($orderId, $request->uid()))
//                                return app('json')->status('success', '余额支付成功');
//                            else {
//                                $errorinfo = CashTradeOrderPayment::getErrorInfo();
//                                if (is_array($errorinfo))
//                                    return app('json')->status($errorinfo['status'], $errorinfo['msg']);
//                                else
//                                    return app('json')->status('pay_error', $errorinfo);
//                            }
//                        case 'ali':
//                            try {
//                                $jsConfig = AliPayService::createTrade($orderId); //创建订单jspay
//                            } catch (\Exception $e) {
//                                return app('json')->status('pay_error', $e->getMessage());
//                            }
//                            $res['jsConfig'] = $jsConfig;
//                            return app('json')->status('ali_pay', '订单创建成功', $res);
//                        default:
//                            return app('json')->fail('支付方式错误');
//                    }
//                } else return app('json')->fail(CashTradeOrder::getErrorInfo('订单生成失败!'));
                break;
            default:
                $res = false;
                break;
        }
        if ($res) {
            return app('json')->success('挂出成功');
        } else {
            return app('json')->fail('挂出失败:' . CashTradeOrder::getErrorInfo('挂出错误'));
        }
    }

    public function trade(Request $request)
    {
        $user = $request->user();
        $uid = $user['uid'];
        list($id, $trade_way, $from, , $captcha) = UtilService::postMore([
            ['id', 'USDT_ERC20', '', '', ['not_empty_check'], ['请选择要进行的交易']],
            ['trade_way', 'weixin'],
            ['from', 'weixin'],
            ['trade_psw', '', '', '', ['not_empty_check', function ($item) use ($user) {
                return md5(md5($item)) == $user['trade_pwd'];
            }], ['请输入交易密码', '交易密码错误']],
            ['captcha', '']
        ], $request, true);
        $order = CashTradeOrder::setStatus(1)->where('id', $id)->find();
//        var_dump(CashTradeOrder::getLastSql());
        if (!$order) {
            return app('json')->fail('订单不存在或已结束挂出');
        }
        $sum = bcmul($order['money_num'], $order['price'], 2);
        if ($sum >= 10000) {
            $verifyCode = CacheService::get('code_' . $user['account']);
            if (!$verifyCode)
                return app('json')->fail('请先获取验证码');
            $verifyCode = substr($verifyCode, 0, 6);
            if ($verifyCode != $captcha)
                return app('json')->fail('验证码错误');
        }
        switch ($order['trade_type']) {
            case 2:
                $res = CashTradeOrder::sale($uid, $id);
                break;
            case 1:
                $res = CashTradeOrder::buy2($uid, $id);
//                if ($res) {
//                    $orderId = $res['order_id'];
//                    switch ($trade_way) {
//                        case "weixin":
//                            $orderInfo = CashTradeOrderPayment::where('order_id', $orderId)->find();
//                            if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
//                            $orderInfo = $orderInfo->toArray();
//                            if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
//                            //支付金额为0
//                            if (bcsub((float)$orderInfo['pay_money'], 0, 2) <= 0) {
//                                //创建订单jspay支付
//                                $payPriceStatus = CashTradeOrderPayment::jsPayPrice($orderId, $uid);
//                                if ($payPriceStatus)//0元支付成功
//                                    return app('json')->status('success', '微信支付成功');
//                                else
//                                    return app('json')->status('pay_error', CashTradeOrderPayment::getErrorInfo());
//                            } else {
//                                try {
//                                    if ($from == 'routine') {
//                                        $jsConfig = OrderRepository::tradeJsPay($orderId); //创建订单jspay
//                                    } else if ($from == 'weixinh5') {
//                                        $jsConfig = OrderRepository::tradeH5Pay($orderId);
//                                    } else {
//                                        $jsConfig = OrderRepository::tradeWxPay($orderId);
//                                    }
//                                } catch (\Exception $e) {
//                                    return app('json')->status('pay_error', $e->getMessage());
//                                }
//                                $res['jsConfig'] = $jsConfig;
//                                if ($from == 'weixinh5') {
//                                    return app('json')->status('wechat_h5_pay', '订单创建成功', $res);
//                                } else {
//                                    return app('json')->status('wechat_pay', '订单创建成功', $res);
//                                }
//                            }
//                        case 'yue':
//                            if (CashTradeOrderPayment::yuePay($orderId, $request->uid()))
//                                return app('json')->status('success', '余额支付成功');
//                            else {
//                                $errorinfo = CashTradeOrderPayment::getErrorInfo();
//                                if (is_array($errorinfo))
//                                    return app('json')->status($errorinfo['status'], $errorinfo['msg']);
//                                else
//                                    return app('json')->status('pay_error', $errorinfo);
//                            }
//                        case 'ali':
//                            try {
//                                $jsConfig = AliPayService::createTrade($orderId); //创建订单jspay
//                            } catch (\Exception $e) {
//                                return app('json')->status('pay_error', $e->getMessage());
//                            }
//                            $res['jsConfig'] = $jsConfig;
//                            return app('json')->status('ali_pay', '订单创建成功', $res);
//                        default:
//                            return app('json')->fail('支付方式错误');
//                    }
//                } else return app('json')->fail(CashTradeOrder::getErrorInfo('订单生成失败!'));
                break;
            default:
                $res = false;
                break;
        }
        if ($res) {
            return app('json')->success('交易开始进行,' . $order['trade_type'] == 1 ? '请通过用户的转账方式交易并上传交易凭证' : '请等待买家转账并上传凭证');
        } else {
            return app('json')->fail('交易失败:' . CashTradeOrder::getErrorInfo('挂出错误'));
        }
    }

    public function myOrder(Request $request)
    {
        $where = UtilService::getMore([
            ['money_type', ''],
            ['page', 1],
            ['limit', 10],
            ['status', ''],
            ['trade_type', '']
        ], $request);
//        $where['trade_type'] = 2;
        $where['uid'] = $request->uid();
        return app('json')->success('ok', CashTradeOrder::getList($where));
    }

    public function uploadProof($id, Request $request)
    {
        $order = CashTradeOrder::get($id);
        $proof = $request->post('proof', '');
        if (!not_empty_check($proof)) return app('json')->fail('请上传凭证');
        if ($order['close_time'] < time()) return app('json')->fail('订单已关闭');
        switch ($order['trade_type']) {
            case 1:
                if ($order['trade_uid'] != $request->uid()) return app('json')->fail('订单交易方错误');
                if ($order['status'] != -1) return app('json')->fail('订单状态错误');
                break;
            case 2:
                if ($order['uid'] != $request->uid()) return app('json')->fail('订单交易方错误');
                if ($order['status'] != 0) return app('json')->fail('订单状态错误');
                break;
            default:
                break;
        }
        $res = CashTradeOrder::where('id', $id)->update(['proof' => $proof, 'status' => 3]);
        if ($res) {
            return app('json')->fail('上传成功');
        } else {
            return app('json')->fail('上传失败');
        }
    }


    public function cancel($id, Request $request)
    {
        $order = CashTradeOrder::get($id);
        if ($order['close_time'] < time()) return app('json')->fail('订单已关闭');
        if ($order['status'] > 0) return app('json')->fail('订单不可撤销');
        BaseModel::beginTrans();
        $res = true;
        switch ($order['trade_type']) {
            case 1:
                //退回币
                $res = $res && UserMoney::incomeMoney($order['uid'], $order['money_type'], $order['money_num'], 'hang_sale_cancel', '挂卖取消', '挂卖取消,退回钱包');
                $res = $res && CashTradeOrder::where('id', $order['id'])->update(['status' => 2]);
                break;
            case 2:
//
                if ($order['trade_uid'])
                    $res = $res && UserMoney::incomeMoney($order['trade_uid'], $order['money_type'], $order['money_num'], 'hang_buy_cancel', '挂买取消', '挂买取消,退回钱包');
                $res = $res && CashTradeOrder::where('id', $order['id'])->update(['status' => 2]);
                break;
            default:
                break;
        }
        BaseModel::checkTrans($res);
        if ($res) {
            return app('json')->fail('取消成功');
        } else {
            return app('json')->fail('取消失败');
        }
    }

    public function check($id, $ok, Request $request)
    {
        $order = CashTradeOrder::where('id', $id)->where('status', 3)->find();
        if (!in_array($ok, ['y', 'n'])) return app('json')->fail('参数错误');
        $res = true;
        BaseModel::beginTrans();
        if ($ok == 'y') {
            switch ($order['trade_type']) {
                case 1:
                    if ($order['uid'] != $request->uid()) return app('json')->fail('订单审核方错误');
                    $res = $res && UserMoney::incomeMoney($order['trade_uid'], $order['money_type'], $order['money_num'], '购币成功', 'buy_success', '购币成功,出售方' . $order['uid']);
                    break;
                case 2:
                    if ($order['trade_uid'] != $request->uid()) return app('json')->fail('订单审核方错误');
                    $res = $res && UserMoney::incomeMoney($order['uid'], $order['money_type'], $order['money_num'], '购币成功', 'buy_success', '购币成功,出售方' . $order['trade_uid']);
                    break;
                default:
                    break;
            }
            $res = $res && CashTradeOrder::where('id', $id)->update(['status' => 1, 'trade_time' => time()]);
            BaseModel::checkTrans($res);
            if ($res) {
                return app('json')->fail('审核成功');
            } else {
                return app('json')->fail('审核失败');
            }
        } else {
            return app('json')->fail('请联系后台审核');
        }
    }
}