<?php

namespace app\admin\service;

use app\admin\validate\WithdrawValidate;
use app\home\service\ClickPayService;
use app\home\service\HTPayService;
use app\home\service\IndPayService;
use app\home\service\MoPayService;
use app\home\service\NicePayService;
use app\home\service\PayService;
use app\home\service\QeaePayService;
use app\home\service\TrcPayService;
use app\home\service\XdPayService;
use app\model\AdminModel;
use app\model\PaymentListModel;
use app\model\UserBankModel;
use app\model\UserModel;
use app\model\UserWithdrawalModel;
use think\facade\Cache;
use function AlibabaCloud\Client\backgroundRed;

class WithdrawService extends AdminBaseService
{

    public function index($param, $adminId)
    {
        try {

            // 参数校验
            validate(WithdrawValidate::class)->scene('index')->check($param);
            Cache::store('redis')->set('Withdraw_Read_Time'.$adminId,time());
            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extend' => UserWithdrawalModel::$statusList]);
                }
                $userId = $user['user_id'];
            }
            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extend' => UserWithdrawalModel::$statusList]);
            }
            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_no'] = $param['order_id'];
            }
            if (isset($param['status'])) {
                $where['status'] = $param['status'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['update_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = UserWithdrawalModel::where($where)->where($whereU)->order('id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = UserWithdrawalModel::where($where)->where($whereU)->count();
            // 统计 提现成功
            $sum = UserWithdrawalModel::where($where)->where($whereU)->where('status', 4)->sum('apply_num');



            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                $ifscArr = UserBankModel::where('user_id', 'in', $userIdArr)->column('ifsc', 'user_id');

                $rows = $list->toArray();
                foreach ($rows as $key => $item) {
                    $rows[$key]['user_no'] = $userNoArr[$item['user_id']] ?? '-'; // 用户号.
                    $rows[$key]['ifsc'] = $ifscArr[$item['user_id']] ?? '-'; // ifsc
                    $rows[$key]['order_id'] = $item['order_no'];
                    $rows[$key]['status_text'] = UserWithdrawalModel::$statusList[$item['status']];
                    //$rows[$key]['pay_info'] = json_decode($item['pay_info'],true);
                }
            }
            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows, 'sum' => $sum . 'USD', 'extend' => UserWithdrawalModel::$statusList]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function info($param, $adminId)
    {
        try {
            // 参数校验
            validate(WithdrawValidate::class)->scene('info')->check($param);
            $where = [
                'id' => $param['id']
            ];

            $userId = 0;
            $where = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($where)) {
                return $this->toData('0', 'SUCCESS', []);
            }

            $order_info = [];
            $info = UserWithdrawalModel::where($where)->find();
            $ifsc = UserBankModel::where('user_id', $info->user_id)->value('ifsc');

            if (!$info->isEmpty()) {
                $order_info = $info->toArray();
                $order_info['pay_info'] = json_decode($order_info['pay_info'], true);
                $channel = PaymentListModel::getPaymentInfo([
                    'id' => intval($order_info['channel_id'])
                ]);
                $order_info['channel_name'] = isset($channel['channel']) ? $channel['channel'] : '';
                $order_info['ifsc'] = $ifsc ?? '-';
            }
            return $this->toData('0', 'SUCCESS', $order_info);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }

    }

    public function change_status($param, $adminId)
    {
        try {
            // 参数校验
            validate(WithdrawValidate::class)->scene('status')->check($param);
            $isAgent = AdminModel::checkUserIsAgent($adminId);
            if ($isAgent) {
                return $this->toData('10040', '代理无权限操作');
            }
            $where = [
                'id' => $param['id']
            ];
            $userId = 0;
            $where = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($where)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => []]);
            }

            $order_info = [];
            $info = UserWithdrawalModel::where($where)->find();
            if (empty($info)) {
                return $this->toData('1004', '订单不存在');
            }
            $order_info = $info->toArray();
            $change_flag = false;
            if ($order_info['status'] == 0 && $param['status'] < 3) {
                $change_flag = true;
            }
            if ($order_info['status'] = 1 && ($param['status'] == 3 || $param['status'] == 2)) {
                $change_flag = true;
            }
            if ($order_info['status'] = 3 && $param['status'] == 4) {
                $change_flag = true;
            }
            $pay_flag = false;
            $msg = "";
            $content = "";
            if ($change_flag) {
                $update_data['status'] = $param['status'];
                $update_data['update_time'] = date('Y-m-d H:i:s');
                //拒绝
                if ($param['status'] == 2) {
                    if(env('ACCOUT_TYPE.ALL_IN_ONE')==1){
                        $updateStatus = $this->updateUserAssetNew($order_info['user_id'],  6, $order_info['market_amount'], -$order_info['market_amount'], $order_info['order_no']);
                    }else{
                        $updateStatus = $this->updateUserAsset($order_info['user_id'], $order_info['account_type'], 6, $order_info['market_amount'], -$order_info['market_amount'], $order_info['order_no']);
                    }

                }

                //代付
                if ($param['status'] == 3) {
                    //解冻资金 ,扣除提现
                    if(env('ACCOUT_TYPE.ALL_IN_ONE')==1){
                        $updateOne = $this->updateUserAssetNew($order_info['user_id'],  6, $order_info['market_amount'], -$order_info['market_amount'], $order_info['order_no']);
                    }else{
                        $updateOne = $this->updateUserAsset($order_info['user_id'], $order_info['account_type'], 6, $order_info['market_amount'], -$order_info['market_amount'], $order_info['order_no']);
                    }

                    if (!empty($updateOne) && $updateOne['status'] == 200) {
                        if(env('ACCOUT_TYPE.ALL_IN_ONE')==1){
                            $updateStatus = $this->updateUserAssetNew($order_info['user_id'], 2, -$order_info['market_amount'], 0, $order_info['order_no']);
                        }else{
                            $updateStatus = $this->updateUserAsset($order_info['user_id'], $order_info['account_type'], 2, -$order_info['market_amount'], 0, $order_info['order_no']);
                        }

                    } else {
                        //提现事务回滚...
                        trace("提现失败1 - change_status - order_no=" . $order_info['order_no'] . "---user_id= " . $order_info['user_id'] . "---account_type= " . $order_info['account_type'] . "---market_amount= " . $order_info['market_amount']);
                        return $this->toData($updateOne['status'] ?? '3251', $updateOne['msg'] ?? $msg, [$content]);
                    }

                    if (!empty($updateStatus) && $updateStatus['status'] == 200) {
                        $channel = PaymentListModel::getPaymentInfo([
                            'id' => $param['channel']
                        ]);
                        if ($channel) {
                            $result = $this->payToUser($order_info, $channel);
                            if ($result['code'] == 200) {
                                $update_data['order_idx'] = $result['order_idx'];
                                $update_data['channel_id'] = $param['channel'];
                            } else {
                                $update_data['status'] = 1;  //代付失败
                                $pay_flag = true;
                                $content = $result['content'];
                                $msg = $result['msg'];
                            }
                        }
                        //手动支付完成
                        if ($param['channel'] == 0) {
                            $update_data['status'] = 4;
                            $update_data['channel_id'] = $param['channel'];
                        }
                    }
                }

                $update_data['beizhu'] = $param['beizhu'] ?? "";

                if ($param['status'] == 1 || (!empty($updateStatus) && $updateStatus['status'] == 200)) {
                    UserWithdrawalModel::where($where)->update($update_data);
                } else {
                    trace("提现失败2 - change_status - order_no=" . $order_info['order_no'] . "---user_id= " . $order_info['user_id'] . "---account_type= " . $order_info['account_type'] . "---market_amount= " . $order_info['market_amount']);
                    return $this->toData($updateStatus['status'] ?? '3251', $updateStatus['msg'] ?? $msg, [$content]);
                }

                if ($pay_flag) {
                    return $this->toData('3250', $msg, [$content]);
                } else {
                    return $this->toData('0', 'SUCCESS');
                }

            } else {
                return $this->toData('10040', '操作流程不合法');
            }

        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    private function payToUser($order, $channel)
    {
        //货币单位换算
        $order['total_amount'] = $order['apply_num'] * $channel['exchange_rate'];
        $address_info = json_decode($order['pay_info'], true);

        switch ($channel['type']) {
            //印尼支付
            case 2:
                return (new IndPayService())->singleIndOrder($order);
                break;
            //TRC
            case 3:
                return (new MoPayService())->apply_pay($order['order_no'], $order['total_amount'], $address_info['bank_code'], $address_info['bank_card'], $address_info['true_name'], $address_info['bank_phone'], $address_info['ifsc']);
                break;
            //合泰
            case 4:
                return (new HTPayService())->arPay($order['order_no'], $order['total_amount'], $address_info['bank_code'], $address_info['bank_card'], $address_info['true_name']);
                break;
            //合泰
            case 5:
                return (new XdPayService())->apply_pay($order['order_no'], $order['total_amount'], $address_info['ifsc'], $address_info['bank_card'], $address_info['true_name']);
                break;
            //QEAE
            case 6:
                return (new QeaePayService())->apply_pay($order['order_no'], $order['total_amount'], $address_info['bank_card'], $address_info['true_name'], $address_info['ifsc'], $address_info['bank_code']);
                break;
            //合泰
            case 7:
                return (new NicePayService())->apply_pay($order['order_no'], $order['total_amount'], $address_info['bank_card'], $address_info['true_name'], $address_info['ifsc']);
                break;
            //ClickPay
            case 8:
                return (new ClickPayService())->apply_pay($order['order_no'], $order['total_amount'], $address_info['bank_card'], $address_info['true_name'], $address_info['ifsc'], $address_info['bank_code']);
                break;
            default:

                break;
        }
    }

    public function get_balance($param, $adminId)
    {
        $channel = PaymentListModel::getPaymentInfo([
            'id' => intval($param['id'])
        ]);
        if ($channel) {
            switch ($channel['type']) {
                case 1:
                    //$result=(new IndPayService())->getIndBalance();
                    $result = [
                        'amount' => 0
                    ];
                    break;
                case 2:
                    $result = (new TrcPayService())->getTrcBalance();
                    break;
                case 4:
                    $result = (new HTPayService())->getHtBalance();
                    break;
                case 5:
                    $result = (new XdPayService())->getBalance();
                    break;
                case 6:
                    $result = (new QeaePayService())->getBalance();
                    break;
                case 8:
                    $result = (new ClickPayService())->getBalance();
                    break;
                default:
                    $result = [
                        'amount' => 0
                    ];
                    break;
            }

            return $this->toData('0', '请求成功', $result);

        } else {
            return $this->toData('1', '参数错误,通道不存在', []);
        }
    }

    public function channel_list($param, $adminId)
    {
        try {
            // 参数校验
            validate(WithdrawValidate::class)->scene('info')->check($param);
            $where = [
                'id' => $param['id']
            ];

            $userId = 0;
            $where = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($where)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => []]);
            }

            $order_info = UserWithdrawalModel::getUserDrawalInfo($where);
            if ($order_info) {
                $channel_list = PaymentListModel::getPaymentList([
                    'is_withdrawal' => 1,
                    'status' => 1,
                    'channel_type' => $order_info['apply_type']
                ]);
            } else {
                $channel_list = [];
            }
            return $this->toData('0', '请求成功', $channel_list);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }


}