<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\Menu;
use app\admin\model\Content as ContentModel;

class Content extends Base
{
    public function index()
    {
        // 判断权限
       
        //获取分类树
        $categoryArray = Db::name('category')->order('listorder')->select();
        $categoryList = Menu::tree($categoryArray);
        $this->assign('categoryList',$categoryList);
        return view();
    }

    public function content($id = 0)
    {
        if($id){
            // 判断权限
            if(!checkAuth()){
                $id = 0;
                echo "<script src='/static/admin/js/jquery.min.js?v=2.1.4'></script>".
                    "<script>$(document).ready(function(){ layer.open({content: '您没有相应的操作权限!',btn: ['确定'],icon: 2,shade: 0.1}); });</script>";
            }
            $catname = getCatInfoById($id, 'catname');
            $this->assign('catname',$catname);
            $this->assign('id',$id);
        }

        return view();
    }

    public function delete($catid = 0, $id = 0){
        // 判断权限
        if(!checkAuth()){
            return error('您没有相应的操作权限!');
        }
        // 获取表名
        $tablename = getModInfoById($catid, 'tablename');
        if(Db::name($tablename)->where('id',$id)->delete()){
            return success('删除成功!',url('content',['id'=>$catid]));
        }else{
            return error('删除失败!');
        }
    }

    // 批量删除
    public function deleteAll(){
        // 判断权限
        if(!checkAuth()){
            return error('您没有相应的操作权限!');
        }
        $catid = input('post.catid');
        // 获取表名
        $tablename = getModInfoById($catid, 'tablename');
        if (empty(input('post.ids/a'))) {
            return error('请选中需要删除的数据!');
        }
        foreach (input('post.ids/a') as $id => $value) {
            Db::name($tablename)->where('id',$id)->delete();
        }
        return success('删除成功!',url('content',['id'=>$catid]));
    }

    // datatables插件请求地址
    public function getDataTables($id) {

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

            $draw = $getParam['draw'];

            //排序
            $orderSql = $getParam['listorder'][0]['dir'];

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

            // 获取表名
            $tablename = getModInfoById($id, 'tablename');
            // 总记录数
            $recordsTotal = Db::name($tablename)->where('catid',$id)->count();
            //过滤条件后的总记录数
            $search = $getParam['search']['value'];
            $recordsFiltered = strlen($search) ?  Db::name($tablename)->where('catid',$id)->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('catid',$id)->where($extra_search,'like','%'.$search.'%')->order($orderSql)->paginate(null,false,$config);
            $lists = [];
            if(!empty($list)){
                foreach ($list as $key => $value) {
                    $lists[$key] = $value;
                    $lists[$key]['operate'] = "<a href='". url('edit',['id'=>$value['id'], 'catid'=>$value['catid']]) ."' title='编辑' target='_parent'><i class='fa fa-edit text-navy'></i></a>&nbsp;&nbsp;
                    <a name='delete' href='". url('delete',['id'=>$value['id'], 'catid'=>$value['catid']]) ."' title='删除'><i class='fa fa-trash-o text-navy'></i></a>";
                }
            }
        } else{
            $draw = 1;
            $recordsTotal = 0;
            $recordsFiltered = 0;
            $lists = [];
        }

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

        echo json_encode($data);
    }

    //信息发布
    public function add($requireField = '', $requireFieldName = '') {
        $id = input('id', 0);
        if(request()->isPost()) {
            // 判断权限
            if(!checkAuth()){
                return error('您没有相应的操作权限!');
            }
           $content = new ContentModel;
           if($content->addContent(input('post.'))) {
             return success('信息发布成功!',url('index',['id'=>input('post.catid')]));
           } else {
             return error('信息发布失败!');
           }
        }elseif($id == 0){
           return error ('请选择相应分类！');
        } else {
          //根据分类ID获取模型ID
          $modelid = getModInfoById($id,'id');
          $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']
                      );
                  }
              }
          }
          $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()) {
            // 判断权限
            if(!checkAuth()){
                return error('您没有相应的操作权限!');
            }
           $content = new ContentModel;
           if($content->editContent(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']
                      );
                  }
              }
          }
          $this->assign('forminfos',$info);
          //分类名称
          $catname = getCatInfoById($catid,'catname');
          $this->assign('catname',$catname);
          return view();
        }
    }

    //单文件异步上传
    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) { }
    }

}
