<?php

namespace app\admin\controller\posts;

use app\common\controller\Backend;

use think\Hook;
use seven\Seven;

/**
 * 单页管理
 *
 * @icon fa fa-bookmark-o
 */
class Page extends Backend
{
    
    /**
     * Page模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Page');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->with('sites')
                ->field('keywords,description,content', true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('show_sitename', $this->auth->isSuperAdmin());
        return $this->view->fetch();
    }


    /**
     * 添加/修改 通用参数
     */
    private function initForm()
    {
        $first_siteid=null;
        if ($this->auth->isSuperAdmin()){
            $sitelist = \app\admin\model\Sites::all();;
            $this->view->assign('siteList', $sitelist);
            $first_siteid=$sitelist?$sitelist[0]['id']:$first_siteid;
        }
        else {
            $this->view->assign('siteList', null);
            $first_siteid = \think\Session::get('user_site_id');
        }
        $this->view->assign("flagList", ['hot' => __('Hot'),  'recommend' => __('Recommend')] );

        $ml = Seven::build_langs('row[lang]',null,['siteid'=>$first_siteid]);

        $this->view->assign('multilanguage',$ml);
    }

    /**
     * Add
     */
    public function add()
    {
        $this->initForm();
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                foreach ($params as $k => &$v)
                {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->initForm();
        $this->view->assign('multilanguage', Seven::build_langs('row[lang]',$row['lang'],['siteid'=>$row->site_id]));
        return $this->view->fetch();
    }

}
