<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use util\Tree;
use app\admin\model\Menu;

use app\admin\model\Category as CategoryModel;


class Link extends Base
{
    public function index($tab = 1, $id = 0){
        // 判断权限
        // if(!checkAuth()){
        //     echo "<script>parent.window.location.href='/zhandaoadmin/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('link')->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 = 'link';
        // 总记录数
        $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]['linkname'] =str_cut($value['linkname'],20);

              $lists[$key]['sort'] ="<input type='text' class='form-control' id='js-ajaxsort' name='sort[".$value['id']."]' value='".$value['sort']."' data-id='".$value['id']."'>";
               
              if($lists[$key]['linkpic'] ==NULL){
                  $lists[$key]['linkpic']= "请上传产品图片！";
                   
              }else{
               

                $imgdata=explode(',',$value['linkpic']);
                $listimg='';
              
                $listimg="<img src='/public/uploads/".$imgdata[0]."' width='80' >";
             
               $lists[$key]['linkpic']= $listimg;
              }
                
                $lists[$key]['operate'] = "<a href='". url('index',['id'=>$value['id'], 'tab'=>3]) ."' title='编辑'><i class='fa fa-edit text-navy'></i></a>&nbsp;&nbsp;
                <a name='delete' href='". url('del',['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($requireField = '', $requireFieldName = '') {
        
        if(request()->isPost()) {
          $data=input('post.');

             if($data['linkname']==null)
           {
                $this->error("链接名称不能为空！");
           }
             if(preg_match("/\\d+/",$data['linkname'])==1)
              {
                 $this->error("必须包含中文！");//全数字
              }

            $newname=$data['linkname'];
            $searchname=Db::name('link')->where('linkname',$newname)->find();
            if(!empty($searchname)){
               $this->error('链接名称已存在！');
                exit();
            }

            if($_FILES['linkpic']['tmp_name']){
                $data['linkpic']=$this->upload();
            }
           $add=db('link')->insert($data);
           if($add){
             $this->success('链接提交成功！',url('index'));
           }else{
              $this->error('链接提交失败！');
           }
          return view();
        }
    }


    public function edit($id = 0, $requireField = '', $requireFieldName = '') {
        
        if(request()->isPost()) {
          $data=input('post.');
          
             if($data['linkname']==null)
           {
                $this->error("链接名称不能为空！");
           }
             if(preg_match("/\\d+/",$data['linkname'])==1)
              {
                 $this->error("广告必须包含中文！");//全数字
              }
             if($_FILES['linkpic']['tmp_name']){
                $oldadrts=db('link')->field('linkpic')->find($data['id']);
                $oldadrtImg=IMG_UPLOADS.$oldadrts['linkpic'];
                if(file_exists($oldadrtImg)){
                    @unlink($oldadrtImg);
                }
                $data['linkpic']=$this->upload();
            }
           $save=db('link')->where('id',$id)->update($data);
           if($save!== false){
             $this->success('链接修改成功！',url('index'));
           }else{
              $this->error('链接修改失败！');
           }
          return view();
        }
    }
    

     public function del($id)
    {
        $links=db('link');
        $linkres=$links->field('linkpic')->find($id);
        $linkImg=IMG_UPLOADS.$linkres['linkpic'];
        if(file_exists($linkImg)){
            @unlink($linkImg);
         }
         $del=$links->where('id',$id)->delete();
         if ($del){
             $this->success('删除链接成功！',url('index'));
         }else{
             $this->error('删除链接失败！');
         }
    }
    

     //上传图片
    public function upload(){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('linkpic');
    
    // 移动到框架应用根目录/public/uploads/ 目录下
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            return $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
            die;
        }
    }
}

  


  

}
