<?php

namespace app\admin\controller\posts;

use app\common\controller\Backend;
use seven\Seven;
use think\Session;

/**
 * 站点配置
 *
 * @icon fa fa-home
 */
class Sites extends Backend
{

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


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

        $modulelist = [];
        $this->view->assign('moduleList', $modulelist);
        $this->view->assign('hostname', config('url_domain_root'));
    }

    /**
     * Index
     */
    public function index()
    {
        //从站点管理登录，进入自己的站点配置页
        if(Session::has("user_site_id")) {
            $this->redirect('posts/sites/edit?addtabs=1');
        }
        //超级管理员从总后台登录
        else {
            //设置过滤方法
            $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
                    ->alias('s')
                    ->where($where)
                    ->join('admin a','a.id=s.user_id')
                    ->field('a.username, s.*')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

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

                return json($result);
            }
            return $this->view->fetch();

        }
    }

    /**
     * Add
     */
    public function add()
    {
        if(!$this->auth->isSuperAdmin()) {
            $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;
                }

                $seo = $this->request->post("seo/a");
                $custom = $this->request->post("custom/a");
                $settings = ['seo'=>'', 'custom'=>''];
                if($seo){
                    $settings['seo'] = json_encode($seo, JSON_UNESCAPED_UNICODE);
                }
                if($custom){
                    $arr = [];
                    foreach ($custom as $k=>$v){
                        $arr[ $v['field'] ] = $v['value'];
                    }
                    $settings['custom'] = json_encode($arr, JSON_UNESCAPED_UNICODE);
                }

                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);

                    if ($result !== false)
                    {
                        $this->model->config()->save($settings);
                        $this->model->refreshRulesCache();
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('multilanguage', Seven::build_langs('row[lang]', '', ['type'=>'checkbox']));
        return $this->view->fetch();
    }

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

        $settings = ['seo' => [
            'zh-cn' => [
                'title'=>'',
                'keywords'=>'',
                'description'=>''
            ]
        ], 'custom' => [
        	'logo' => '',
        	'favicon' => '',
        ]
        ];


        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                //foreach ($params as $k => &$v)
                //{
                //    $v = is_array($v) ? implode(',', $v) : $v;
                //}
                $seo = $this->request->post("seo/a");
                $custom = $this->request->post("custom/a");
                $settings = ['seo'=>'', 'custom'=>''];
                if($seo){
                    $settings['seo'] = json_encode($seo, JSON_UNESCAPED_UNICODE);
                }
                if($custom){
                    $arr = [];
                    foreach ($custom as $k=>$v){
                        $arr[ $v['field'] ] = $v['value'];
                    }
                    $settings['custom'] = json_encode($arr, JSON_UNESCAPED_UNICODE);
                }
                
                if(!$row) $row=$this->model;

                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)
                    {
                        $row->config->save($settings);
                        $this->model->refreshRulesCache();
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['seo'] = !empty($row->config->seo) ? json_decode($row->config->seo,true) : null;
        $row['custom'] = !empty($row->config->custom) ? json_decode($row->config->custom,true) : null;
        $this->view->assign("row", $row);
        $this->view->assign('editstyle', $this->auth->isSuperAdmin()?'1':'0');
        $this->view->assign('multilanguage', Seven::build_langs('row[lang]', $row['lang'], ['type'=>'checkbox']));
        return $this->view->fetch();
    }

    public function get_site_langs()
    {
        $value = $this->request->post('lang');
        if($this->request->isAjax()){
            $result['html'] = Seven::build_langs('row[lang]',null,['siteid'=>$value]);
            $this->success('','', $result);
        }
    }

    /**
     * 返回站点的栏目列表/可选语言版本
     * 供栏目和文章的 添加&编辑 ajax调用
     */
    public function get_site_info()
    {
        if($this->request->isAjax()) {
            $site_id = $this->request->post('site_id');
            $result['lang'] = Seven::build_langs('row[lang]', null, ['siteid' => $site_id]);
            $result['list'] = [];
            $list = model('channel')->where('site_id', $site_id)->field('id,pid,type,model,name')->select();
            if ($list) {
                $tree = \fast\Tree::instance();
                $tree->init($list, 'pid');
                $result['list'] = $tree->getTreeList($tree->getTreeArray(0), 'name');
                foreach ($result['list'] as $k => &$v) {
                    $v['disabled'] = 0;
                    if ($v['type'] != 'list') {
                        $v['disabled'] = 1;
                    }
                }
            }
            $this->success('', null, $result);
        }
    }

    public function check_element_available()
    {
        $params = $this->request->post("domain");
        //保留域名
        $invail = ['www','admin'];
        if ($params)
        {
            if (in_array($params, $invail)) {
                $this->error( __('Domain already exist'));
            }
            $result = $this->model->get(['domain'=>$params]);
            if ($result!=false)
            {
                $this->error( __('Domain already exist'));
            }
            else
            {
                $this->success();
            }
        }
        else
        {
            $this->error( __('Invalid parameters'));
        }
    }

}
