<?php

namespace app\home\service;

use app\model\PaymentListModel;
use app\model\RechargeApplyModel;
use app\model\StockMarketModel;
use app\model\UserModel;
use app\model\UserWithdrawalModel;
use app\model\WalletListModel;
use think\facade\Db;
use think\facade\Log;

/**
 * 处理团队佣金业务
 */
class PayService extends BaseHomeService
{
    public function getPaymentList(array $data)
    {
        $list = PaymentListModel::where([
            'status' => 1,
            'is_recharge' => 1,
            'is_online' => $data['is_online']
        ])->order('id', 'desc')->select()->toArray();

        return $this->toData(0, 'Request successful.', $list);
    }

    /**
     * 用户充值申请入库1
     * @param array $data
     * @return array
     */
    public function insertRechargeApply(array $data): array
    {
        $channel = PaymentListModel::getPaymentInfo([
            'id' => $data['recharge_channel']
        ]);

        if (empty($channel)) {
            return $this->toData('100110', 'The system is busy. Please try again later.1', []);
        }
        if (empty($data['country'])) {
            return $this->toData('100120', 'The system is busy. Please try again later.2', []);
        }
        if (empty($data['recharge_num']) || $data['recharge_num'] <= 0) {
            return $this->toData('100130', 'The system is busy. Please try again later.3', []);
        }
        if($channel['type']==9){
            //1USD=1USDT
            $currency_rate = 1;
            if($data['product']=='TRC20Buy'){
                switch ($data['extra']){
                    case 'GBP':
                        $gpx_rate=StockMarketModel::where('stock_market_type',14)->value('rate');
                        $currency_rate=$gpx_rate/100;
                    break;
                    case "EUR":
                        $eur_rate=StockMarketModel::where('stock_market_type',15)->value('rate');
                        $currency_rate=$eur_rate*1;
                    break;
                }
            }
        }else{
            $currency_rate = $channel['exchange_rate'];
        }
        //$currency_rate=(new StockMarketModel)->getRate(4);
        if ($data['account_type'] > 2 && ($data['account_type'] != 8)) {
            $market_rate = (new StockMarketModel)->getRate($data['account_type']);
        } else {
            $market_rate = 1;
        }
        $market_amount = $data['recharge_num'] * $market_rate;
        $market_amount = round($market_amount, 2);

        if ($channel['pay_type'] == 1) {
            $fee = $data['recharge_num'] * $currency_rate * $channel['service_rate'];
            $server_fee = $market_amount * $channel['service_rate'];
        } else {
            $fee = $currency_rate * $channel['service_rate'];
            $server_fee = $market_rate * $channel['service_rate'];
        }
        $total_amount = $data['recharge_num'] * $currency_rate + $fee;
        $total_amount = round($total_amount, 2);

        if ($data['is_online'] == 1 && $total_amount > 100000) {
            return $this->toData('101900', 'Online payment scope: 100 - 100000');
        }
        $data['service_fee'] = $server_fee;//手续费用
        $data['market_amount'] = $market_amount; //换算的市场金额
        $data['total_amount'] = $total_amount;  //要支付的渠道货币金额
        $data['currency_rate'] = $currency_rate;
        if ($channel['channel_type'] == 'Bank') {
            $data['recharge_type'] = 2;
        } else {
            $data['recharge_type'] = 1;
        }

        $data['order_no'] = $this->generateOrderNumber();

        $order_id = RechargeApplyModel::InsertUserRecharge($data);
        if ($order_id) {
            switch ($channel['type']) {
                case 2:
                    $result = (new IndPayService())->indPay($data['order_no'], $data['total_amount']);
                    if ($result['status'] == 'SUCCESS') {
                        RechargeApplyModel::where('order_no', $data['order_no'])->update([
                            'order_idx' => $result['order_no'],
                            'pay_url' => $result['order_data'],
                        ]);
                        return $this->toData(0, 'Request successful.', [
                            'type' => 'bank_pay',
                            'pay_url' => $result['order_data'],
                            'order_no' => $result['mer_order_no'],
                        ]);
                    } else {
                        return $this->toData('100900', 'The system is busy. Please try again later.4', [$result['err_msg'], $result['err_code']]);
                    }
                    break;
                case 3:
                    $result = (new MoPayService())->create_order($data['order_no'], $data['total_amount']);
                    if ($result['status'] == 'SUCCESS') {
                        RechargeApplyModel::where('order_no', $data['order_no'])->update([
                            'pay_url' => $result['data']['pay_url'],
                        ]);
                        return $this->toData(0, 'Request successful.', [
                            'type' => 'bank_pay',
                            'pay_url' => $result['data']['pay_url'],
                            'order_no' => $data['order_no'],
                        ]);
                    } else {
                        return $this->toData('100600', 'The system is busy. Please try again later.5', [$result['err_msg'], $result['err_code']]);
                    }
                    break;
                case 4:
//                    $result = (new HTPayService())->qrPay($data['order_no'], round($data['total_amount']));
//                    if ($result['status'] == 1) {
//                        RechargeApplyModel::where('order_no', $data['order_no'])->update([
//                            'order_idx' => $result['orderNo'],
//                            'pay_url' => $result['payUrl'],
//                            'total_amount' => $result['oriAmount']
//                        ]);
//                        return $this->toData(0, 'Request successful.', [
//                            'type' => 'bank_pay',
//                            'pay_url' => $result['payUrl'],
//                            'order_no' => $data['order_no'],
//                        ]);
//                    } else {
//                        return $this->toData('101900', 'The system is busy. Please try again later.6', [$result['status'], $result['message']]);
//                    }
                    // 20250110 跟负责人确认不要第三方验证,后台管理端手动审核订单信息
                    return $this->toData(0, 'Request successful.', [
                        'type' => 'bank_pay',
                        'pay_url' => '',
                        'order_no' => $data['order_no'],
                    ]);
                    break;
                case 5:
                    $result = (new XdPayService())->create_order($data['order_no'], $data['total_amount']);
                    if ($result['code'] == 200) {
                        RechargeApplyModel::where('order_no', $data['order_no'])->update([
                            'pay_url' => $result['data']['url'],
                        ]);
                        return $this->toData(0, 'Request successful.', [
                            'type' => 'bank_pay',
                            'pay_url' => $result['data']['url'],
                            'order_no' => $data['order_no'],
                        ]);
                    } else {
                        return $this->toData('101900', 'The system is busy. Please try again later.7', [$result['code'], $result['msg']]);
                    }
                    break;
                case 6:
                    $result = (new QeaePayService())->create_order($data['order_no'], $data['total_amount']);
                    if ($result['respCode'] == 'SUCCESS') {
                        RechargeApplyModel::where('order_no', $data['order_no'])->update([
                            'pay_url' => $result['payInfo'],
                        ]);
                        return $this->toData(0, 'Request successful.', [
                            'type' => 'bank_pay',
                            'pay_url' => $result['payInfo'],
                            'order_no' => $data['order_no'],
                        ]);
                    } else {
                        return $this->toData('101900', 'The system is busy. Please try again later.8', [$result['respCode'], $result['tradeMsg']]);
                    }
                    break;
                case 7:
                    $result = (new NicePayService())->create_order($data['order_no'], $data['total_amount']);
                    if ($result['err'] == 0 && !empty($result)) {
                        RechargeApplyModel::where('order_no', $data['order_no'])->update([
                            'pay_url' => $result['url'],
                        ]);
                        return $this->toData(0, 'Request successful.', [
                            'type' => 'bank_pay',
                            'pay_url' => $result['url'],
                            'order_no' => $data['order_no'],
                        ]);
                    } else {
                        return $this->toData('101900', 'The system is busy. Please try again later.9', [$result['err'], $result['err_msg']]);
                    }
                    break;
                case 8:
                    $result = (new ClickPayService())->create_order($data['order_no'], $data['total_amount']);
                    if (strtoupper($result['platRespCode']) == 'SUCCESS') {
                        RechargeApplyModel::where('order_no', $data['order_no'])->update([
                            'order_idx' => $result['platOrderNum'],
                        ]);
                        return $this->toData(0, 'Request successful.', [
                            'type' => 'bank_pay',
                            'pay_url' => $result['payData'],
                            'order_no' => $data['order_no'],
                        ]);
                    } else {
                        return $this->toData('101900', 'The system is busy. Please try again later.10');
                    }
                    break;
                case 9:
                    if(in_array(trim($data['product']),['TRC20H5','TRC20Buy'])){
                        $result = (new StarPayService())->create_order($data['order_no'], $data['total_amount'],$data['product'],$data['extra']);
                        if ($result['code'] == 200) {
                            $respon=json_decode($result['params'],true);
                            RechargeApplyModel::where('order_no', $data['order_no'])->update([
                                'pay_url' => $respon['payurl'],
                            ]);
                            return $this->toData(0, 'Request successful.', [
                                'type' => 'bank_pay',
                                'pay_url' => $respon['payurl'],
                                'order_no' => $data['order_no'],
                            ]);
                        } else {
                            return $this->toData('100600', 'The system is busy. Please try again later.5', $result);
                        }
                    }else{
                        return $this->toData('102000', 'The system is busy. Please try again later.20');
                    }
                    break;
                default:
                    return $this->toData(0, 'Request successful.', []);
                    break;
            }

        } else {
            return $this->toData(100140, 'The system is busy. Please try again later.10', []);
        }
    }

    public function dealPayNotify($order_info)
    {
        $wallet = new WalletService();
        // 启动事务
        Db::startTrans();
        try {
            //查询划转资金账户信息
            $account = $wallet->lockUserBalance($order_info['account_type'], $order_info['user_id']);
            if (empty($account)) {
                Db::rollback();
                return [
                    'code' => 100,
                    'msg' => 'FAIL'
                ];
            }
            // 新增转入 特别需要注意的是,股票账户需要进行汇率转换  现货\合约\美股都是USD
            $update_data['usable_num'] = $account['usable_num'] + $order_info['market_amount'];
            $res = $wallet->updateUserBalance($order_info['account_type'], $update_data, $order_info['user_id']);
            if (empty($res)) {
                Db::rollback();
                return [
                    'code' => 300,
                    'msg' => 'FAIL'
                ];
            }
            //插入资金变动日志
            $logs['user_id'] = $order_info['user_id'];
            $logs['change_type'] = 1;
            $logs['change_num'] = $order_info['market_amount'];
            $logs['before_num'] = $account['usable_num'];
            $logs['order_id'] = $order_info['order_no'];
            $log_res = $wallet->addUserBalanceLog($order_info['account_type'], $logs);
            if (empty($log_res)) {
                Db::rollback();
                return [
                    'code' => 400,
                    'msg' => 'FAIL'
                ];
            }
            //修改订单状态
            RechargeApplyModel::where('id', $order_info['id'])->update([
                'status' => 1,
                'deal_time' => date('Y-m-d H:i:s'),
            ]);
            // 提交事务
            Db::commit();
            return [
                'code' => 200,
                'msg' => 'SUCCESS'
            ];
        } catch (\Exception $e) {
            // 出现异常,回滚事务
            Db::rollback();
            return [
                'code' => 500,
                'msg' => $e->getMessage()
            ];
        }
    }


}