<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use util\Tree;
use app\admin\model\Menu;
use app\admin\model\Page as PageModel;
use app\admin\model\Category as CategoryModel;


class Page extends Base
{
    public function index($tab = 1, $id = 0){
       
        
       
        $category = CategoryModel::order('listorder')->select();
        $categoryList = array();
        foreach ($category as $key => $value) {


 
            $categoryList[] = $value->toArray(); //对象转数组
            //一对一关联出对应模型
            if( 0 != $categoryList[$key]['isend'] && 0 != $categoryList[$key]['modelid']){
                $categoryList[$key]['models'] = $value->models->toArray(); //关联模型用时才加载
            }

        }
        $tree = new Tree();
        $tree->tree($categoryList,'id','parentid','catname');
        $categoryArray = $tree->getArray();

        $this->assign('category',$categoryArray);
        // // 编辑菜单，默认加载
        if( 3 == $tab ){
            // 获取所要编辑菜单的信息
            $info = Db::name('page')->where('id',$id)->find();
            if($info!=null && is_array($info)){
                $this->assign('info',$info);
            }
        }
        return view();
    }
   


  
    public function getDataTables() {
        

        //获取请求过来的数据
        $getParam = request()->param();

        $draw = $getParam['draw'];

        //排序
        $orderSql = 'id desc';

        //自定义查询参数
        $extra_search = $getParam['extra_search'];

        // 获取表名
        $tablename = 'pages';
        // 总记录数
        $recordsTotal = Db::name($tablename)->count();
        //过滤条件后的总记录数
        $search = $getParam['search']['value'];
        $recordsFiltered = strlen($search) ?  Db::name($tablename)->where($extra_search,'like','%'.$search.'%')->count() : $recordsTotal;

        //分页
        $start = $getParam['start']; //起始下标
        
        $length = $getParam['length']; //每页显示记录数

        //根据开始下标计算出当前页
        $page = intval($start/$length) + 1;
        $config = ['page'=>$page, 'list_rows'=>$length];
        $list = Db::name($tablename)->where($extra_search,'like','%'.$search.'%')->order($orderSql)->paginate(null,false,$config);
        $lists = [];
        if(!empty($list)){
            foreach ($list as $key => $value) {
                $lists[$key] = $value;
                

                if($lists[$key]['status']==1){
                    $lists[$key]['status'] ="<button class='btn btn-info btn-circle btn-lg' id='".$value['id']."'  type='button' ><i class='fa fa-check'></i></button>";
                }else{
                    $lists[$key]['status'] ="<button class='btn btn-info btn-circle btn-lg' id='".$value['id']."'  type='button' ><i class='fa fa-times'></i></button>";
                }

                $lists[$key]['operate'] = "<a href='". url('edit',['id'=>$value['id'], 'catid'=>$value['catid']]) ."' onClick='location.href='{:url('add')}'' title='编辑'><i class='fa fa-edit text-navy'></i></a>&nbsp;&nbsp;
                <a name='delete' href='". url('deletedg',['id'=>$value['id'], 'catid'=>$value['catid']]) ."' title='删除'><i class='fa fa-trash-o text-navy'></i></a>";
            }
        }

        $data = array(
            "draw"=>$draw,
            "recordsTotal"=>$recordsTotal, //数据总数
            "recordsFiltered"=>$recordsFiltered, //过滤之后的记录总数
            "data"=>$lists
        );

        echo json_encode($data);
    }


   //单页发布
    public function add($id = 1, $tab = 2) {
        
        if(request()->isPost()) {
          $data=input('post.');
           if($data['catid']==0)
           {
                return error("请选择单页栏目！");
           }
           if($data['info']['title']==null)
           {
                return error("单页标题不能为空！");
           }
           
           if($data['info']['content']==null)
           {
                return error("单页内容不能为空！");
           }
           

           $content = new PageModel;
           if($content->addPage(input('post.'))) {
             return success('单页发布成功!',url('index',['id'=>input('post.catid')]));
           } else {
             return error('单页发布失败!');
           }
        }elseif($id == 0){
           return error ('请选择相应分类！');
        } else {
         
          // var_dump($cateid);
          // die;
          //根据分类ID获取模型ID
          $modelid = getModInfoById($id,'id');
          // var_dump($modelid);
          // die;
          $modelsFieldArray = Db::name('models_field')->where('modelid',$modelid)->order('sort')->select();
          foreach ($modelsFieldArray as $value) {
              //字段名
              $field = $value['field'];
              //字段类型
              $func = $value['formtype'];

              //判断函数是否存在
              if(function_exists($func)){
                  //获取表单HTML代码
                  $form = $func($value);

                  if($form != ''){
                      $info[$field] = array(
                          'name' => $value['name'],
                          'form' => $form,
                          'formtype' => $value['formtype']
                      );
                  }
              }
          }
          $category = CategoryModel::order('listorder')->select();
          $categoryList = array();
          foreach ($category as $key => $value) {


   
              $categoryList[] = $value->toArray(); //对象转数组
              //一对一关联出对应模型
              if( 0 != $categoryList[$key]['isend'] && 0 != $categoryList[$key]['modelid']){
                  $categoryList[$key]['models'] = $value->models->toArray(); //关联模型用时才加载
              }

          }
          $tree = new Tree();
          $tree->tree($categoryList,'id','parentid','catname');
          $categoryArray = $tree->getArray();

          $this->assign('category',$categoryArray);
          $this->assign('forminfos',$info);
          //分类名称
          $catname = getCatInfoById($id,'catname');
          $this->assign('catname',$catname);
          return view();
        }
    }
    

    //编辑功能
    public function edit($id = 0, $requireField = '', $requireFieldName = '') {
         $catid = input('catid', 0);
        if(request()->isPost()) {
            $content = new PageModel;
           if($content->editPage(input('post.'))) {
             return success('单页编辑成功!',url('index',['id'=>input('post.catid')]));
           } else {
             return error('单页编辑失败!');
           }
        }else {
          //获取数据
          $tablename = getModInfoById($catid,'tablename');
          $article = Db::name($tablename)->where('id',$id)->find();

          //根据分类ID获取模型ID
          $modelid = getModInfoById($catid,'id');
          $modelsFieldArray = Db::name('models_field')->where('modelid',$modelid)->order('sort')->select();
          foreach ($modelsFieldArray as $value) {
              //字段名
              $field = $value['field'];
              //字段类型
              $func = $value['formtype'];

              $value['realvalue'] = $article[$field];

              //判断函数是否存在
              if(function_exists($func)){
                  //获取表单HTML代码
                  $form = $func($value);

                  if($form != ''){
                      $info[$field] = array(
                          'name' => $value['name'],
                          'form' => $form,
                          'formtype' => $value['formtype']
                      );
                  }
              }
          }
           $category = CategoryModel::order('listorder')->select();
          $categoryList = array();
          foreach ($category as $key => $value) {


   
              $categoryList[] = $value->toArray(); //对象转数组
              //一对一关联出对应模型
              if( 0 != $categoryList[$key]['isend'] && 0 != $categoryList[$key]['modelid']){
                  $categoryList[$key]['models'] = $value->models->toArray(); //关联模型用时才加载
              }

          }
          $tree = new Tree();
          $tree->tree($categoryList,'id','parentid','catname');
          $categoryArray = $tree->getArray();

          $pageres=db('pages')->field('catid')->find($id);
          
          $this->assign('pageres',$pageres);
          $this->assign('category',$categoryArray);
          $this->assign('forminfos',$info);
          //分类名称
          $catname = getCatInfoById($catid,'catname');
          $this->assign('catname',$catname);
          return view();
        }
    }

    
    public function deletedg($catid = 0, $id = 0){
        // 获取表名
        $tablename = getModInfoById($catid, 'tablename');
        if(Db::name($tablename)->where('id',$id)->delete()){
            return success('删除成功!',url('index',['id'=>$catid]));
        }else{
            return error('删除失败!');
        }
    }

 


    public function deleteAll(){
       
        $ids = input('post.ids/a');
        // var_dump($catid);
        // die;
        // 获取表名
       
        foreach (input('post.ids/a') as $id => $value) {
            Db::name('pages')->where('id',$id)->delete();
        }
        return success('删除成功!',url('index'));
    }
    

   

 
    


     //单文件异步上传
    public function upload_image(){
        //图片上传
        $file = request()->file(input('name'));
        $info = $file->move(ROOT_PATH . 'public/uploads');
        if($info) {
            return json_encode($info->getSaveName());
        }
    }

    //多图片上传
    public function upload_images(){
        $file = request()->file('file');
        $info = $file->move(ROOT_PATH . 'public/uploads');
        if($info) {
            return json_encode($info->getSaveName());
        }
    }

    //多文件上传
    public function upload_downfiles(){
        $files = request()->file('file');
        foreach ($files as $file) {
            $info = $file->move(ROOT_PATH . 'public/uploads');
            if($info) {
                return $info->getSaveName();
            }
        }
    }

    //删除文件或图片
    public function delete_file(){
        $delete_url = input('img');
        try {
          unlink(ROOT_PATH . 'public/uploads/' . $delete_url);  //删除成功返回1
        } catch (Exception $e) { }
    }

    


   

  

}
