<?php

namespace App\Distributor\Controllers;

use App\Distributor\Metrics\DistMessage;
use App\Distributor\Repositories\DistAdminDistributor;
use App\Distributor\Repositories\DistAppearancePublishList;
use App\Distributor\Repositories\DistAppearanceTemplate;
use App\Distributor\Repositories\SiteMenu;
use App\Http\Controllers\Controller;
use App\Libraries\CommonHelper;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Traits\HasUploadedFile;


class VisualEditorController extends Controller
{
    use HasUploadedFile;

    /*
     * 可视化编辑器
     */
    public function index()
    {
        $mid = isset($_GET['mid'])? intval($_GET['mid']) : 0;
        $uri = isset($_GET['uri'])? $_GET['uri'] : '';
        //网站html内容
        $url = getSiteDomain();
        $html = $this->getURlHTML($url,$uri);
        //菜单
        $siteMenu = SiteMenu::showAllSelectOptions();
        foreach ($siteMenu as $key => $value) {
            if ($value['url'] == '/' && $mid == 0) {
                $mid =$value['id'];
                break;
            }
        }
        //
        $publish = admin_trans_label('publish');
        $visualEdit = admin_trans_label('visual_edit');
        return view('distributor.pages-custom.visual-editor',[
            'html'=>$html,
            'siteMenu'=>json_encode($siteMenu),
            'mid'=>$mid,
            'publish' => $publish,
            'visualEdit' => $visualEdit,
        ]);
    }

    /*
     * 保存预览修改
     */
    public function previewSave()
    {
        $html = isset($_POST['html'])? $_POST['html'] : '';
        if (empty($html) == false) {
            DistAppearanceTemplate::previewSave($html);
        }
        return response()->json(['status' => 1]);
    }

    /*
     * 发布
     */
    public function publish()
    {
        $info = DistAdminDistributor::getInfo();
        $distId = $info->id;
        $appearanceId = $info->appearance_id;
        //发布
        DistAppearancePublishList::publish($appearanceId, $distId);
        //清除缓存
        DistAdminDistributor::clearCache();
        return ['status'=>1,'message'=>admin_trans('admin.update_succeeded')];
    }

    /*
     * 上传图片
     */
    public function upload()
    {
        $disk = $this->disk('oss');
        // 判断是否是删除文件请求
        if ($this->isDeleteRequest()) {
            // 删除文件并响应
            //return $this->deleteFileAndResponse($disk);
            return $this->responseDeleted();
        }
        // 获取上传的文件
        $file = $this->file();
        // 获取上传的字段名称
        // $column = $this->uploader()->upload_column;
        $column = uniqueCode("img");
        $dir = config("distributor.upload.gjs_directory.image").'/'.date('Ymd');
        $newName = $column.'.'.$file->getClientOriginalExtension();
        $result = $disk->putFileAs($dir, $file, $newName);
        $result = CommonHelper::ossUrl($result);
        $response =  [
            'data'=>[[
                'src' => $result,
                'type'=>'image',
            ]]
        ];
        return json_encode($response);
    }

    private function getURlHTML($url,$uri)
    {
        $siteUrl = $url . $uri;
        // 检查URL中是否已经包含？
        if (strpos($siteUrl, '?') !== false) {
            // 如果包含？则添加&mtb-preview=1
            $siteUrl .= "&mtb-preview=1";
        } else {
            // 如果不包含？则添加?mtb-preview=1
            $siteUrl .= "?mtb-preview=1";
        }
        $ch = curl_init($siteUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回原生的（Raw）输出
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查（在生产环境中，应将其设置为true并指定CA证书路径）
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳过证书主机名验证

        $html = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);exit;
        }
        curl_close($ch);
        $pattern = '/<(link|script|img)[^>]*\s+(href|src)=["\'](\/[^"\']+)["\'][^>]*>/i';
        $replacement = function($matches) use ($url) {
            // $matches[3] 是匹配到的以 / 开头的路径
            return str_replace($matches[3], $url . $matches[3], $matches[0]);
        };
        $html = preg_replace_callback($pattern, $replacement, $html);

        //把form去掉
        $pattern = '/<form[^>]*>(.*?)<\/form>/is';
        $html = preg_replace($pattern, '$1', $html);

        return $html;
    }


}
