<?php

namespace app\controller;


use app\business\GoodsBusiness;
use app\business\LoginBusiness;
use app\business\PayorderBusiness;
use app\business\WithdrawBusiness;
use Illuminate\Support\Arr;
use Respect\Validation\Validator;
use support\Db;
use support\Redis;
use support\Request;
use hg\apidoc\annotation as Apidoc;
use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;

//    #[Apidoc\Title("绑定")]
#[Apidoc\Group("Binding")]
#[Apidoc\Sort(5)]
class BindingController
{

    #[Apidoc\Title("绑定支付宝，绑定微信，绑定数字人民币 扫码支付")]
    #[Apidoc\Url("api/binding.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
    #[Apidoc\Param("account_number", type: "int", require: true, desc: "账号", mock: 10)]
    #[Apidoc\Param("name", type: "int", require: true, desc: "姓名", mock: 10)]
    #[Apidoc\Param("baseimg", type: "int", require: true, desc: "图片base", mock: 10)]
    #[Apidoc\Param("type", type: "int", require: true, desc: "类型：1=绑定支付宝，2=绑定微信 ", mock: 2)]
    public function addbinding(Request $request)
    {
        $param              = $request->all();
        $param['user_data'] = $request->user_data;
        Db::beginTransaction();
        try {
            Validator::input($param, [
                'account_number' => Validator::notEmpty()->setName('账号'),
                'name'           => Validator::notEmpty()->setName('姓名'),
                'type'           => Validator::notEmpty()->setName('类型'),
            ]);

            if (Arr::get($param, 'baseimg')) {
                $base64Image_one = $param['baseimg'];                                                                                           // 获取Base64字符串
                $imageData       = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64Image_one));                             // 移除数据URL的前缀并解码
                $imageName       = $request->user_data['id'] . time() . '.png';                                                             // 生成一个唯一的文件名

                $data              = '/upload/img/' . date('Ymd');
                $relative_dir      = ltrim($data, '\\/');
                $admin_public_path = rtrim(config('app.public_path', ''), '\\/');
                $base_dir          = $admin_public_path ? $admin_public_path . DIRECTORY_SEPARATOR : base_path() . '/plugin/admin/public/';
                $full_dir          = $base_dir . $relative_dir;
                if (!is_dir($full_dir)) {
                    mkdir($full_dir, 0777, true);
                }
                $imagePath_one = '/upload/img/' . date('Ymd') . '/' . $imageName; // 指定保存路径和文件名

                // 保存图片到服务器
                file_put_contents($base_dir . $imagePath_one, $imageData);
            } else {
                $imagePath_one = '';
            }
            $data    = [
                'user_id'        => $param['user_data']['id'],
                'account_number' => $param['account_number'],
                'name'           => $param['name'],
                'type'           => $param['type'],
                'created_at'     => date('Y-m-d H:i:s'),
                'updated_at'     => date('Y-m-d H:i:s'),
            ];
            $binding = Db::table('wa_binding')
                ->where('user_id', $param['user_data']['id'])
                ->where('type', $param['type'])->first();
            if (empty($binding)) {
                $data['img'] = $imagePath_one;
                Db::table('wa_binding')->insert($data);
            } else {
                if (empty($param['baseimg'])) {
                    $data['img'] = $binding->img;
                } else {
                    $data['img'] = $imagePath_one;
                }
                Db::table('wa_binding')->where('id', $binding->id)->update($data);
            }

        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success();

    }

    #[Apidoc\Title("绑定记录详情")]
    #[Apidoc\Url("api/binding/binding_details.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
    #[Apidoc\Param("type", type: "int", require: true, desc: "类型：1=绑定支付宝，2=绑定微信 ", mock: 2)]
    #[Apidoc\Returned(name: "account_number", type: "string", require: true, desc: '账号', default: '0.00')]
    #[Apidoc\Returned(name: "name", type: "string", require: true, desc: '姓名', default: '0.00')]
    #[Apidoc\Returned(name: "img", type: "string", require: true, desc: '图片', default: '0.00')]
    public function binding_details(Request $request)
    {
        $param              = $request->param_data;
        $param['user_data'] = $request->user_data;
        Db::beginTransaction();
        try {
            Validator::input($param, [
                'type' => Validator::notEmpty()->setName('类型'),
            ]);

            $bindingdata = Db::table('wa_binding')
                ->where('user_id', $param['user_data']['id'])
                ->where('type', $param['type'])
                ->first();
            if (empty($bindingdata)) {
                $data = [
                    'id'             => '',
                    'account_number' => '',
                    'name'           => '',
                    'img'            => '',
                    'type'           => '',
                ];
            } else {
                $data = [
                    'id'             => $bindingdata->id,
                    'account_number' => $bindingdata->account_number,
                    'name'           => $bindingdata->name,
                    'img'            => imageToBase64($bindingdata->img),
                    'type'           => $bindingdata->type,
                ];
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success($data);

    }


}
