<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Cache;

/**
 * 会员规则管理
 *
 * @icon fa fa-car
 */
class Car extends Backend
{

    /**
     * Car模型对象
     * @var \app\admin\model\Car
     */
    protected $model = null;
    protected $rulelist = [];
    protected $multiFields = 'ismenu,status';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Car');
//        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("ismenuList", $this->model->getIsmenuList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $filter = $this->request->get("filter", '');
        $filter = json_decode($filter, true);
        $where = [];
        if (!empty($filter['title'])) $where['title'] = ['LIKE', '%' . $filter['title'] . '%'];
        // 必须将结果集转换为数组
        $ruleList = collection($this->model->field('*,pid')->where($where)->order('weigh', 'desc')->select())->toArray();
        foreach ($ruleList as $k => &$v) {
            $v['title'] = __($v['title']);
            $v['remark'] = __($v['remark']);
        }
        unset($v);
        Tree::instance()->init($ruleList);
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
            if (!$v['ismenu']) {
                continue;
            }
            $ruledata[$v['id']] = $v['title'];
        }
        $this->view->assign('ruledata', $ruledata);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
//        if ($this->request->isAjax()) {
//            $list = $this->rulelist;
//            $total = count($this->rulelist);
//
//            $result = array("total" => $total, "rows" => $list);
//
//            return json($result);
//        }
//        return $this->view->fetch();
        //设置过滤方法
        if ($this->request->isAjax()) {
            $list = $this->rulelist;
            $total = count($this->rulelist);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查看
     */
//    public function index()
//    {
//        //设置过滤方法
//        $this->request->filter(['strip_tags', 'trim']);
//        if ($this->request->isAjax()) {
//            //如果发送的来源是Selectpage,则转发到Selectpage
//            if ($this->request->request('keyField')) {
//                return $this->selectpage();
//            }
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
//            $list = $this->model
//                ->where($where)
//                ->order($sort, $order)
//                ->paginate($limit);
//
//            $result = array("total" => $list->total(), "rows" => $list->items());
//
//            return json($result);
//        }
//        return $this->view->fetch();
//    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $Info = Db::name('car')->where('id', $ids)->find();
        $this->assignconfig('ismenu', $Info['ismenu']);

        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $delIds = [];
            foreach (explode(',', $ids) as $k => $v) {
                $delIds = array_merge($delIds, Tree::instance()->getChildrenIds($v, true));
            }
            $delIds = array_unique($delIds);
            $count = $this->model->where('id', 'in', $delIds)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }

    /*拉取资料*/
    public function Pull()
    {
        $this->CreateDoc();
        Cache::clear();
        $this->success('更新成功');
    }


    /*DOC*/
    public function CreateDoc()
    {
        /*查询出所有文件夹名称*/
        $HouseName = Db::name('house')->where('ismenu', 0)->select();
        if (!empty($HouseName)) {
            foreach ($HouseName as $k => $v) {
                /*返回目录结构*/
                $Tree = $this->read_all_dir('../public/doc/' . $v['title']);
                if (!empty($Tree)) {
                    foreach ($Tree as $key => $value) {
                        /*新增一级标题*/
                        unset($value[0]);
                        $IsHave = Db::name('car')->where('pid', 0)->where('title', $key)->find();
                        if (empty($IsHave)) {
                            Db::name('car')->insert(['pid' => 0, 'title' => $key, 'ismenu' => 1, 'createtime' => time(), 'updatetime' => time(), 'weigh' => 0, 'pdf_file' => '', 'image' => '/doc/' . $v['title'] . '/' . $key . '/1.png', 'con' => $key, 'read_num' => 0, 'house_id' => Db::name('house')->where('title', $v['title'])->value('id')]);
                        }
                        $this->LastSon($value, Db::name('car')->where('title', $key)->order('id desc')->value('id'), Db::name('house')->where('title', $v['title'])->value('id'), '/doc/' . $v['title'] . '/' . $key);
                    }
                }
            }
        }
    }

    /*递归函数*/
    public function LastSon($Array, $Pid, $Houseid, $PdfUrl)
    {
        foreach ($Array as $k => $v) {
            if (!is_numeric($k)) {
                //$k != int类型 是分类标题 else 是下标
                if (empty(Db::name('car')->where('pid', $Pid)->where('title', $k)->where('ismenu', 1)->where('house_id', $Houseid)->find())) {
                    Db::name('car')->insert(['pid' => $Pid, 'title' => $k, 'ismenu' => 1, 'createtime' => time(), 'updatetime' => time(), 'weigh' => 0, 'pdf_file' => '', 'image' => '', 'con' => $k, 'read_num' => 0, 'house_id' => $Houseid]);
                }
            }
            if (is_array($v)) {
//                echo '是数组';
                $this->LastSon($v, Db::name('car')->where('title', $k)->order('id desc')->value('id'), $Houseid, $PdfUrl . '/' . $k);
            } else {
//                echo '是pdf';
                $Name = explode('.', $v);
                if (empty(Db::name('car')->where(['pdf_file' => $PdfUrl . '/' . $v])->find())) {
                    Db::name('car')->insert(['pid' => $Pid, 'title' => $Name[0], 'ismenu' => 0, 'createtime' => time(), 'updatetime' => time(), 'weigh' => 0, 'pdf_file' => $PdfUrl . '/' . $v, 'image' => '', 'con' => $v, 'read_num' => 0, 'house_id' => $Houseid]);
                }
            }
        }
    }


    /*递归获取项目树*/
    function read_all_dir($dir)
    {
        $arr = array();
        $hander = scandir($dir);                                             //列出文件下的目录
        foreach ($hander as $v) {                                           //遍历文件夹下所有文文件
            if (is_dir($dir . DS . $v) && $v != "." && $v != "..") {        //判断文件夹下是否还有文件夹需要遍历
                $arr[$v] = $this->read_all_dir($dir . DS . $v);                    //递归调用
            } else {
                if ($v != "." && $v != "..") {                                //排除  "." " .."
                    $arr[] = $v;                                              //文件存入
                }

            }
        }
        return $arr;
    }
}