<?php

namespace app\admin\controller\posts;

use app\common\controller\Backend;
use fast\Tree;
use think\Hook;
use seven\Seven;
use think\Session;

/**
 * 栏目管理
 *
 * @icon fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类
 */
class Channel extends Backend
{

    protected $model = null;
    protected $noNeedRight = ['check_element_available','getlist'];


    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);
        $this->model = model('Channel');

    }

    private function initForm($siteId=null)
    {
        $first_siteid=null;
        if ($this->auth->isSuperAdmin()){
            $sitelist = \app\admin\model\Sites::all();;
            $this->view->assign('siteList', $sitelist);
            if ($sitelist && $this->request->action()=='add') {
                $first_siteid = $sitelist[0]['id'] ;
            }
        }
        else {
            $this->view->assign('siteList', null);
            $first_siteid = Session::get('user_site_id');
        }
        if (!is_null($siteId)) $first_siteid=$siteId;
        $where = ['site_id'=>$first_siteid];

        $tree = Tree::instance();
        $tree->init($this->model->order('weigh desc,id desc')->where($where)->with('Sites,archives')->select(), 'pid');
        $channellist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $channeldata = [0 => ['site_id'=>0, 'name' => __('None')]];
        foreach ($channellist as $k => $v)
        {
            //添加&编辑页面， 排除非首选网站的栏目
            if(!is_null($first_siteid) && $v['site_id']!=$first_siteid) {
                //do nothing
            }else {
                $channeldata[$v['id']] = $v;
            }
        }
        $this->view->assign("parentList", $channeldata);

        /*
        $tpldir=APP_PATH.'index/view/channel';
        $templatelist=scandir($tpldir);
        foreach($templatelist as $k=>$file){
            if($file=='.' || $file=='..'){
                unset($templatelist[$k]);
            }else {
                $templatelist[$k] = str_replace('.html', '', $file);
            }
        }
        $this->view->assign('templatelist', $templatelist);
        */

        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("modelList", model('PostsModelx')->all());

        $ml = Seven::build_langs('row[lang]',null,['siteid'=>$first_siteid]);
        $this->view->assign('multilanguage',$ml);

    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $search = $this->request->request("search");
            //构造父类select列表选项数据

            list($where, $sort, $order, $offset, $limit) = $this->buildparams(false, true);

            $tree = Tree::instance();
            $tree->init($this->model->order('weigh desc,id desc')->where($where)->with('Sites,archives')->select(), 'pid');

            $channellist = $tree->getTreeList($tree->getTreeArray(0), 'name');

            $list = [];
            if ($search)
            {
                foreach ($channellist as $k => $v)
                {
                    if (stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false)
                    {
                        $list[] = $v;
                    }
                }
            }
            else
            {
                $list = $channellist;
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        if ($this->auth->isSuperAdmin()){
            $sitelist = \app\admin\model\Sites::all();;
            $this->view->assign('siteList', $sitelist);
        }
        $this->assignconfig('show_sitename', $this->auth->isSuperAdmin());
        return $this->view->fetch();
    }

    /**
     * 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->initForm($row->site_id);
        $this->view->assign('multilanguage', Seven::build_langs('row[lang]',$row['lang'],['siteid'=>$row->site_id]));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 返回栏目列表,供文章列表搜索框Ajax调用
     */
    public function getlist()
    {
        if($this->request->isAjax()){
            $tree = Tree::instance();
            $channellist=$tree->init($this->model->order('weigh desc,id desc')->with('Sites,archives')->select(), 'pid');
            $channellist = $tree->getTreeList($tree->getTreeArray(0), 'name');
            foreach ($channellist as $k => $v){
                $list[$v['id']]=$v['name'];
            }
            return json($list);
        }
    }

    /**
     * 校验字段的值的唯一性
     */
    public function check_element_available()
    {
        $field = $this->request->post('name');
        $value = $this->request->post('value');
        if($field && $value) {
            $params = [preg_replace('/row\[(\w+)\]/i', '$1', $field) => $value];
            $result = $this->model->get($params);
            if ($result != false) {
                $this->error(__('Name already exist'));
            } else {
                $this->success();
            }
        }else{
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }
}
