<?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("Stream")]
#[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("mobile", type: "int", require: true, desc: "手机号", mock: 10)]
    #[Apidoc\Param("type", type: "int", require: true, desc: "类型：1=支付宝，2=微信 ", mock: 2)]
    #[Apidoc\Param("img", type: "int", require: false, desc: "图片 ", 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('账号'),
                'type'           => Validator::notEmpty()->setName('类型'),
                'img'           => Validator::notEmpty()->setName('类型'),
            ]);
           if(!empty($param['img'])){
               $base64Image = $param['img'];                                                              // 获取Base64字符串
               $imageData   = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64Image)); // 移除数据URL的前缀并解码
               $imageName   = 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 = '/upload/img/' . date('Ymd') . '/' . $imageName; // 指定保存路径和文件名

               // 保存图片到服务器
               file_put_contents($base_dir.$imagePath, $imageData);
           }else{
               $imagePath = '';
           }

            $data = [
                'user_id'        => $param['user_data']['id'],
                'account_number' => $param['account_number'],
                'img'            => $imagePath,
                'mobile'         => $param['user_data']['mobile'],
                '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)) {
                Db::table('wa_binding')->insert($data);
            } else {
                Db::table('wa_binding')->where('id', $binding->id)->update($data);
            }

        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return adminsuccess($data,'绑定成功');

    }

    #[Apidoc\Title("绑定支付宝，绑定微信")]
    #[Apidoc\Url("api/binding/binding_new.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
    #[Apidoc\Param("wechat_binding", type: "string", require: true, desc: "微信绑定账号", mock: 10)]
    #[Apidoc\Param("alipay_binding", type: "string", require: true, desc: "支付宝绑定账号", mock: 10)]
    public function addbinding_new(Request $request)
    {
        $param              = $request->param_data;
        $param['user_data'] = $request->user_data;
        Db::beginTransaction();
        try {
            Validator::input($param, [
                'wechat_binding' => Validator::notEmpty()->setName('微信绑定账号'),
                'alipay_binding' => Validator::notEmpty()->setName('支付宝绑定账号'),
            ]);
            Db::table('wa_users')
                ->where('id', $param['user_data']['id'])
                ->update([
                    'wechat_binding' => $param['wechat_binding'],
                    'alipay_binding' => $param['alipay_binding'],
                    'updated_at'     => date('Y-m-d H:i:s')
                ]);

        } 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: "mobile", 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' => '',
                    'mobile'         => '',
                    'img'            => '',
                ];
            } else {
                $data = [
                    'id'             => $bindingdata->id,
                    'account_number' => $bindingdata->account_number,
                    'mobile'         => $bindingdata->mobile,
                    'img'            => imageToBase64($bindingdata->img),
                ];
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success($data);

    }


}
