<?php

namespace app\admin\service;

use app\admin\validate\RechargeValidate;
use app\model\AdminModel;
use app\model\FileModel;
use app\model\PaymentListModel;
use app\model\RechargeApplyModel;
use app\model\UserModel;
use think\facade\Cache;

class RechargeService extends AdminBaseService
{

    public function index($param, $adminId)
    {
        try {
            // 参数校验
            validate(RechargeValidate::class)->scene('index')->check($param);
            $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' => [], ]);
                }
                $userId = $user['user_id'];
            }
            $statusList = RechargeApplyModel::$statusList;
            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extend' => $statusList]);
            }
            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_no'] = $param['order_id'];
            }
            if (isset($param['is_online'])) {
                $where['is_online'] = $param['is_online'];
                if ($param['is_online'] == 1) $statusList[0] = '用户取消';
            }

            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']]];
            }

            Cache::store('redis')->set('Recharge_Read_Time'.$adminId,time());
            // 列表
            $list = RechargeApplyModel::where($where)->where($whereU)->order('id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = RechargeApplyModel::where($where)->where($whereU)->count();
            // 统计 充值成功
            $sum = RechargeApplyModel::where($where)->where($whereU)->where('status', 1)->sum('recharge_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');
                $rows = $list->toArray();
                foreach ($rows as $key => $item) {
                    $rows[$key]['status_text'] = $statusList[$item['status']];
                    $rows[$key]['user_no'] = $userNoArr[$item['user_id']] ?? '-'; // 用户号
                    $rows[$key]['order_id'] = $item['order_no'];
                    $rows[$key]['recharge_channel'] = PaymentListModel::where('id', $item['recharge_channel'])->value('channel');
                }
            }
            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows, 'sum' => $sum . 'USD', 'extend' => $statusList]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function info($param, $adminId)
    {
        try {
            // 参数校验
            validate(RechargeValidate::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', []);
            }

            $info = RechargeApplyModel::getOrderInfo($where);
            if ($info['file_id']) {
                $info['file_url'] = FileModel::getFilePath($info['file_id']);
            }
            $payment_info = PaymentListModel::getPaymentInfo([
                'id' => $info['recharge_channel']
            ]);
            if ($payment_info) {
                $info['recharge_channel'] = !isset($payment_info['channel']) ? $payment_info['channel'] : $info['recharge_channel'];
                $info['bank_name'] = !isset($payment_info['bank_name']) ? $payment_info['bank_name'] : '';
                $info['bank_branch'] = !isset($payment_info['bank_branch']) ? $payment_info['bank_branch'] : '';
                $info['bank_user'] = !isset($payment_info['bank_user']) ? $payment_info['bank_user'] : '';
                $info['bank_account'] = !isset($payment_info['bank_account']) ? $payment_info['bank_account'] : '';
                $info['wallet_address'] = !isset($payment_info['wallet_address']) ? $payment_info['wallet_address'] : '';
            }
            return $this->toData('0', 'SUCCESS', $info);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }

    }

    public function check($param, $adminId)
    {
        try {
            // 参数校验
            validate(RechargeValidate::class)->scene('info')->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', []);
            }
            $info = RechargeApplyModel::getOrderInfo($where);
            if ($info) {
                if ($info['is_online'] == 1){
                    return $this->toData('10040', '在线充值 不可操作');
                }

                if ($info['is_check'] == 0) {
                    if ($param['check_status'] == 1) {
                        if(env('ACCOUT_TYPE.ALL_IN_ONE')==1){
                            $result = $this->updateUserAssetNew($info['user_id'], 1, $info['market_amount'], 0, $info['order_no']);
                        }else{
                            $result = $this->updateUserAsset($info['user_id'], $info['account_type'], 1, $info['market_amount'], 0, $info['order_no']);
                        }
                        if ($result['status'] == 200) {
                            RechargeApplyModel::where('id', $info['id'])->update([
                                'is_check' => 1,
                                'status' => 1,
                                'deal_time' => date('Y-m-d H:i:s')
                            ]);
                        } else {
                            return $this->toData('1015', $result['msg'],$result['data']);
                        }
                    } else {
                        RechargeApplyModel::where('id', $info['id'])->update([
                            'is_check' => 2,
                            'status' => 2
                        ]);
                    }
                }
                if ($info['file_id']) {
                    $info['file_url'] = FileModel::getFilePath($info['file_id']);
                    $file = dirname(dirname(dirname(__DIR__))) . "/public" . $info['file_url'];
                    @unlink($file);
                }

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

    }
}