<?php

namespace plugin\admin\app\controller;

use app\api\repositories\MoneyLogRepositories;
use app\business\StreamBusiness;
use Illuminate\Support\Arr;
use plugin\admin\app\model\ApplyRecord;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserCark;
use plugin\admin\app\repositories\WithdrawRepositories;
use Respect\Validation\Validator;
use support\Db;
use support\Log;
use support\Request;
use support\Response;
use plugin\admin\app\model\Withdraw;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;
use yzh52521\EasyHttp\Http;

/**
 * 提现列表
 */
class UserCarkController extends Crud
{


    /**
     * @var UserCark
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new UserCark();
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('usercark/index');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('usercark/update');
    }

    /**查询收银余额
     * @param Request $request
     * @return Response
     */
    public function select(Request $request): Response
    {
        $param = $request->all();
        $data  = UserCark::query()->where(function ($query) use ($param) {
            if (Arr::get($param, 'created_at.0') && Arr::get($param, 'created_at.1')) {
                $query->whereBetween('created_at', [$param['created_at'][0], $param['created_at'][1]]);
            } elseif (Arr::get($param, 'created_at.0')) {
                $query->where('created_at', '>=', $param['created_at'][0]);
            } elseif (Arr::get($param, 'created_at.1')) {
                $query->where('created_at', '<=', $param['created_at'][1]);
            }

            if (Arr::get($param, 'status')) {
                $query->where('status', $param['status']);
            }
            if (Arr::get($param, 'is_buy')) {
                $query->where('is_buy', $param['is_buy']);
            }
            if (Arr::get($param, 'id')) {
                $query->where('id', $param['id']);
            }

        })->whereExists(function ($query) use ($param) {
            $query->from('wa_users')->whereRaw('wa_users.id=wa_user_social_cark.user_id');
            if (Arr::get($param, 'user_name')) {
                $query->where('name', 'like', '%' . $param['user_name'] . '%');
            }
            if (Arr::get($param, 'user_mobile')) {
                $query->where('mobile', 'like', '%' . $param['user_mobile'] . '%');
            }
        })
            ->with('userData:id,name,mobile');
        if (Arr::get($param, 'field')) {
            $order = 'asc';
            if (Arr::get($param, 'order')) {
                $order = 'desc';
            }
            $data = $data->orderBy($param['field'], $order);
        } else {
            $data = $data->orderBy('updated_at', 'desc');
        }
        $data = $data->paginate(Arr::get($param, 'limit', 10))->toArray();
        $arr  = [];
        foreach ($data['data'] as $k => $v) {

            $arr[] = [
                'id'          => $v['id'],
                'user_name'   => $v['user_data']['name'],
                'user_mobile' => $v['user_data']['mobile'],
                'name'        => $v['name'],
                'number'      => $v['number'],
                'mobile'      => $v['mobile'],
                'card_num'    => $v['card_num'],
                'status'      => $v['status'],
                'created_at'  => $v['created_at'],
                'updated_at'  => $v['updated_at'],
                'address'     => $v['address'],
                'limit'       => $v['limit'],
                'use_limit'   => $v['use_limit'],
                'create_date' => $v['create_date'],
                'flag'        => $v['flag'],
                'validity'    => $v['validity'],
                'safety_code' => $v['safety_code'],
                'odd_numbers' => $v['odd_numbers'],
                'ranking'     => $v['ranking'],
            ];
        }
        return json(['code' => 0, 'data' => $arr, 'msg' => 'ok', 'count' => $data['total']]);
    }

    /** 批量通过
     * @param Request $request
     * @return Response
     */
    public function pass(Request $request): Response
    {
        try {
            $param = $request->all();
            Validator::input($param, [
                'id' => Validator::notEmpty()->ArrayType()->setName('标识'),
            ]);
            $applyRecordModel = UserCark::query();
            foreach ($param['id'] as $k => $v) {
                Db::beginTransaction();
                try {
                    $system = Db::table('wa_system')->first();
                    $has    = (clone $applyRecordModel)->where('id', $v)->lock(true)->first();
                    if (empty($has)) {
                        throw new \Exception('数据不存在!');
                    }
                    if ($has->status != 1) {
                        throw new \Exception('数据已经处理!');
                    }
                    if ($has && $has->status == 1) {

                        $result   = [
                            'cardToken'   => '4981e7b51d80078d95eb75f6a0113f8c',
                            'channel'     => '100003',
                            'coupon'      => '10035',
                            'amount'      => 10,
                            'action'      => 'applicationCard',
                            'user_number' => (string)$has->id,
                            'shopno'      => '20001032',
                            'key'         => 'A7F232D8364468ED10BC872B4E7EF4D3',
                        ];
                        $info     = openssl_encrypt(json_encode($result), 'AES-256-ECB', 'A7F232D8364468ED10BC872B4E7EF4D3', OPENSSL_RAW_DATA);
                        $info     = base64_encode($info);
                        $order_no = date('YmdHis') . mt_rand(1000, 9999);
                        $arr      = [
                            'shopno'         => '20001032',
                            'wholeRequestId' => $order_no,
                            'data'           => $info,
                        ];
                        $url      = 'https://www.supplicardes.online/api/virtual_card';
                        $data     = Http::post($url, $arr)->array();
                        Log::channel('kaicard')->info('开通虚拟卡', $data);
                        if ($data['code'] == 1000) {
                            $has->status     = 2;
                            $has->updated_at = date('Y-m-d H:i:s');
                            $has->save();
                        } else {
                            throw new \Exception('开卡失败：' . $data['msg']);
                        }


                    } else {
                        throw new \Exception('已处理请不要重复提交!');
                    }

                    Db::commit();
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    throw new \Exception($exception->getMessage());
                }
            }
        } catch (\Throwable $exception) {
            return $this->fail($exception->getMessage());
        }
        return $this->success();
    }


    /** 更新卡信息
     * @param Request $request
     * @return Response
     */
    public function release(Request $request): Response
    {
        try {
            $param = $request->all();
            Validator::input($param, [
                'id' => Validator::notEmpty()->ArrayType()->setName('标识'),
            ]);
            $applyRecordModel = UserCark::query();
            foreach ($param['id'] as $k => $v) {
                Db::beginTransaction();
                try {
                    $system = Db::table('wa_system')->first();
                    $has    = (clone $applyRecordModel)->where('id', $v)->lock(true)->first();
                    if (empty($has)) {
                        throw new \Exception('数据不存在!');
                    }
                    if ($has->status == 1) {
                        throw new \Exception('请先开卡!');
                    }
                    if ($has) {
                        $order_no = date('YmdHis') . mt_rand(1000, 9999);
                        $result   = [
                            'shopno'      => '20001032',
                            'key'         => 'A7F232D8364468ED10BC872B4E7EF4D3',
                            'action'      => 'card_list',
                            'user_number' => $has->id,
                        ];
                        $info     = openssl_encrypt(json_encode($result), 'AES-256-ECB', 'A7F232D8364468ED10BC872B4E7EF4D3', OPENSSL_RAW_DATA);
                        $infodata = base64_encode($info);
                        $arr      = [
                            'shopno'         => '20001032',
                            'wholeRequestId' => $order_no,
                            'data'           => $infodata,
                        ];
                        $url      = 'https://www.supplicardes.online/api/virtual_card';
                        $data     = Http::post($url, $arr)->array();
                        Log::channel('kaicard')->info('更新虚拟卡', $data);
                        if ($data['code'] == 1000) {
                            foreach ($data['data'] as $jj => $ll) {
                                if ($ll['user_number'] == $v) {
                                    $has->card_num    = $ll['cardno'];
                                    $has->safety_code = $ll['CVV'];
                                    $has->validity    = $ll['validity'];
                                    $has->limit       = $ll['limit'];
                                    $has->use_limit   = $ll['use_limit'];
                                    $has->flag        = $ll['flag'];
                                    $has->create_date = $ll['create_date'];
                                    $has->taskId      = $ll['taskId'];
                                    $has->user_number = $ll['user_number'];
                                    $has->status      = 3;
                                    $has->updated_at  = date('Y-m-d H:i:s');
                                    $has->save();
                                }

                            }

                        } else {
                            throw new \Exception('更新卡失败：' . $data['msg']);
                        }


                    } else {
                        throw new \Exception('已处理请不要重复提交!');
                    }

                    Db::commit();
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    throw new \Exception($exception->getMessage());
                }
            }
        } catch (\Throwable $exception) {
            return $this->fail($exception->getMessage());
        }
        return $this->success();
    }

    /** 充值
     * @param Request $request
     * @return Response
     */
    public function topup(Request $request): Response
    {
        try {
            $param = $request->all();
            Validator::input($param, [
                'id'            => Validator::notEmpty()->ArrayType()->setName('标识'),
                'operate_money' => Validator::notEmpty()->setName('充值金额'),
            ]);
            $applyRecordModel = UserCark::query();
            foreach ($param['id'] as $k => $v) {
                Db::beginTransaction();
                try {
                    $has = (clone $applyRecordModel)->where('id', $v)->lock(true)->first();
                    if (empty($has)) {
                        throw new \Exception('数据不存在!');
                    }
                    if ($has->status != 3) {
                        throw new \Exception('卡未完成，不能充值!');
                    }
                    if ($has->status == 4) {
                        throw new \Exception('已充值，请更新查看!');
                    }
                    if ($has) {
                        $order_no = date('YmdHis') . mt_rand(1000, 9999);
                        $result   = [
                            'cardToken'   => $has->taskId,
                            'amount'      => (int)$param['operate_money'],
                            'cardno'      => $has->card_num,
                            'shopno'      => '20001032',
                            'key'         => 'A7F232D8364468ED10BC872B4E7EF4D3',
                            'action'      => 'rech_card',
                            'user_number' => $has->id,
                        ];
                        $info     = openssl_encrypt(json_encode($result), 'AES-256-ECB', 'A7F232D8364468ED10BC872B4E7EF4D3', OPENSSL_RAW_DATA);
                        $infodata = base64_encode($info);
                        $arr      = [
                            'shopno'         => '20001032',
                            'wholeRequestId' => $order_no,
                            'data'           => $infodata,
                        ];
                        $url      = 'https://www.supplicardes.online/api/virtual_card';
                        $data     = Http::post($url, $arr)->array();
                        Log::channel('kaicard')->info('充值请求', $arr);
                        Log::channel('kaicard')->info('充值返回', $data);
                        if ($data['code'] == 1000) {

                            (clone $applyRecordModel)->where('id', $v)->update(['status' => 4]);

                            $topup = [
                                'login_admin_id'      => admin_id(),
                                'user_id'             => $has->user_id,
                                'user_social_cark_id' => $has->id,
                                'money'               => $param['operate_money'],
                                'ip'                  => $request->getRealIp($safe_mode = true),
                                'updated_at'          => date('Y-m-d H:i:s', time()),
                                'created_at'          => date('Y-m-d H:i:s', time()),
                            ];
                            Db::table('wa_user_topup_log')->insert($topup);


                        } else {
                            throw new \Exception('充值失败：' . $data['msg']);
                        }


                    } else {
                        throw new \Exception('数据错误，不存在卡!');
                    }

                    Db::commit();
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    throw new \Exception($exception->getMessage());
                }
            }
        } catch (\Throwable $exception) {
            return $this->fail($exception->getMessage());
        }
        return $this->success();
    }


    /** 批量通过
     * @param Request $request
     * @return Response
     */
    public function again(Request $request): Response
    {
        try {
            $param = $request->all();
            Validator::input($param, [
                'id' => Validator::notEmpty()->ArrayType()->setName('标识'),
            ]);
            $applyRecordModel = UserCark::query();
            foreach ($param['id'] as $k => $v) {
                Db::beginTransaction();
                try {
                    $has = (clone $applyRecordModel)->where('id', $v)->lock(true)->first();
                    if (empty($has)) {
                        throw new \Exception('数据不存在!');
                    }

                    if ($has) {
                        $result   = [
                            'cardToken'   => '4981e7b51d80078d95eb75f6a0113f8c',
                            'channel'     => '100003',
                            'coupon'      => '10035',
                            'amount'      => 10,
                            'action'      => 'applicationCard',
                            'user_number' => (string)$has->id,
                            'shopno'      => '20001032',
                            'key'         => 'A7F232D8364468ED10BC872B4E7EF4D3',
                        ];
                        $info     = openssl_encrypt(json_encode($result), 'AES-256-ECB', 'A7F232D8364468ED10BC872B4E7EF4D3', OPENSSL_RAW_DATA);
                        $info     = base64_encode($info);
                        $order_no = date('YmdHis') . mt_rand(1000, 9999);
                        $arr      = [
                            'shopno'         => '20001032',
                            'wholeRequestId' => $order_no,
                            'data'           => $info,
                        ];
                        $url      = 'https://www.supplicardes.online/api/virtual_card';
                        $data     = Http::post($url, $arr)->array();
                        Log::channel('kaicard')->info('开通虚拟卡', $data);
                        if ($data['code'] == 1000) {
                            $has->status     = 2;
                            $has->updated_at = date('Y-m-d H:i:s');
                            $has->save();
                        } else {
                            throw new \Exception('开卡失败：' . $data['msg']);
                        }


                    } else {
                        throw new \Exception('已处理请不要重复提交!');
                    }

                    Db::commit();
                } catch (\Throwable $exception) {
                    Db::rollBack();
                    throw new \Exception($exception->getMessage());
                }
            }
        } catch (\Throwable $exception) {
            return $this->fail($exception->getMessage());
        }
        return $this->success();
    }


    /** 消费记录
     * @param Request $request
     * @return Response
     */
    public function record(Request $request): Response
    {
        $param = $request->all();

        if ($request->isAjax()) {
            $param = $request->all();

            $has = UserCark::query()->where('id', $param['user_id'])->first();

            $result   = [

                'shopno' => '20001032',
                'key'    => 'A7F232D8364468ED10BC872B4E7EF4D3',
                'action' => 'bill_list',
                'cardno' => $has->card_num,
                'p'      => $param['page']
            ];
            $info     = openssl_encrypt(json_encode($result), 'AES-256-ECB', 'A7F232D8364468ED10BC872B4E7EF4D3', OPENSSL_RAW_DATA);
            $info     = base64_encode($info);
            $order_no = date('YmdHis') . mt_rand(1000, 9999);
            $arr      = [
                'shopno'         => '20001032',
                'wholeRequestId' => $order_no,
                'data'           => $info,
            ];
            $url      = 'https://www.supplicardes.online/api/virtual_card';
            $data     = Http::post($url, $arr)->array();
            if ($data['code'] != 1000) {
                throw new \Exception('获取失败：' . $data['msg']);
            }


            return json(['code' => 0, 'data' => $data['data'], 'msg' => 'ok', 'count' => $data['arr']['totalPages']]);
        }
        return view('usercark/record', $param);
    }

}
