<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\api\service\User as UserService;
use think\response\Json;
use app\api\service\Upload as UploadService;
use app\common\enum\file\FileType as FileTypeEnum;

/**
 * 文件上传管理
 * Class Upload
 * @package app\api\controller
 */
class Upload extends Controller
{
    /**
     * 图片上传接口
     * @param bool $checkLogin 是否验证登录
     * @return Json
     * @throws \cores\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function image(bool $checkLogin = true): Json
    {
        // 执行文件上传
        $service = new UploadService();
        if (!$service->upload(FileTypeEnum::IMAGE, $checkLogin)) {
            return $this->renderError('文件上传失败:' . $service->getError());
        }
        // 图片上传成功
        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
    }


    public function wxUpload(): Json {
        $checkLogin = $this->request->param('checkLogin');
        // 执行文件上传
        $service = new UploadService();
        if (!$service->upload(FileTypeEnum::IMAGE, boolval($checkLogin))) {
            return $this->renderError('文件上传失败:' . $service->getError());
        }
        // 图片上传成功
        return $this->renderSuccess(['fileInfo' => $service->getFileInfo()], '文件上传成功');
    }

    /**
     * 微信头像上传
     */
    public function wxHeadImgUpload(): Json
    {
        $headImag = $this->request->param('headImg');
        $checkLogin = $this->request->param('checkLogin');
        $user_id = UserService::getCurrentLoginUserId();

        // 创建一个新的 cURL 会话
        $ch = curl_init();
        // 设置 URL 地址
        curl_setopt($ch, CURLOPT_URL, 'https://www.royaum.com.cn/index.php?s=/api/upload/wxUpload'); //目标服务器接收文件的地址

        $fileName = $this->getFileName($headImag, $user_id);
        // 打开文件流
        $fileStream = fopen($fileName, 'r');
        // 构造请求头部信息
        $headers = array(
            "Content-Type: multipart/form-data",
            "storeId: ".$this->storeId,
            "Access-Token: ".$this->request->header("Access-Token"),
            "platform: ".$this->request->header("platform")
        );
        //请求数据
        $post_data = [
            'checkLogin' => $checkLogin,
            'file' =>  new \CURLFile($fileName)
        ];
        // 设置其他选项
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_INFILE, $fileStream);
        curl_setopt($ch, CURLOPT_INFILESIZE, filesize($fileName));

        // 执行请求并获取结果
        $result = curl_exec($ch);

        // 关闭文件流和 cURL 会话
        fclose($fileStream);
        curl_close($ch);

        $result = json_decode($result, true);
        return $this->renderSuccess($result['data'],$result['message']);
    }

    public function getFileName($imageUrl,$user_id) {
        $imageFile = $this->setFileData($imageUrl);
        $savePath = "./uploads/wxImage/".date("Y-m-d").'/';
        $fileName = $user_id.'.jpg';
        if(!file_exists($savePath)) {
            mkdir($savePath, 0777,true);
        }
        file_put_contents($savePath.$fileName, $imageFile);
        return $savePath.$fileName;
    }

    public function setFileData($image_url) {
        return file_get_contents($image_url);
    }
}