<?php

namespace App\Distributor\Controllers;

use App\Distributor\Repositories\DistAdminDistributor;
use App\Http\Controllers\Controller;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Dcat\Admin\Models\Setting as SettingModel;
use Dcat\Admin\Traits\HasUploadedFile;

class SettingsController extends Controller
{
    use HasUploadedFile;

    public function index(Content $content)
    {
        $formTab = isset($_GET['tab']) ? $_GET['tab'] : 0;
        if ($formTab == 0) {
            return $content->title(admin_trans( 'admin.settings'))
                ->body($this->form1());
        } else {
            return $content->title(admin_trans( 'admin.settings'))
                ->body($this->form2());
        }

    }

    /*
     * 域名配置
     */
    protected function form1()
    {
        exit;
        $distInfo = DistAdminDistributor::getInfo();
        $form = new \Dcat\Admin\Form();
        $form->title(admin_trans_label('domain'));
        //提交URL
        $form->action('/dist-settings');
        $form->hidden('act')->value('domain');
        //查分销商信息
        $secondaryDomain = $distInfo->secondary_domain ? $distInfo->secondary_domain : '';
        $customDomain = $distInfo->custom_domain ? $distInfo->custom_domain : '';
        $form->radio('domain_type')
            ->when(0, function (\Dcat\Admin\Form $form) use ($secondaryDomain) {
                $form->text('secondary_domain')->width(4,2)->value($secondaryDomain)->readOnly();
            })
            ->when(1, function (\Dcat\Admin\Form $form) use ($customDomain){
                $form->text('custom_domain')->width(4,2)->value($customDomain)->help('Please enter the domain name, such as www.example.com,and bind the domain name to the IP address '.env('DIST_SITE_IP'));
            })
            ->options([0=>admin_trans_field('secondary_domain'),1=>admin_trans_field('custom_domain')])
            ->value($distInfo->domain_type)
            ->required();
        //按钮
        $form->disableListButton();
        $form->disableViewCheck();
        $form->disableEditingCheck();
        $form->disableCreatingCheck();
        return $form;
    }

    /*
     * 站点配置
     */
    protected function form2()
    {
        $distInfo = DistAdminDistributor::getInfo();
        $form = new \Dcat\Admin\Form();
        $form->title(admin_trans_label('site'));
        //提交URL
        $form->action('/dist-settings');
        //字段
        $form->hidden('act')->value('site');

        $form->column(6, function (\Dcat\Admin\Form $form) use ($distInfo) {
            $form->text('site_name')->value($distInfo->site_name)->required();
            $form->text('seo_title')->value($distInfo->seo_title)->required();
            $form->text('seo_keywords')->value($distInfo->seo_keywords);
            $form->textarea('seo_description')->value($distInfo->seo_description);
            $form->image("logo")
                //->aspectRatio(130/50)// 设置裁剪框比例
                ->retainable()//禁止删OSS图
                ->autoUpload()
                ->uniqueName()
                ->accept(config('distributor.upload.oss_image.accept'))
                ->maxSize(config('distributor.upload.oss_image.max_size'))
                ->dir(config("distributor.upload.directory.image").'/logo')
                ->url('/dist-settings/upload')
                ->default($distInfo->logo)->width(4,2);


        });

        $form->column(6, function (\Dcat\Admin\Form $form) use ($distInfo) {
            $form->text('company_name')->value($distInfo->company_name);
            $form->text('company_address')->value($distInfo->company_address);
            $form->text('service_hotline')->value($distInfo->service_hotline);
            $form->text('dist_email',admin_trans_label('email'))->value($distInfo->dist_email);
            $form->text('whats_app')->value($distInfo->whats_app);
            $form->text('facebook')->value($distInfo->facebook);
            $form->text('instagram')->value($distInfo->instagram);
            $form->text('youtube')->value($distInfo->youtube);
            $form->text('linkedin')->value($distInfo->linkedin);
            $form->text('tiktok')->value($distInfo->tiktok);
            $form->text('copy_right')->value($distInfo->copy_right);
        });
        $form->disableListButton();
        $form->disableViewCheck();
        $form->disableEditingCheck();
        $form->disableCreatingCheck();
        return $form;
    }


    /*
     * 保存配置
     */
    public function store(Request $request)  {
        $form = new Form();
        $act = $request->input('act');
        if ($act == 'domain') {
            $domainType = $request->input('domain_type');
            $customDomain = $request->input('custom_domain');
            if (!in_array($domainType, [0,1])) {
                return $form->response()->error('Invalid argument');
            }
            $customDomain = $this->removeHttpAndPort($customDomain);
            DistAdminDistributor::updateDomain($domainType,$customDomain);
        } else {
            //站点配置
            DistAdminDistributor::updateInfo($request->all());
        }
        return $form->response()->success(admin_trans_label('update_success'));
    }

    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("logo");
        $dir = config("distributor.upload.directory.image").'/logo';
        $newName = $column.'.'.$file->getClientOriginalExtension();
        $result = $disk->putFileAs($dir, $file, $newName);
        $path = "{$dir}/$newName";
        return $result
            ? $this->responseUploaded($path, $disk->url($path))
            : $this->responseErrorMessage(admin_trans_label('upload_failed'));
    }

    private function removeHttpAndPort($url) {
        // 使用正则表达式去除 http:// 和 https://
        $url = preg_replace('#^https?://#', '', $url);
        // 使用正则表达式去除端口号
        $url = preg_replace('#:\d+/#', '/', $url);
        $url = preg_replace('#:\d+$#', '', $url);
        $url = trim($url);
        $url = trim($url,'/');
        $url = trim($url,'\\');
        return $url;
    }



}
