<?php

namespace app\admin\controller\posts;

use app\common\controller\Backend;
use think\Hook;
use think\Session;
use fast\Tree;
use seven\Seven;
use app\admin\model\PostsModelx as Modelx;
use app\common\model\Counter;

/**
 * 文档管理
 *
 * @icon fa fa-file-code-o
 */
class Archives extends Backend
{

    /**
     * Posts模型对象
     */
    protected $model = null;
    protected $noNeedRight = ['get_model_fields','check_element_available'];
    protected $multiFields = ['status'];

    protected $searchFields = ['name', 'title'];

    private $channellist = [];

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Archives');

        /*
        if(!$this->auth->isSuperAdmin()){
            $this->model->where('site_id', 'in', function ($query) {
                $admin = $this->auth->getUserInfo();
                $query->table(config("database.prefix") . 'sites')->where('user_id', $admin['id'])->field('id');
            });
        }*/
    }

    /**
     * 读取栏目列表
     */
    private function initForm($siteId=null)
    {
        $where=$first_siteid='';
        if ($this->auth->isSuperAdmin()) {
            $sitelist = \app\admin\model\Sites::all();
            $this->view->assign('siteList', $sitelist);

            //记住下拉列表中第一个网站的ID，添加文章时，只读取对应的栏目等信息
            if ($sitelist && $this->request->action()=='add') {
                $first_siteid = $sitelist[0]['id'];
                $where = ['site_id' => $first_siteid];
            }
        }
        else {
            $this->view->assign('siteList', null);
            $first_siteid = Session::get('user_site_id');
        }
        if (!is_null($siteId)) $first_siteid=$siteId;

        $tree = Tree::instance();
        $tree->init(model('channel')->with('sites')->where($where)->order('site_id asc,weigh desc,id desc')->select(), 'pid');
        $this->channellist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $channeldata = []; //0 => ['mode' => 'default','site_id'=>0, 'name' => __('None')]];
        foreach ($this->channellist as $k => $v)
        {
            $channeldata[$v['id']] = $v;
            $channeldata[$v['id']]['disabled'] = 0;
            $channeldata[$v['id']]['sitename'] = $v['sites']['name'] == '' ? __('Main site') : $v['sites']['name'];
            if ($v['type'] != 'list') {
                $channeldata[$v['id']]['disabled'] = 1;
            }
        }
        $this->view->assign("channelList", $channeldata);
        $this->view->assign("extra", '');
        $ml = Seven::build_langs('row[lang]',null,['siteid'=>$first_siteid]);
        $this->view->assign('multilanguage',$ml);
    }

    /**
     * 查看
     */
    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(false, true);
            $total = $this->model
                ->where($where)
                //->where('site_id', Session::get('admin.siteid'))
                ->where('isDelete',0)
                ->order($sort, $order)
                ->count();

            $tablename = $this->model->getQuery()->getTable();
            $list = $this->model
                ->where($where)
                //->where('site_id', Session::get('admin.siteid'))
                ->where('isDelete',0)
                ->with('sites,channel')
                ->field('subtitle,content',true, $tablename)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

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

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

    /**
     * 回收站
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where('isDelete','>',0)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $tablename = $this->model->getQuery()->getTable();
            $list = $this->model
                ->where('isDelete','>',0)
                ->where($where)
                ->with('channel')
                ->field('id,channel_id,title,cover,type,isDelete',false, $tablename)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

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

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

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {

                if ($this->dataLimit)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if(empty($params['updatetime'])) $params['updatetime'] = time();

                if (!isset($params['site_id'])) {
                    $params['site_id'] = Session::get('user_site_id');
                }
                $params['authorid']=Session::get("admin.id");

                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)
                    {
                        Counter::create(['item_id'=>$this->model->id,'item_type'=>'archive','views'=>$params['views']]);
                        Modelx::saveExtraForm($params['type'],$this->model->id, $params);
                        $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->initForm();
        return $this->view->fetch();
    }

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

        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                //没有自定义“修改时间”，将以实际修改时间为准
                if($params['updatetime_old']==$params['updatetime']){
                    $params['updatetime']=time();
                }else{
                    $params['updatetime']=strtotime($params['updatetime']);
                }
                unset($params['updatetime_old']);
                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)
                    {
                        Counter::where(['item_id'=>$ids, 'item_type'=>'archive'])->update(['views'=>$params['views']]);
                        Modelx::saveExtraForm($row['type'], $ids, $params);

                        $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);
        $channeldata = []; //0 => ['mode' => 'default','site_id'=>0, 'name' => __('None')]];
        foreach ($this->channellist as $k => $v)
        {
            if($v['site_id']==$row['site_id']) {
                $channeldata[$v['id']] = $v;
                $channeldata[$v['id']]['disabled'] = 0;
                if ($v['type'] != 'list') {
                    $channeldata[$v['id']]['disabled'] = 1;
                }
                if ($row['type'] != $v['model']) {
                    $channeldata[$v['id']]['disabled'] = 1;
                }
            }
        }
        $this->view->assign("channelList", $channeldata);
        $this->view->assign("extra", Modelx::getExtraForm($row->type, $ids));
        $this->view->assign('multilanguage', Seven::build_langs('row[lang]',$row['lang'],['siteid'=>$row->site_id]));

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $this->model->where($this->dataLimitField,'in', $adminIds);
            }
            $result=$this->model->where($pk, 'in', $ids)->update(['isDelete'=>time()]);

            if ($result!=false)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /*
     * Destroy
     *  销毁,无参数时清空回收站
     *  删除后一并将访问统计、模型表相对应数据清除
     */
    public function destroy($ids="")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        if($ids=='')
        {
            $this->model->where(['isDelete'=>['>',0]]);
        }
        else
        {
            $this->model->where($pk, 'in', $ids);
        }
        $list = $this->model->select();

        if(!$list){
            $this->error(__('No rows were deleted'));
        }
        $count = 0;
        foreach ($list as $k => $v)
        {
            $result = $v->delete();
            //删除相关附件，扩展&模型表
            if($result!=false) {
                Hook::listen('archive_del', $v);
                Counter::where(['item_type'=>'archive', 'item_id' => $v[$pk]])->delete();
                $count++;
            }
        }
        if ($count)
        {
            $this->success();
        }else {
            $this->error($this->model->getError());
        }
        $this->error(__('Operation failed'));
    }

    /**
     * 还原
     */
    public function restore($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids=='')
        {
            $this->model->where('isDelete','>', 0);
        } else {
            $this->model->where($pk, 'in', $ids);
        }
        $count = $this->model->restore('1=1');
        if ($count)
        {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 批量移动到其他分类
     */
    public function move($ids="")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $channel_id = $this->request->param('channel_id');
        $moveable = [];

        $dstCate = \app\admin\model\Channel::get($channel_id);

        if(!$dstCate){
            $this->success(__('You have no permission'));
        }
        if ($ids)
        {

            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $lists = $this->model->where($pk, 'in', $ids)->select();
            $count=0;
            foreach($lists as $k => $v)
            {
                //忽略不同模型
                if ($v['type']==$dstCate['model'] && $v['channel_id']!=$dstCate['id']){
                    $moveable[] = $v[$pk];
                }
            }
            \app\admin\model\AdminLog::setTitle(__('Move'));
            foreach($moveable as $k=>$v) {
                if(sesion('admin.id')!=1) {
                    $count += $this->model->where($pk, $v)->update(['channel_id' => $channel_id, 'site_id' => $dstCate['site_id']]);
                }else { //非超级管理员，不能跨站移动
                    $count += $this->model->where($pk, $v)->update(['channel_id' => $channel_id]);
                }
            }
            if($count){
                $this->success();
            }else {
                $this->success(__('No rows were updated'));
            }
        }
        $this->success(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 输出模型表单
     */
    public function get_model_fields()
    {
        $result = ['name'=>'', 'html'=>''];
        if($this->request->isAjax())
        {
            $modelname=$this->request->post('model');
            $form = Modelx::getExtraForm($modelname);
            if($form != ''){
                $result['name'] = $modelname;
                $result['html'] = $form;
            }
            $this->success('', '', $result);
        }
    }

    /**
     * 校验字段的值的唯一性
     */
    public function check_element_available()
    {
        $field = $this->request->post('name');
        $value = $this->request->post('value');
        if($field && $value) {
            //$params = ['diyname' => $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', ''));
        }
    }
}
