<?php

namespace App\Http\Controllers\Admin;


use Edwin404\Admin\Cms\Field\FieldImage;
use Edwin404\Admin\Cms\Field\FieldRichtext;
use Edwin404\Admin\Cms\Field\FieldSelect;
use Edwin404\Admin\Cms\Field\FieldText;
use Edwin404\Admin\Cms\Field\FieldTextarea;
use Edwin404\Admin\Cms\Handle\BasicCms;
use Edwin404\Admin\Http\Controllers\Support\AdminCheckController;
use Edwin404\Base\Support\InputPackage;
use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\RequestHelper;
use Edwin404\Base\Support\Response;
use Edwin404\Demo\Helpers\DemoHelper;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;

class SuperPageController extends AdminCheckController
{
    private $cmsConfigBasic = [
        'model' => 'super_page',
        'pageTitle' => '超级页面',
        'group' => 'data',
        'canAdd' => true,
        'canEdit' => true,
        'canDelete' => true,
        'fields' => [
            'url' => ['type' => FieldText::class, 'title' => '路径', 'list' => true, 'edit' => true, 'add' => true, 'desc' => '必须以/开头，只能由数字、小写字母下划线组成'],
            'title' => ['type' => FieldText::class, 'title' => '标题', 'list' => true, 'edit' => true, 'add' => true,],
            'keywords' => ['type' => FieldText::class, 'title' => '关键词', 'list' => true, 'edit' => true, 'add' => true,],
            'description' => ['type' => FieldText::class, 'title' => '描述', 'list' => true, 'edit' => true, 'add' => true,],
        ]
    ];

    public function dataPostDelete(&$data)
    {
        ModelHelper::delete('super_page_item', ['pageId' => $data['id']]);
    }

    public function dataProcessView(&$item, &$record)
    {
        if ($record['url'] != '/') {
            $item['url'] = '<a href="/p' . $record['url'] . '" target="_blank">/p' . $record['url'] . '</a>';
        }
    }

    public function dataBeforeAddCheck(&$data)
    {
        if (!Str::startsWith($data['url'], '/')) {
            return Response::generate(-1, 'URL必须以/开头');
        }
        if (!preg_match('/^\\/[a-zA-Z0-9_]+$/', $data['url'])) {
            return Response::generate(-1, 'URL只能由数字、小写字母下划线组成');
        }
        if (ModelHelper::exists('super_page', ['url' => $data['url']])) {
            return Response::generate(-1, 'URL重复');
        }
        return Response::generate(0, 'ok');
    }

    public function dataBeforeEditCheck(&$data)
    {
        if (!Str::startsWith($data['url'], '/')) {
            return Response::generate(-1, 'URL必须以/开头');
        }
        if (!preg_match('/^\\/[a-zA-Z0-9_]+$/', $data['url'])) {
            return Response::generate(-1, 'URL只能由数字、小写字母下划线组成');
        }
        $founds = ModelHelper::find('super_page', ['url' => $data['url']]);
        if (count($founds) > 1) {
            return Response::generate(-1, 'URL重复');
        }
        if (count($founds) == 1) {
            if ($founds[0]['id'] != $data['id']) {
                return Response::generate(-1, 'URL重复');
            }
        }
        return Response::generate(0, 'ok');
    }

    public function dataList(BasicCms $basicCms)
    {
        return $basicCms->executeList($this, $this->cmsConfigBasic);;
    }

    public function dataDelete(BasicCms $basicCms)
    {
        return $basicCms->executeDelete($this, $this->cmsConfigBasic);
    }

    public function dataEdit(BasicCms $basicCms)
    {
        return $basicCms->executeEdit($this, $this->cmsConfigBasic);
    }

    public function dataAdd(BasicCms $basicCms)
    {
        return $basicCms->executeAdd($this, $this->cmsConfigBasic);
    }

    public function manage($id)
    {
        $superPage = ModelHelper::load('super_page', ['id' => $id]);
        $superPageItems = ModelHelper::find('super_page_item', ['pageId' => $superPage['id']], ['sort', 'asc']);
        ModelHelper::decodeRecordsJson($superPageItems, ['content']);
        return view('admin.superPage.manage', [
            'superPage' => $superPage,
            'superPageItems' => $superPageItems,
        ]);
    }

    public function manageEdit($id, $itemType, $itemId = 0)
    {
        $superPage = ModelHelper::load('super_page', ['id' => $id]);
        $superPageItem = null;
        $itemContent = [];
        $itemSort = 999;
        if ($itemId) {
            $superPageItem = ModelHelper::load('super_page_item', ['id' => $itemId]);
            $itemContent = ($superPageItem ? @json_decode($superPageItem['content'], true) : []);
            if (empty($itemContent)) {
                $itemContent = [];
            }
            $itemSort = ($superPageItem ? $superPageItem['sort'] : 999);
        }
        if (RequestHelper::isPost()) {
            if (DemoHelper::shouldDenyAdminDemo()) {
                return Response::send(-1, '演示账号禁止修改信息');
            }
            $input = InputPackage::buildFromInput();
            $update = [];
            $update['content'] = $input->getJson('content');
            $update['content'] = json_encode($update['content']);
            $update['sort'] = $input->getInteger('sort');
            if ($superPageItem) {
                ModelHelper::updateRaw('super_page_item', ['id' => $itemId], $update);
            } else {
                $update['pageId'] = $id;
                $update['type'] = $itemType;
                ModelHelper::add('super_page_item', $update);
            }
            return Response::send(0, '保存成功', null, action('\App\Http\Controllers\Admin\SuperPageController@manage', ['id' => $id]));
        }
        return view('admin.superPage.manageEdit', [
            'superPage' => $superPage,
            'itemType' => $itemType,
            'itemContent' => $itemContent,
            'itemSort' => $itemSort,
            'superPageItem' => $superPageItem,
        ]);
    }

    private function _manageSort($direction, $id, $itemId)
    {
        if (DemoHelper::shouldDenyAdminDemo()) {
            return Response::send(-1, '演示账号禁止修改信息');
        }
        $allM = ModelHelper::model('super_page_item')->where(['pageId' => $id])->orderBy('sort', 'asc')->get()->toArray();
        $oldIndex = null;
        foreach ($allM as $index => &$m) {
            ModelHelper::updateRaw('super_page_item', ['id' => $m['id']], ['sort' => $index]);
            $m['sort'] = $index;
            if ($m['id'] == $itemId) {
                $oldIndex = $index;
            }
        }
        if (null !== $oldIndex) {
            switch ($direction) {
                case 'up':
                    if ($oldIndex > 0) {
                        $old = $allM[$oldIndex];
                        $new = $allM[$oldIndex - 1];
                        ModelHelper::updateRaw('super_page_item', ['id' => $old['id']], ['sort' => $new['sort']]);
                        ModelHelper::updateRaw('super_page_item', ['id' => $new['id']], ['sort' => $old['sort']]);
                    }
                    break;
                case 'down':
                    if ($oldIndex < count($allM) - 1) {
                        $old = $allM[$oldIndex];
                        $new = $allM[$oldIndex + 1];
                        ModelHelper::updateRaw('super_page_item', ['id' => $old['id']], ['sort' => $new['sort']]);
                        ModelHelper::updateRaw('super_page_item', ['id' => $new['id']], ['sort' => $old['sort']]);
                    }
                    break;
            }

        }
        return Response::send(0, null, null, action('\App\Http\Controllers\Admin\SuperPageController@manage', ['id' => $id]));
    }

    public function manageUp($id, $itemId)
    {
        return $this->_manageSort('up', $id, $itemId);
    }

    public function manageDown($id, $itemId)
    {
        return $this->_manageSort('down', $id, $itemId);
    }

    public function manageDelete($id, $itemId)
    {
        ModelHelper::delete('super_page_item', ['id' => $itemId, 'pageId' => $id]);
        return Response::send(0, null, null, action('\App\Http\Controllers\Admin\SuperPageController@manage', ['id' => $id]));
    }

}
