<?php

namespace plugin\admin\app\controller;

use support\Request;
use support\Response;
use plugin\admin\app\model\Hotinformation;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

use simplehtmldom\HtmlDocument;
/**
 * 文章发布 
 */
class HotinformationController extends Crud
{

    /**
     * @var Hotinformation
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Hotinformation;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('hotinformation/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('hotinformation/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        //拼接url
        $url = "http://39.98.251.138";
        $srt = "/app/admin/upload/img";
        if ($request->method() === 'POST') {
            $res_tmp = parent::update($request);
            $content = $request->post('content');

            if(strpos($content, "http") !== false){
                return $res_tmp;
            }
            $id = $request->post('id');
            $Hotinformation = $this->model::where('id', $id)->first();
            /**
             * 方法1
             */
            // $change_url = str_replace($srt, $url . $srt, $Hotinformation->content,);
            // $change_img_attr = str_replace('alt=""', 'alt="" style="width:100%"', $change_url);

            /**
             * 方法2
             */
            $html = new HtmlDocument();
            $html->load($content);
            $img = $html->find('img');
            foreach ($img as $paragraph) {
                $paragraph->src=str_replace($srt, $url . $srt, $paragraph->src);
                $newStyle = 'width: 100%;';
                // $paragraph->removeAttribute('height');
                // $paragraph->removeAttribute('width');
                $paragraph->setAttribute('style', $newStyle);  // 更新样式
            }
            $change_img_attr=$html->save();

            $Hotinformation->content = $change_img_attr;
            // $img=$html->find('img',0);
            // $Hotinformation->img= $img->src;
            $Hotinformation->save();
            return $res_tmp;
        }
        return view('hotinformation/update');
    }
}