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


class Cpcase extends Base
{
    public function index($tab = 1, $id = 0){
        // 判断权限
        if(!checkAuth()){
            echo "<script>parent.window.location.href='/admin/index/index';</script>";
            exit;
        }
        $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 = 'case';
        // 总记录数
        $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;
                
                $lists[$key]['title'] =str_cut($value['title'],20);
                // $lists[$key]['price'] =$value['price'];

                
                if($lists[$key]['catid']==4){
                    $lists[$key]['catid'] ="工程案例";
                }
                

                

                 //$lists[$key]['thumb'] =explode(',',$value['thumb']);
              if($lists[$key]['casepic'] ==NULL){
                  $lists[$key]['casepic']= "请上传案例图片！"; 
              }else{
                $imgdata=explode(',',$value['casepic']);
                $listimg='';
              
                $listimg="<img src='/public/uploads/".$imgdata[0]."' width='80' >";
             
               $lists[$key]['casepic']= $listimg;
              }
               

                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 = 4, $tab = 2) {
        
        if(request()->isPost()) {
          $data=input('post.');
          if(!checkAuth()){
            return error('您没有相应的操作权限!');
          }
          $newname=$data['info']['title'];
          $searchname=Db::name('product')->where('title',$newname)->find($id);
          
          if(!empty($searchname)){
               return error('案例标题已存在！');
                exit();
            }
           if($data['catid']==0)
           {
                return error("请选择案例栏目！");
           }

           if($data['info']['title']==null)
           {
                return error("案例标题不能为空！");
           }


           if($data['info']['casecontent']==null)
           {
                return error("案例内容不能为空！");
           }
           

           $content = new CpcaseModel;
           if($content->addCpcase(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()) {
            if(!checkAuth()){
            return error('您没有相应的操作权限!');
          }

            $content = new CpcaseModel;
           if($content->editCpcase(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();

          $cpcaseres=db('case')->field('catid')->find($id);
          
          $this->assign('cpcaseres',$cpcaseres);
          $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){
        //判断权限
        if(!checkAuth()){
            $this->error('您没有相应的操作权限!');
        }

       $cpcases=db('case')->field('casepic')->find($id);
       $imgdata=explode(',',$cpcases['casepic']);
      
       if($imgdata){
          foreach ($imgdata as $k => $v){
             foreach ($imgdata as $k1 => $v1){
                $thumbSrc=IMG_UPLOADS.$v1;
                if(file_exists($thumbSrc)){
                      @unlink($thumbSrc);
                  }
             }
          }
        }
       
       //  // 获取表名
        $tablename = getModInfoById($catid, 'tablename');
       
        if(Db::name($tablename)->where('id',$id)->delete()){
            $this->success('删除成功!',url('index',['id'=>$catid]));
        }else{
           $this->error('删除失败!');
        }
    }

  


    public function deleteAll(){
        // 判断权限
        if(!checkAuth()){
            return error('您没有相应的操作权限!');
        }
        $ids = input('post.ids/a');
        $cases=db('case')->field('casepic')->find($id);

        $imgdata=explode(',',$cases['casepic']);
        
        if($ids){
          foreach ($imgdata as $k => $v){
             foreach ($imgdata as $k1 => $v1){
                $thumbSrc=IMG_UPLOADS.$v1;
                if(file_exists($thumbSrc)){
                      @unlink($thumbSrc);
                  }
             }
          }
        }
        
        // 获取表名
       
        foreach (input('post.ids/a') as $id => $value) {
            Db::name('case')->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) { }
    }

    


   

  

}
