<?php

namespace App\Api\Controllers;

use App\Http\Controllers\BaseApiController;
use App\Models\PharmacistModel;
use App\Models\PharmacyModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PharmacistController extends BaseApiController
{
    // 药师列表
    public function pharmacistList() {}
    // 药师信息

    // 药师新增

    // 药师编辑

    // 设置默认药师

    // 药师签名上传
    public function upload(Request $request)
    {

        // 验证上传的图片文件
        $validated = $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
        // 验证药师编号
        $pharmacist_id = $request->input('pharmacist_id');
        if (empty($pharmacist_id) || ! filter_var($pharmacist_id, FILTER_VALIDATE_INT)) {
            return $this->failed('ID不能为空且必须为整数');
        }
        $authInfo = auth('api')->user();
        // 获取药店信息
        $pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
        if (empty($pharmacy)) {
            return $this->failed('该药店不存在');
        }
        // 获取药师信息
        $pharmacist = PharmacistModel::where('id', $pharmacist_id)->where('pharmacy_id', $pharmacy->id)->first();
        if (empty($pharmacist)) {
            return $this->failed('该药师不存在');
        }

        // 获取上传的图片
        if ($request->hasFile('image')) {
            // 获取图片文件
            $image = $request->file('image');

            // 生成唯一文件名
            $fileName = time().'.'.$image->getClientOriginalExtension();

            // 保存图片到指定路径
            $tempPath = $image->storeAs('app/public', $fileName);

            // 读取文件内容
            $fileContent = file_get_contents(storage_path('app/public/'.$fileName));

            // 上传到腾讯云
            Storage::disk('cos')->put('pharmacist-images/'.$fileName, $fileContent);

            // 返回图片地址
            $imageUrl = Storage::disk('cos')->url('pharmacist-images/'.$fileName);

            // 签名图片地址记录到数据库
            $pharmacist->signed_pic = $imageUrl;
            if ($pharmacist->save()) {
                // 删除临时文件
                unlink(storage_path('app/public/'.$fileName));

                return $this->success(['message' => 'ok', 'url' => $imageUrl]);
            }

            return $this->failed('签名图片上传失败');
        } else {
            return $this->failed('签名图片上传失败');
        }
    }
}
