<?php

// +----------------------------------------------------------------------
// | thinkcmf 内容管理
// +----------------------------------------------------------------------
// | Copyright (c) thinkcmf
// +----------------------------------------------------------------------
// | Author: sd <995251229@qq.com>
// +----------------------------------------------------------------------

namespace Content\Controller;
use Common\Controller\AdminbaseController;
use Content\Model\ContentModel;
class ContentshowController extends AdminbaseController {
    function _initialize() {
        parent::_initialize();
        $this->fields = APP_PATH . 'Content/Fields/';
        $config_siteurl = __ROOT__.'/public/';
        $this->assign("config_siteurl", $config_siteurl);
    }
     //栏目信息列表
   
      public function classlist() {
        $where = array();
        //查询条件
        $catids = I("catids");
        if($catids){
            $arr_catids = explode(',',$catids);
            foreach($arr_catids as $val){
                $map_arr['catid']=$val;
                $catInfos = M("Category")->where($map_arr)->find();
                $all_catids[] = $catInfos['arrchildid'];
            }
            $all_catids=implode(',', array_unique(explode(',',implode(',', $all_catids))));
            $modelid=$catInfos['modelid'];
            $where['catid'] = array('IN', $all_catids);
            $where['is_del'] = 0;
            //实例化模型
            $model_name=getModel($modelid, 'tablename');
            $model=M($model_name);
            //数量统计
            $sum = $model->where($where)->count();
            $checkSum = $model->where(array_merge($where, array('status' => 1)))->count();
            $this->assign('sum', $sum)->assign('checkSum', $checkSum);
        }elseif(I('modelid')){
            //当前栏目信息
            $modelid=I('modelid');
            //$where['modelid'] = $modelid;
            //实例化模型
            $model_name=getModel($modelid, 'tablename');
            $model=M($model_name);

        }else{
            //当前栏目信息
            $this->catid=I('catid')?I('catid'):$_POST['catid'];
            
            $map['catid']=I('catid');
            $catInfo = getCategory($map['catid']);
            $all_catids=$catInfo['arrchildid'];
            if (empty($catInfo)) {
                $this->error('该栏目不存在！', U('Content/Contents/index'));
            }
            //栏目所属模型
            $modelid = $catInfo['modelid'];
            //栏目扩展配置
            $setting = $catInfo['setting'];
            $where['catid'] = array('IN', $all_catids);
            $where['is_del'] = 0;
            //实例化模型
            $model_name=getModel($modelid, 'tablename');
            $model=M($model_name);
            //数量统计
            $sum = $model->where($where)->count();
            $checkSum = $model->where(array_merge($where, array('status' => 1)))->count();
            $this->assign('sum', $sum)->assign('checkSum', $checkSum);
        }
        //检查模型是否被禁用
        if (getModel($modelid, 'disabled')) {
            $this->error('模型被禁用！');
        }
        //搜索
        if(IS_POST){
                //添加开始时间
                $start_time = $_POST['start_time'];
                if (!empty($start_time)) {
                    $start_time = strtotime($start_time);
                    $where['inputtime'] = array("EGT", $start_time);
                    $this->assign('start_time', $_POST['start_time']);
                }
                //添加结束时间
                $end_time = $_POST['end_time'];
                if (!empty($end_time)) {
                    $end_time = strtotime($end_time);
                    $where['inputtime'] = array("LT", $end_time);
                    $this->assign('end_time', $_POST['end_time']);
                }
                if ($end_time > 0 && $start_time > 0) {
                    $where['inputtime'] = array(array('EGT', $start_time), array('LT', $end_time));
                }
                //搜索字段
                $searchtype = $_POST['searchtype'];
                //搜索关键字
                $keyword = $_POST['keyword'];
                if (!empty($keyword)) {
                    $this->assign("searchtype", $searchtype);
                    $this->assign("keyword", $keyword);
                    $type_array = array('title', 'description', 'username');
                    if ($searchtype < 3) {
                        $searchtype = $type_array[$searchtype];
                        $where[$searchtype] = array("LIKE", "%{$keyword}%");
                    } elseif ($searchtype == 3) {
                        $where["id"] = array("EQ", (int)$keyword);
                    }
                }
                //状态
                $status = $_POST['status'];
                if ($status) {
                    $where['status'] = array("EQ", $status);
                }
        }
        //信息总数
        if(!I('modelid')){
            if (empty($search)) {
                $count = $sum;
            } else {
                $count = $model->where($where)->count();
            }
            $page = $this->page($count, 20);
            $this->assign('Page', $page->show());
        }
        //置顶
        if(I("istop")){$order['istop']='desc';}else{$order['listorder']='desc';}
        //推荐
        if(I("recommend")){$order['recommend']='desc';}else{$order['listorder']='desc';}
        $px = I('order');
        if($px)$order = "listorder $px,id $px";
        else $order = 'listorder desc,id desc';
        $where['is_del'] = 0;
        $data = $model->where($where)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select();
        //模板处理
        $template = '';
        //自定义列表
        if (!empty($setting['list_customtemplate'])) {
            $template = "Listtemplate:{$setting['list_customtemplate']}";
        }
        //选择分类
        if($catInfo['child'] == 1){
            $sons = array_splice(explode(',', $catInfo['arrchildid']),1);
            foreach($sons as $val){
                $catinfo_son[] = M('Category')->where(array('catid'=>$val,'child'=>0))->field('catid,catname')->find();
            }
            $catinfo_son = array_filter($catinfo_son);
        }
        $catinfo_son = get_catgory_son($this->catid);

        //排序
        $mapor['modelid'] = $modelid;
        $mapor['catid'] = $this->catid;
        $orderinfo = M('Sortorder')->where($mapor)->find();



        $this->assign($catInfo)
            ->assign('catid', $this->catid)
            ->assign('count', $count)
            ->assign('catinfo_son',$catinfo_son)
            ->assign('data', $data)
            ->assign('modelid', $modelid)
            ->assign('orderinfo', $orderinfo);
         
        $this->display();
    }
    //添加信息
    public function add() {
        if(I('catid_s')){
            $catid=I('catid_s');
        }else{
            $catid=I('catid');
            if($_POST['info']['catid']){$catid = intval($_POST['info']['catid']);}
        }
        if($this->auth_con($catid,"add")){$this->error("亲没有添加的权限哦！");}
        if (IS_POST) {
            //栏目ID
             
            if (empty($catid)) {
                $this->error("请指定栏目ID！");
            }
            if (trim($_POST['info']['title']) == '') {
                $this->error("标题不能为空！");
            }
            //获取当前栏目配置
            $category = getCategory($catid);
            //栏目类型为0
            if ($category['type'] == 0) {
                //模型ID
                $modelid = getCategory($catid, 'modelid');
                //检查模型是否被禁用
                if ($this->model[$modelid]['disabled'] == 1) {
                    $this->error("模型被禁用！");
                }
                
                //seourl 检查重复
                $model_name=getModel($modelid, 'tablename');
                if($_POST['info']['seourl']){
                    //检查是否重复
                    $checkseourl = M($model_name)->where(" seourl='".$_POST['info']['seourl']."'")->find();
                    if($checkseourl){
                        $this->error("seourl已经存在！");
                    }
                }
                
                //关键词信息
                $tdks = M('Tdks')->where(array('catid'=>$catid))->find();
                $desc = unserialize($tdks['description']);
                if($tdks && $desc['iswrite'] == 1){
                    $descarr['des1'] = $_POST['des1'];
                    $descarr['desc_mo'] = $_POST['desc_mo'];
                    $descarr['des2'] = $_POST['des2'];
                    $descarr['des3'] = $_POST['des3'];
                    $descarr['des4'] = $_POST['des4'];
                    $_POST['info']['seodescription']=serialize($descarr);
                }
                $map_mf['modelid']=$modelid;
                $map_mf['formtype']='images';
                $Model_info = M("ModelField")->where($map_mf)->select();
                $arr_ua=array();
                if($Model_info){
                    foreach ($Model_info as $key => $val) {
                        $alias_u = $val['field'].'_url';
                        $alias_a = $val['field'].'_alt';
                        $alias_s = $val['field'].'_seq';
                        foreach ($_POST[$alias_u] as $k => $v) {
                            $arr_ua[$k]['url'] = $v;
                            $arr_ua[$k]['alt'] = $_POST[$alias_a][$k];
                             $arr_ua[$k]['seq'] = $_POST[$alias_s][$k];
                        }
                        $_POST['info'][$val['field']] = json_encode($arr_ua);
                    }
                }
                $map_dl['modelid']=$modelid;
                $map_dl['formtype']='downfiles';
                $Model_info_dl = M("ModelField")->where($map_dl)->select();
                $arr_ua_dl=array();
                if($Model_info_dl){
                    foreach ($Model_info_dl as $key => $val) {
                        $alias_u_dl = $val['field'].'_fileurl';
                        $alias_a_dl = $val['field'].'_filename';
                        foreach ($_POST[$alias_u_dl] as $k => $v) {
                            $arr_ua_dl[$k]['fileurl'] = $v;
                            $arr_ua_dl[$k]['filename'] = $_POST[$alias_a_dl][$k];
                        }
                        $_POST['info'][$val['field']] = json_encode($arr_ua_dl);
                    }
                }
                $cons = new \Content\Lib\Content();
                
                $status = $cons->data($_POST['info'])->add();
               
                if ($status) {
                    
                    //不填写seourl,id作为seourl
                    if(!$_POST['info']['seourl']){
                        $up_seourl = M($model_name)->where(" id = $status")->save(array("seourl"=>$status));
                    }
                    //默认添加相关产品
                    $tl['catid'] = $catid;
                    $tl = M($model_name)->where($tl)->order('id desc')->select();
                    if(count($tl) > 0){
                        $tl['id'] = array('lt',$status);
                        $newinfo = M($model_name)->where($tl)->order('id desc')->find();
                        $modelidr = getCategory($newinfo['catid'], 'modelid');
                        $r['relation'] = '|'.$modelidr.','.$newinfo['id'];

                    }else{
                       $r['relation'] = '|'.$modelid.','.$status;
                    }
                    $rew['id'] = $status;
                    M($model_name.'_data')->where($rew)->save($r); 
                    
                    //添加文章赠积分
                    if($modelid == 1){
                        $admininfo = get_admin_info($_SESSION['ADMIN_ID']);
                        $points_auth = explode(',', $admininfo['points_auth']);
                        if($admininfo['identity'] == 1 && in_array(4, $points_auth)){
                            $point_data['adminid'] = $_SESSION['ADMIN_ID'];
                            $point_data['contentid'] = 4;
                            $point_data['points'] = 10;
                            $point_data['addtime'] = date("Y-m-d",time());
                            M('Points')->add($point_data);
                        }
                    }
                     
                    adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_ADD').$_POST['info']['title']);
                    $this->success("添加成功！");
                } else {
                    $error = $this->Content->getError();
                    $this->error($error ? $error : '添加失败！');
                }
            } else if ($category['type'] == 1) {//单页栏目
                $db = D('Content/Page');
                if ($db->savePage($_POST)) {
                    //扩展字段处理
                    if ($_POST['extend']) {
                        D('Content/Category')->extendField($catid, $_POST);
                    }
                    $this->Html->category($catid);
                    $this->success('操作成功！');
                } else {
                    $error = $db->getError();
                    $this->error($error ? $error : '操作失败！');
                }
            } else {
                $this->error("该栏目类型无法发布！");
            }
        } else {
            //取得对应模型
            $category = getCategory($catid);
            if (empty($category)) {
                $this->error('该栏目不存在！');
            }

            if ($category['type'] == 0) {
                //模型ID
                $modelid = $category['modelid'];
                //检查模型是否被禁用
                if (getModel($modelid, 'disabled') == 1) {
                    $this->error('该模型已被禁用！');
                }
                //实例化表单类 传入 模型ID 栏目ID 栏目数组
                $content_form = new \Content\Fields\content_form($modelid, $this->catid);
                $content_form->setModelid($modelid,$catid);
                //生成对应字段的输入表单
                $forminfos = $content_form->get();
                //生成对应的JS验证规则
                $formValidateRules = $forminfos['formValidateRules'];
                if($formValidateRules){
                    $formValidateRules = $forminfos['formValidateRules'];
                }else{
                    $formValidateRules = "'"."'";
                }
                //js验证不通过提示语
                $formValidateMessages = $forminfos['formValidateMessages'];
                //js
                $formJavascript = $forminfos['formJavascript'];
                //取得当前栏目setting配置信息
                $setting = $category['setting'];
                $this->assign("catid", $this->catid);
                $this->assign("content_form", $content_form);
                $this->assign("forminfos", $forminfos);
                //print_r($forminfos['base']);exit;
                $this->assign("formValidateRules", $formValidateRules);
                $this->assign("formValidateMessages", $formValidateMessages);
                $this->assign("formJavascript", $formJavascript);
                $this->assign("setting", $setting);
                $this->assign("category", $category);
                $this->display();
            } else if ($category['type'] == 1) {//单网页模型
                $info = D('Content/Page')->getPage($this->catid);
                if ($info && $info['style']) {
                    $style = explode(';', $info['style']);
                    $info['style_color'] = $style[0];
                    if ($style[1]) {
                        $info['style_font_weight'] = $style[1];
                    }
                }
                $extend = $category['setting']['extend'];
                $this->assign("catid", $this->catid);
                $this->assign("setting", $setting);
                $this->assign('extend', $extend);
                $this->assign('info', $info);
                $this->assign("category", $category);
                //栏目扩展字段
                $this->assign('extendList', D("Content/Category")->getExtendField($this->catid));
                $this->display('singlepage');
            }
        }
    }
    //图片裁减 
    public function public_imagescrop() {
        $picurl = I('get.picurl');
        $catid = I('get.catid', $this->catid, 'intval');
        if (!$catid) {
            $this->error('栏目不存在！');
        }
        if ($picurl) {
            $picurl = str_replace(urlDomain($picurl), '/', $picurl);
        }
        $module = I('get.module', MODULE_NAME);
        $this->assign('picurl', $picurl);
        $this->assign('catid', $catid);
        $this->assign('module', $module);
        $this->display('imagescrop');
    }
    //图片在线裁减，保存图片 
    public function public_crop_upload() {
        $Prefix = "thumb_"; //默认裁减图片前缀
        C('SHOW_PAGE_TRACE', false);
        if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $pic = $GLOBALS["HTTP_RAW_POST_DATA"];
            if (isset($_GET['width']) && !empty($_GET['width'])) {
                $width = intval($_GET['width']);
            }

            if (isset($_GET['height']) && !empty($_GET['height'])) {
                $height = intval($_GET['height']);
            }
            if (isset($_GET['file']) && !empty($_GET['file'])) {
                if (isImage($_GET['file']) == false) {
                    exit();
                }
                $file = $_GET['file'];
                $basename = basename($file);
                if (strpos($basename, $Prefix) !== false) {
                    $file_arr = explode('_', $basename);
                    $basename = array_pop($file_arr);
                }
                $new_file = $Prefix . $width . '_' . $height . '_' . $basename;
                //栏目ID
                // $catid = I('get.catid', 0, 'intval');
                // $module = I('get.module');
                // $Attachment = service("Attachment", array("module" => $module, "catid" => $catid));
                //附件存放路径
                $file_path = './'.C("UPLOADPATH");
                //附件原始名称
                $filename = basename($file);
                //上传文件的后缀类型
                $fileextension = fileext($file);

                $savepath=date('Ymd').'/';

                //保存地址
                $filePaht = $file_path . $savepath . $new_file;
                //保存图片
                file_put_contents($filePaht, $pic);
                //图片信息
                // $info = array(
                //     "name" => $filename,
                //     "type" => "",
                //     "size" => filesize($file_path . $new_file),
                //     "key" => "",
                //     "extension" => $fileextension,
                //     "savepath" => $file_path,
                //     "savename" => $new_file,
                //     "hash" => md5(str_replace($Attachment->uploadfilepath, "", $file_path . $new_file)),
                // );
                // $info['url'] = $Attachment->sitefileurl . str_replace($Attachment->uploadfilepath, '', $info['savepath'] . $info['savename']);
                // $Attachment->movingFiles($info['savepath'] . $info['savename'], $info['savepath'] . $info['savename']);
            } else {
                return false;
            }
            echo $filePaht;
            exit;
        }
    }
    //编辑信息 
    public function edit() {
        $this->catid = (int)$_POST['info']['catid'] ?: I('catid');
        $catid = $this->catid;
        if($this->auth_con($catid,"edit")){$this->error("亲没有编辑的权限哦！");}
        //信息ID
        $id = I('request.id', 0, 'intval');
        $Categorys = getCategory($this->catid);
        if (empty($Categorys)) {
            $this->error("该栏目不存在！");
        }
        //栏目setting配置
        $cat_setting = $Categorys['setting'];
        //模型ID
        $modelid = $Categorys['modelid'];
        //检查模型是否被禁用
        if ($this->model[$Categorys['modelid']]['disabled'] == 1) {
            $this->error("模型被禁用！");
        }
        
        $model = \Content\Model\ContentModel::getInstance($modelid);

        //检查是否锁定
        if (false === $model->locking($this->catid, $id)) {
            $this->error($model->getError());
        }
        if (IS_POST) {
            if (trim($_POST['info']['title']) == '') {
                $this->error("标题不能为空！");
            }
            $id = $id ?: $_POST['info']['id'];
            //取得原有文章信息
            $data = $model->where(array("id" => $id))->find();
            
            //检查seourl是否重复
            
            if(!$_POST['info']['seourl']){
                $this->error("seourl不能为空！");
            }
            
            $checkseourl = $model->where(" id != $id and seourl='".$_POST['info']['seourl']."'")->find();
            
            if($checkseourl){
                $this->error("seourl已经存在！");
            }
           
            //如果有自定义文件名，需要删除原来生成的静态文件
            if ($_POST['info']['prefix'] != $data['prefix'] && $cat_setting['content_ishtml']) {
                //删除原来的生成的静态页面
                $this->Content->data($data)->deleteHtml();
            }
            //关键词信息
            $tdks = M('Tdks')->where(array('catid'=>$catid))->find();
            $desc = unserialize($tdks['description']);
            if($tdks && $desc['iswrite'] == 1){
                $descarr['des1'] = $_POST['des1'];
                $descarr['desc_mo'] = $_POST['desc_mo'];
                $descarr['des2'] = $_POST['des2'];
                $descarr['des3'] = $_POST['des3'];
                $descarr['des4'] = $_POST['des4'];
                $_POST['info']['seodescription']=serialize($descarr);
            }
            $map_mf['modelid']=$modelid;
            $map_mf['formtype']='images';
            $Model_info = M("ModelField")->where($map_mf)->select();
            if($Model_info){
                foreach ($Model_info as $key => $val) {
                    $arr_ua=array();
                    $alias_u = $val['field'].'_url';
                    $alias_a = $val['field'].'_alt';
                    $alias_s = $val['field'].'_seq';
                    foreach ($_POST[$alias_u] as $k => $v) {
                        $arr_ua[$k]['url'] = $v;
                        $arr_ua[$k]['alt'] = $_POST[$alias_a][$k];
                        $arr_ua[$k]['seq'] = $_POST[$alias_s][$k];
                    }
                    $_POST['info'][$val['field']] = json_encode( multi_array_sort($arr_ua,'seq'));
                }
            }
            $map_dl['modelid']=$modelid;
            $map_dl['formtype']='downfiles';
            $Model_info_dl = M("ModelField")->where($map_dl)->select();
            $arr_ua_dl=array();
            if($Model_info_dl){
                foreach ($Model_info_dl as $key => $val) {
                    $alias_u_dl = $val['field'].'_fileurl';
                    $alias_a_dl = $val['field'].'_filename';
                    foreach ($_POST[$alias_u_dl] as $k => $v) {
                        $arr_ua_dl[$k]['fileurl'] = $v;
                        $arr_ua_dl[$k]['filename'] = $_POST[$alias_a_dl][$k];
                    }
                    $_POST['info'][$val['field']] = json_encode($arr_ua_dl);
                }
            }
            $cons = new \Content\Lib\Content();
             
            $status = $cons->data($_POST['info'])->edit();
            if ($status) {
                //解除信息锁定
                M("Locking")->where(array("userid" => session('ADMIN_ID'), "catid" => $catid, "id" => $id))->delete();
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_SAVE').$_POST['info']['title']);
                $this->success("修改成功！");
            } else {
                $this->error($this->Content->getError());
            }
        } else {
            //取得数据，这里使用关联查询
            $data = $model->relation(true)->where(array("id" => $id))->find();
            if (empty($data)) {
                $this->error("该信息不存在！");
            }
            $model->dataMerger($data);
            //锁定信息
            $user_login=M("Users")->where(array("id"=>session('ADMIN_ID')))->getField("user_login");
            M("Locking")->add(
                array(
                    "userid" => session('ADMIN_ID'),
                    "username" => $user_login,
                    "catid" => $this->catid,
                    "id" => $id,
                    "locktime" => time()
                )
            );
            //引入输入表单处理类
            $content_form = new \Content\Fields\content_form($modelid, $this->catid,$id);
            //字段内容
            $forminfos = $content_form->get($data);
            //生成对应的JS验证规则
            $formValidateRules = $forminfos['formValidateRules'];
            if($formValidateRules){
                $formValidateRules = $forminfos['formValidateRules'];
            }else{
                $formValidateRules = "'"."'";
            }

            //js验证不通过提示语
            $formValidateMessages = $forminfos['formValidateMessages'];
            //js
            $formJavascript = $forminfos['formJavascript'];
           
            $this->assign("category", $Categorys);
            $this->assign("data", $data);
            $this->assign("catid", $this->catid);
            $this->assign("modelid",$modelid);
            $this->assign("id", $id);
            $this->assign("content_form", $content_form);
            $this->assign("forminfos", $forminfos);
            $this->assign("formValidateRules", $formValidateRules);
            $this->assign("formValidateMessages", $formValidateMessages);
            $this->assign("formJavascript", $formJavascript);
            $this->display();
        }
    }


    //单页信息 
    public function pagedit() {
        $catid = I('catid');
            //默认部分
            $option=M("Options")->where("option_name='site_options'")->find();
            $option_info =(array)json_decode($option['option_value']);
            $list_title_mo = $option_info['list_title_h'];//title默认部分
            $list_desc_mo = $option_info['list_desc_z'];//description句型默认部分
        if($_POST){
            $article=I("post.post");
            //关键词设置
            $map['catid']=$article['catid'];
            $tdk = M('Tdks')->where($map)->find();
            $seodescription_info = unserialize($tdk['description']);
            $infopage = M('Page')->where(array('catid'=>$article['catid']))->find();
             //相册图集
            foreach ($_POST['photos_url'] as $key=>$url){
                $photourl=sp_asset_relative_url($url);
                $_POST['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
            }
            $article['photo']=json_encode($_POST['photo']);
            $article['seotitle']=$article['seotitle'];
            $article['seokeywords']=$article['seokeywords'];
            if($seodescription_info['is_write'] != 1){
                $in_desc['des1']=$_POST['des1'];
                $in_desc['desc_mo']=$_POST['desc_mo'];
                $in_desc['des2']=$_POST['des2'];
                $in_desc['des3']=$_POST['des3'];
                $in_desc['des4']=$_POST['des4'];
                $article['seodescription']=json_encode($in_desc);
               
            }else{
                $article['seodescription']=$article['seodescription'];
            }
            if($infopage){
                $article['title']=$article['title'];
                $article['intro']=$article['intro'];
                $article['content']=htmlspecialchars_decode($article['content']);
                $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
                $article['thumb']=$_POST['smeta']['thumb'];
                $article['updatetime']=time();
                $result=M('Page')->where(array('catid'=>$article['catid']))->save($article);
                if($result){
                    adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_SAVE').$article['title']);
                    $this->success("保存成功！");
                }else{
                    $this->error("保存失败！");
                }
            }else{
                $article['catid']=$article['catid'];
                $article['title']=$article['title'];
                $article['intro']=$article['intro'];
                $article['content']=htmlspecialchars_decode($article['content']);
                $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
                $article['thumb']=$_POST['smeta']['thumb'];
                $article['updatetime']=time();
                $result=M('Page')->add($article);
                if($result){
                    adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_ADD').$article['title']);
                    $this->success("添加成功！");
                }else{
                    $this->error("添加失败！");
                }

            }
        }else{
            //关键词设置
            $map['catid']=$catid;
            $tdk = M('Tdks')->where($map)->find();
            $seodescription_info = unserialize($tdk['description']);
            //单页信息
            $info = M('Page')->where(array('catid'=>$catid))->find();
            $info['photo'] = json_decode($info['photo'],true);
            if($seodescription_info['is_write'] == 0){
                $info_desc = json_decode($info['seodescription'],true);
                $descarr['des1']=$info_desc['des1'];
                $descarr['desc_mo']=$info_desc['desc_mo'];
                $descarr['des2']=$info_desc['des2'];
                $descarr['des3']=$info_desc['des3'];
                $descarr['des4']=$info_desc['des4'];
                $this->assign("descarr",$descarr);
            }
            $this->assign($info);
            $this->assign("catid",$catid);
            $this->assign("seodescription_info",$seodescription_info);
            $this->assign("list_desc_mo",$list_desc_mo);
            $this->display();
        }
        
    }
    
    function recycle(){
        $map['disabled'] = 0;
        $model = M('Model')->where($map)->select();
        foreach ($model as $key => $value) {
            $model_name=getModel($value['modelid'], 'tablename');
            $where1['is_del'] = 1;
            $list = M($model_name)->where($where1)->field('')->select();
            foreach ($list as $k => $val) {
                $list[$k]['modelid'] = $value['modelid'];
            }
            if($list){
                $alllist[$key] = $list;
                $alllist[$key]['modelid'] = $value['modelid'];
                $alllist[$key]['name'] = $value['name'];
            }
        }
 
        if(IS_POST){
                //添加开始时间
                $start_time = $_POST['start_time'];
                if (!empty($start_time)) {
                    $start_time = strtotime($start_time);
                    $where['inputtime'] = array("EGT", $start_time);
                    $this->assign('start_time', $_POST['start_time']);
                }
                //添加结束时间
                $end_time = $_POST['end_time'];
                if (!empty($end_time)) {
                    $end_time = strtotime($end_time);
                    $where['inputtime'] = array("LT", $end_time);
                    $this->assign('end_time', $_POST['end_time']);
                }
                if ($end_time > 0 && $start_time > 0) {
                    $where['inputtime'] = array(array('EGT', $start_time), array('LT', $end_time));
                }
                //搜索字段
                $searchtype = $_POST['searchtype'];
                //搜索关键字
                $keyword = $_POST['keyword'];
                if (!empty($keyword)) {
                    $this->assign("searchtype", $searchtype);
                    $this->assign("keyword", $keyword);
                    $type_array = array('title', 'description', 'username');
                    if ($searchtype < 3) {
                        $searchtype = $type_array[$searchtype];
                        $where[$searchtype] = array("LIKE", "%{$keyword}%");
                    } elseif ($searchtype == 3) {
                        $where["id"] = array("EQ", (int)$keyword);
                    }
                }
                //状态
                $status = $_POST['status'];
                if ($status) {
                    $where['status'] = array("EQ", $status);
                }
        }
        $modelid = $_POST['modelid']?$_POST['modelid']:I('modelid');
         
         
        if($alllist && !$modelid){
            foreach($alllist as $v){
                $newModel = $v['modelid'];
                break;
            }
            $this->redirect("Contentshow/recycle",array("modelid"=>$newModel) );
             
        }
        
        if($modelid){
            $model_name=getModel($modelid, 'tablename');
            $where['is_del'] = 1;
            $count =  M($model_name)->where($where)->count();
            $page = $this->page($count, 20);
            
            $list_per_model =  M($model_name)->where($where)->limit($page->firstRow . ',' . $page->listRows)->select();
            $this->assign('list_per_model',$list_per_model);
            $Page = $page->show('Admin');
            $this->assign('Page',$Page);
            $this->assign('modelid',$modelid);
        }
       
        //print_r($list_per_model);exit;
        $this->assign('alllist',$alllist);

        $this->display();
    }
    function art_recycle(){
        //搜索
        if(IS_POST){
                //添加开始时间
                $start_time = $_POST['start_time'];
                if (!empty($start_time)) {
                    $start_time = strtotime($start_time);
                    $where['inputtime'] = array("EGT", $start_time);
                    $this->assign('start_time', $_POST['start_time']);
                }
                //添加结束时间
                $end_time = $_POST['end_time'];
                if (!empty($end_time)) {
                    $end_time = strtotime($end_time);
                    $where['inputtime'] = array("LT", $end_time);
                    $this->assign('end_time', $_POST['end_time']);
                }
                if ($end_time > 0 && $start_time > 0) {
                    $where['inputtime'] = array(array('EGT', $start_time), array('LT', $end_time));
                }
                //搜索字段
                $searchtype = $_POST['searchtype'];
                //搜索关键字
                $keyword = $_POST['keyword'];
                if (!empty($keyword)) {
                    $this->assign("searchtype", $searchtype);
                    $this->assign("keyword", $keyword);
                    $type_array = array('title', 'description', 'username');
                    if ($searchtype < 3) {
                        $searchtype = $type_array[$searchtype];
                        $where[$searchtype] = array("LIKE", "%{$keyword}%");
                    } elseif ($searchtype == 3) {
                        $where["id"] = array("EQ", (int)$keyword);
                    }
                }
                //状态
                $status = $_POST['status'];
                if ($status) {
                    $where['status'] = array("EQ", $status);
                }
        }
        //信息总数
        if(!I('modelid')){
            if (empty($search)) {
                $count = $sum;
            } else {
                $count = M('Product')->where($where)->count();
            }
            $page = $this->page($count, 20);
            $this->assign('Page', $page->show());
        }
        $data = M('Article')->where($where)->select();
        $data_num = count($data);
        $i=0;
        foreach ($data as $key => $value) {
            if($value['listorder']){
                $order = 'listorder asc';continue;
            }else{
                ++$i;
            }
        }
        if($i == $data_num)$order = 'id desc';
        $where['is_del'] = 1;
        $data = M('Article')->where($where)->limit($page->firstRow . ',' . $page->listRows)->order($order)->select();
        $this->assign($catInfo)
            ->assign('catid', $this->catid)
            ->assign('data', $data);

        $this->display();

    }
    //放入回收站
    public function delete() {
        if(I('catid')){
            $catid=$this->catid=I('catid');
            $is_del = I('is_del');
        }else{
            $catid=$this->catid=$_POST['catid'];
            $is_del = $_POST['is_del'];
        }
        
       
        //if($this->auth_con($catid,"delete")){$this->error("亲没有删除的权限哦！");}
        if (IS_POST) {
            $Categorys = getCategory($this->catid);
            if (empty($Categorys)) {
                $this->error("该栏目不存在！");
            }
            //模型ID
            $modelid = $Categorys['modelid'];
            if (empty($_POST['ids'])) {
                $this->error('没有信息被选中！');
            }
            $model = \Content\Model\ContentModel::getInstance($modelid);
            foreach ($_POST['ids'] as $id) {
                //检查是否锁定
                if (false === $model->locking($this->catid, $id)) {
                    $this->error($model->getError());
                }
                //放入回收站
                $model_name=getModel($modelid, 'tablename');
                $w['id'] = $id;
                $data['is_del'] = $is_del;
                M($model_name)->where($w)->save($data);
                
            }
            adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_DEL').$Categorys['catname'],L('ADMINLOG_ZDPRO'));
            if($is_del == 1){
                $this->success('批量删除成功！');
            }else{
                $this->success('批量还原成功！');
            }
            
        } else {
            $id = I('get.id', 0, 'intval');
            $Categorys = getCategory($catid);
            if (empty($Categorys)) {
                $this->error('该栏目不存在！');
            }
            //模型ID
            $modelid = $Categorys['modelid'];
            $model = \Content\Model\ContentModel::getInstance($modelid);
            //检查是否锁定
            if (false === $model->locking($this->catid, $id)) {
                $this->error($model->getError());
            }
            //放入回收站
            $model_name=getModel($modelid, 'tablename');
            $w['id'] = $id;
            $data['is_del'] = $is_del;
            $rel = M($model_name)->where($w)->save($data);
            if ($rel) {
                $model_name=getModel($modelid, 'tablename');
                $t_info = M($model_name)->where(array('id'=>$id))->find();
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_DEL').$t_info['title']);
                if($is_del == 1){
                    $this->success('删除成功！');
                }else{
                    $this->success('还原成功！');
                }
                
            } else {
                if($is_del == 1){
                    $this->error('删除失败！');
                }else{
                    $this->error('还原失败！');
                }
            }
        }

    }
    
    /* 
     * 批量恢复内容
     *  
     * @author cx
     * @time 20161028
     * @param modelid 模型ID
     * @param ids     要还原的内容ID
     *  
     *  */
    
    public function modelRestore(){
        $modelid = I("post.modelid","","int");
        $ids = I("post.ids");
        
        $model_name = getModel($modelid ,"tablename");
        $model = \Content\Model\ContentModel::getInstance($modelid);
        
        $total = count($ids);
        $a= 0;
        $b= 0; 
        $is_del =0;
        
         
        foreach($ids as $value){
            
            $info = M($model_name)->where(" id = '".$value."'")->find();
            //检查是否锁定
            if (false === $model->locking($info['catid'], $value)) {
                 $b++;
            }else{
                $status = M($model_name)->where("id = '".$value."'")->save(array("is_del"=>$is_del));
                if($status){
                    $a++;
                }else{
                    $b++;
                }
            }
        }
        $this->success("总共恢复".$total."个，成功".$a."个， 失败".$b."个");
    }
    
    
    //删除
    public function delete_c() {
        if(I('catid')){
            $catid=$this->catid=I('catid');
        }else{
            $catid=$this->catid=$_POST['catid'];
        }
        
        
        if (IS_POST) {
            //模型ID
            $modelid = $_POST['modelid'];
            if (empty($_POST['ids'])) {
                $this->error('没有信息被选中！');
            }
            $model = \Content\Model\ContentModel::getInstance($modelid);
            $model_name=getModel($modelid, 'tablename');
            
            $total =count($_POST['ids']);
            $a=0;
            $b=0;

            foreach ($_POST['ids'] as $id) {
                $info = M($model_name)->where("id ='".$id."'")->find();
                if(false === $model->locking($info['catid'], $id)){
                    $b++;
                }else{
                    $map_ss['id'] = $id;
                    $get_info = M($model_name)->where($map_ss)->find();
                    $cons = new \Content\Lib\Content();
                    $cons->delete($id, $get_info['catid']);
                    
                    $a++;
                }

            }
            adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_DEL'),L('ADMINLOG_ZDPRO'));
            $this->success("总共删除".$total."个，成功".$a."个，失败".$b."个");
        } else {
            $id = I('get.id', 0, 'intval');
            $Categorys = getCategory($catid);
            if (empty($Categorys)) {
                $this->error('该栏目不存在！');
            }
            //模型ID
            $modelid = $Categorys['modelid'];
            $model = \Content\Model\ContentModel::getInstance($modelid);
            //检查是否锁定
            if (false === $model->locking($this->catid, $id)) {
                $this->error($model->getError());
            }
            $cons = new \Content\Lib\Content();
            if ($cons->delete($id, $this->catid)) {
                $model_name=getModel($modelid, 'tablename');
                $t_info = M($model_name)->where(array('id'=>$id))->find();
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_DEL').$t_info['title']);
                $this->success('删除成功！');
            } else {
                $this->error('删除失败！');
            }
        }
    }
    //排序
    public function listorder() {
        $listorders = $_POST['listorders'];
        $this->catid = I('get.catid', 0, 'intval');
        if($this->auth_con($this->catid,'listorder')){$this->error("亲没有排序的权限哦！");}
        if (is_array($listorders)) {
            $modelid = getCategory($this->catid, 'modelid');
            if (empty($modelid)) {
                $this->error('模型不存在！');
            }
            $db = \Content\Model\ContentModel::getInstance($modelid);
            foreach ($listorders as $id => $v) {
                $db->where(array('id' => $id))->save(array('listorder' => $v));
            }
            adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_ORDER').$t_info['title']);
            $this->success('更新成功！', U('classlist', array('catid' => $this->catid)));
        } else {
            $this->error('参数错误！');
        }
    }
    //文章审核
    public function public_check() {
        $this->catid = $_POST['catid'];
        if($this->auth_con(I('catid'),'auth')){$this->error("亲没有审核的权限哦！");}
        if ($_POST) {
            $this->Content = new \Content\Lib\Content();
            $ids = $_POST['ids'];
            if (!$ids) {
                $this->error('没有信息被选中！');
            }
            foreach ($ids as $id) {
                $this->Content->check($this->catid, $id, 99);
            }
            adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_AUDIT'));
            $this->success('审核成功！');
        } else {
            $id = I('get.id', 0, 'intval');
            if (!$id) {
                $this->error('没有信息被选中！');
            }
            if ($this->Content->check($this->catid, $id, 99)) {
                $cateinfo = getCategory($this->catid);
                $info = getModel($cateinfo['modelid'],'tablename');
                $data_info = M($info)->where(array('id'=>$id))->find();
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_AUDIT').$data_info['title']);
                $this->success('审核成功！');
            } else {
                $this->error('审核失败！');
            }
        }
    }
    //取消审核
    public function public_nocheck() {
        $this->Content = new \Content\Lib\Content();
        $this->catid = I('catid', 0, 'intval');
        if($this->auth_con(I('catid'),'auth')){$this->error("亲没有取消审核的权限哦！");}
        if (IS_POST) {
            $ids = $_POST['ids'];
            if (!$ids) {
                $this->error('没有信息被选中！');
            }
            foreach ($ids as $id) {
                $this->Content->check($this->catid, $id, 1);
            }
            adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_NOAUDIT'));
            $this->success('取消审核成功！');
        } else {
            $id = I('get.id', 0, 'intval');
            if (!$id) {
                $this->error('没有信息被选中！');
            }
            if ($this->Content->check($this->catid, $id, 1)) {
                $cateinfo = getCategory($this->catid);
                $info = getModel($cateinfo['modelid'],'tablename');
                $data_info = M($info)->where(array('id'=>$id))->find();
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_NOAUDIT').$data_info['title']);
                $this->success('取消审核成功！');
            } else {
                $this->error('取消审核失败！');
            }
        }
    }
    //批量移动
    function move(){
        $catid = I('get.catid', '', 'intval');
        if($this->auth_con($catid,'remove')){$this->error("亲没有移动的权限哦！");}
        $this->Content = new \Content\Lib\Content();
        if (IS_POST && isset($_POST['fromtype'])) {
            if (!$catid) {
                $this->error("请指定栏目！");
            }
            //移动类型
            $fromtype = I('post.fromtype', '', 'intval');
            //需要移动的信息ID集合
            $ids = $_POST['ids'];
            //需要移动的栏目ID集合
            $fromid = $_POST['fromid'];
            //目标栏目
            $tocatid = I('post.tocatid', '', 'intval');
            if (!$tocatid) {
                $this->error("目标栏目不正确！");
            }
            switch ($fromtype) {
                //信息移动
                case 0:
                    if ($ids) {
                        if ($tocatid == $catid) {
                            $this->error('目标栏目和当前栏目是同一个栏目！');
                        }
                        $modelid = getCategory($tocatid, 'modelid');
                        if (!$modelid) {
                            $this->error('该模型不存在！');
                        }
                        $model = \Content\Model\ContentModel::getInstance($modelid);
                        if (!$ids) {
                            $this->error('请选择需要移动信息！');
                        }
                        $ids = array_filter(explode(',', $_POST['ids']), 'intval');
                        //删除静态文件
                        
                        foreach ($ids as $sid) {
                            //$maps['catid'] = $catid;
                            $maps['id'] = $sid;
                            $data = $model->where($maps)->find();
                            $this->Content->data($data)->deleteHtml();
                            $model->where($maps)->save(array('catid' => $tocatid));
                            //$data['catid'] = $tocatid;
                            //$urls = $this->Url->show($data);
                            //$model->where(array('catid' => $catid, 'id' => $sid))->save(array('catid' => $tocatid, 'url' => $urls['url']));
                        }
                        $this->success('移动成功！');
                    } else {
                        $this->error('请选择需要移动的信息！');
                    }
                    break;
                //栏目移动
                case 1:
                    if (!$fromid) {
                        $this->error('请选择需要移动的栏目！');
                    }
                    $where = array();
                    $where['catid'] = array('IN', $fromid);
                    $modelid = getCategory($catid, 'modelid');
                    if (!$modelid) {
                        $this->error("该模型不存在！");
                    }
                    $model = \Content\Model\ContentModel::getInstance($modelid);
                    //进行栏目id更改
                    if ($model->where($where)->save(array('catid' => $tocatid, 'url' => ''))) {
                        $this->success('移动成功，请使用《批量更新URL》更新新的地址！！');
                    } else {
                        $this->error('移动失败！');
                    }
                    break;
                default:
                    $this->error('请选择移动类型！');
                    break;
            }
        } else {
            $ids = I('request.ids', '', '');
            $ids = is_array($ids) ? implode(",", $ids) : $ids;
            $catid = I('get.catid', '', 'intval');
            if (!$catid) {
                $this->error("请指定栏目！");
            }
            $modelid = getCategory($catid, 'modelid');
            $tree = new \Common\Lib\Tree();
            $tree->icon = array('&nbsp;&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;';
            $categorys = array();

            $result=S("Category");

            $newcate=array();
            foreach ($result as $m){
                $newcate[$m['catid']]=$m;
            }$categorysList=$newcate;
            foreach ($categorysList as $cid => $r) {
                $r = getCategory($r['catid']);
                if ($r['type'])
                    continue;
                if ($modelid && $modelid != $r['modelid'] && $r['child'] == 0)
                    continue;
                
                //$r['disabled'] = $r['child'] ? 'disabled' : '0';
                $count_arrchildid = count(explode(',', $r['arrchildid']));
                if($count_arrchildid > 1){
                    $r['disabled'] = 'disabled';
                }else{
                    $r['disabled'] = '0';
                }
                
                $r['selected'] = $cid == $catid ? 'selected' : '';
                $categorys[$cid] = $r;
            }
            $str = "<option value='\$catid' \$selected \$disabled>\$spacer \$catname</option>";
            $tree->init($categorys);
            $string .= $tree->get_tree(0, $str);

            $str = "<option value='\$catid'>\$spacer \$catname</option>";
            $source_string = '';
            $tree->init($categorys);
            $source_string .= $tree->get_tree(0, $str);

            $this->assign("ids", $ids);
            $this->assign("string", $string);
            $this->assign("source_string", $source_string);
            $this->assign("catid", $catid);
            $this->display();
        }

    }

    //批量置顶
    public function top(){
        $this->catid = I('get.catid', 0, 'intval');
        $istop = I('get.istop')?I('get.istop'):0;
        $untop = I('get.untop')?I('get.untop'):0;
        $Categorys = getCategory($this->catid);
        if (empty($Categorys)) {$this->error('该栏目不存在！');}
        if (IS_POST) {
            $ids = $_POST['ids'];
            if(!$ids){$this->error('没有信息被选中！');}
            $modelid=$Categorys['modelid'];
            $model_name=getModel($modelid, 'tablename');
            $model=M($model_name);
            if($istop){
                foreach($ids as $val){
                    $con['istop']=1;
                    $info = $model->where(array("id"=>$val))->save($con);
                }
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_TOP'));
                $this->success('置顶成功！', U('classlist', array('catid' => $this->catid)));
            } 
            if($untop){
                foreach($ids as $val){
                    $con['istop']=0;
                    $info = $model->where(array("id"=>$val))->save($con);
                }
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_NOTOP'));
                $this->success('取消置顶成功！', U('classlist', array('catid' => $this->catid)));
            }
        }
    }
     //单个是否置顶
    function istopajax(){
        $this->catid = I('get.catid', 0, 'intval');
        $istop = I('get.istop')?I('get.istop'):0;
        $Categorys = getCategory($this->catid);
        $id = I('get.id');
        if (empty($Categorys)) {$this->error('该栏目不存在！');}
        $modelid=$Categorys['modelid'];
        $model_name=getModel($modelid, 'tablename');
        $model=M($model_name);
        if($istop){
            $con['istop']=1;
            $data['msg']='是';
            $data['istop']=0;

        }else{
           $con['istop']=0; 
           $data['msg']='否';
           $data['istop']=1;
        }
     
        $rel = $model->where(array("id"=>$id))->save($con);
        if($rel){
            $data['status']=1;
        }else {
            $data['status']=0;
        }
        $this->ajaxReturn($data);
        

    }
    //批量推荐推荐
    function recommend(){
        $this->catid = I('get.catid', 0, 'intval');
        if($this->auth_con($catid,'push')){$this->error("亲没有推荐的权限哦！");}
        $recommend = I('get.recommend')?I('get.recommend'):0;
        $unrecommend = I('get.unrecommend')?I('get.unrecommend'):0;
        $Categorys = getCategory($this->catid);
        if (empty($Categorys)) {$this->error('该栏目不存在！');}
        if (IS_POST) {
            $ids = $_POST['ids'];
            if(!$ids){$this->error('没有信息被选中！');}
            $modelid=$Categorys['modelid'];
            $model_name=getModel($modelid, 'tablename');
            $model=M($model_name);
            if($recommend){
                foreach($ids as $val){
                    $con['recommend']=1;
                    $info = $model->where(array("id"=>$val))->save($con);
                }
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_TUIJIAN'));
                $this->success('推荐成功！', U('classlist', array('catid' => $this->catid)));
            } 
            if($unrecommend){
                foreach($ids as $val){
                    $con['recommend']=0;
                    $info = $model->where(array("id"=>$val))->save($con);
                }
                adminlog($_SESSION['ADMIN_ID'],L('ADMINLOG_PILIANG').L('ADMINLOG_NOTUIJIAN'));
                $this->success('取消推荐成功！', U('classlist', array('catid' => $this->catid)));
            }
        }

        
    }
    //单个推荐
    function recommendajax(){
        $this->catid = I('get.catid', 0, 'intval');
        $recommend = I('get.recommend')?I('get.recommend'):0;
        $Categorys = getCategory($this->catid);
        $id = I('get.id');
        if (empty($Categorys)) {$this->error('该栏目不存在！');}
        $modelid=$Categorys['modelid'];
        $model_name=getModel($modelid, 'tablename');
        $model=M($model_name);
        if($recommend){
            $con['recommend']=1;
            $data['msg']='是';
            $data['recommend']=0;

        }else{
           $con['recommend']=0; 
           $data['msg']='否';
           $data['recommend']=1;
        }
     
        $rel = $model->where(array("id"=>$id))->save($con);
        if($rel){
            $data['status']=1;
        }else {
            $data['status']=0;
        }
        $this->ajaxReturn($data);

    }
    //相关文章选择
    public function public_relationlist() {
        $modelid = I('get.modelid', 0, 'intval')?I('get.modelid', 0, 'intval'):$_POST['modelid'];
        /*if (IS_POST) {//
            $modelid = getCategory($this->catid, 'modelid');
            $_POST['modelid'] = $modelid;
            $this->redirect('public_relationlist', $_POST);
        }*/
        
        if (empty($modelid)) {
            $this->error('缺少参数！');
        } else {
            //分类
            $tree = new \Common\Lib\Tree();
            $tree->icon = array('&nbsp;&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;';
            $categorys = array();

            $result=S("Category");

            //print_r($result);exit;
            $newcate=array();
            foreach ($result as $m){
                $newcate[$m['catid']]=$m;
            }$categorysList=$newcate;
            foreach ($categorysList as $cid => $r) {
                $r = getCategory($r['catid']);
                if ($r['type'])
                    continue;
                if ($modelid && $modelid != $r['modelid'] && $r['child'] == 0)
                    continue;

                $r['disabled'] = $r['child'] ? 'disabled' : '';
                $r['selected'] = $cid == $catid ? 'selected' : '';
                $categorys[$cid] = $r;
            }
            $str = "<option value='\$catid' \$disabled>\$spacer \$catname</option>";
            $source_string = '';
            $tree->init($categorys);
            $source_string .= $tree->get_tree(0, $str);
            $this->assign("Formcategory", $source_string);
            
            $model = \Content\Model\ContentModel::getInstance($modelid);
            $where = array();
            $catid = $_POST['catid'];
            if ($catid) {
                $where['catid'] = $catid;
            }
            $where['status'] = 99;
            if (isset($_POST['keywords'])) {
                $keywords = trim($_POST['keywords']);
                $field = $_POST['searchtype'];
                if (in_array($field, array('id', 'title', 'keywords', 'description'))) {
                    if ($field == 'id') {
                        $where['id'] = array('eq', $keywords);
                    } else {
                        $where[$field] = array('like', '%' . $keywords . '%');
                    }
                }
            }
            $count = $model->where($where)->count();
            $page = $this->page($count, 12);
            $data = $model->where($where)->limit($page->firstRow . ',' . $page->listRows)->order(array('id' => "DESC"))->select();
            $this->assign('data', $data);
            $this->assign('Page', $page->show());
            $this->assign('modelid', $modelid);
            $this->assign('post', $_POST);
            $this->assign('modelid', $modelid);
            $this->display('relationlist');
        }
    }

    //加载相关文章列表 
    public function public_getjson_ids() {
        $istop = I('get.istop');
        $id = I('get.id', 0, 'intval');
       
        $this->ajaxReturn(array('data' => $infos, 'status' => 1));
    }
   
    function seo_random(){
        $catid = I('get.catid', 0, 'intval');
        $name = I('get.name');
        $map['catid']=$catid;
        $tdk = M('Tdks')->where($map)->find();
        if($tdk){
            $seotitles_arr = explode(',', unserialize($tdk['title']));
            $seokeywords_arr = explode(',', unserialize($tdk['keywords']));
            $seodescription_arr = unserialize($tdk['description']);
            $title = array_rand($seotitles_arr,1);
            $keywords = array_rand($seokeywords_arr,1);
            $arr['title']=str_replace("*",$name,$seotitles_arr[$title]);
            $arr['keywords']=str_replace("*",$name,$seokeywords_arr[$title]);
        }else{
            $tdk_info = M('TksLibrary')->select();
            foreach ($tdk_info as $key => $value) {
                $keywords_all[] = $value['keywords'];
            }
            $title = array_rand($keywords_all,1);
            $keywords = array_rand($keywords_all,1);
            $arr['title']=str_replace("*",$name,$keywords_all[$title]);
            $arr['keywords']=str_replace("*",$name,$keywords_all[$keywords]);
        }
        if($seodescription_arr['iswrite'] == 0){
            $option=M("Options")->where("option_name='site_options'")->find();
            $option_info =(array)json_decode($option['option_value']);
            $list_title_mo = $option_info['list_title_h'];//title默认部分
            $list_desc_mo = $option_info['list_desc_z'];//description句型默认部分
            $arr['description']=$list_desc_mo;
        }else{
            $arr['description']=$seodescription_arr['description_j'];
        }
        $arr['status']=1;
        $this->ajaxReturn($arr);
    }
    //权限
    function auth_con($catid,$action){

        $catid = $catid;
        $user_login = $_SESSION['ADMIN_ID'];


        if($user_login == 1){
            return false;
        }else{
            $role_user = M("RoleUser")->where(array("user_id"=>$user_login))->select();
            foreach ($role_user as $key => $value) {
                $role[] = $value['role_id'];
            }

            if(in_array(1 , $role)){
                return false;
            }

            $role = implode(',', $role);
            $map['roleid']=array(array('in',$role));
            $map['catid']=$catid;
            $map['action']=$action;
            $category_priv = M("CategoryPriv")->where($map)->find();
            
            if(empty($category_priv)){
                return true;
            }else{
                return false;
            }
        }
       
    }
    //检测标题是否存在
    public function public_check_title() {
        $title = I('get.data');
        $catid = I('get.catid');
        if (empty($title)) {
            $this->ajaxReturn(array('status' => 1, 'info' => '标题没有重复！'));
            return false;
        }
        $count = \Content\Model\ContentModel::getInstance(getCategory($catid, 'modelid'))->where(array('title' => $title))->count();
        if ($count > 0) {
            $this->ajaxReturn(array('status' => 0, 'info' => '标题有重复！'));
        } else {
            $this->ajaxReturn(array('status' => 1, 'info' => '标题没有重复！'));
        }
    }
    //
    function sortorder(){
        if(IS_POST){
            $post = I('post.');
            $map['modelid'] = $post['modelid'];
            $map['catid'] = $post['catid'];
            $info = M('Sortorder')->where($map)->find();
            if($info){
                $rel = M('Sortorder')->where($map)->save($post);
            }else{
                $rel = M('Sortorder')->add($post);
            }
            if($rel){
                $this->success('排序设置成功');
            }else{
                $this->error('排序设置失败');
            }
        }
    }
    // 热销产品
    function hot_product(){
        $map['istop'] = 1;
        $map['is_del'] = 0;
        $map['status'] = 99;
        $count = M('Product')->where($map)->count();
        $page = $this->page($count, 20);
        $info = M('Product')->where($map)->limit($page->firstRow . ',' . $page->listRows)->order('listorder asc,id desc')->select();
        $this->assign('info',$info);
        $this->assign("Page", $page->show('Admin'));
        $this->display();
    }
    // 最新产品
    function new_product(){
        $map['recommend'] = 1;
        $map['is_del'] = 0;
        $map['status'] = 99;
        $count = M('Product')->where($map)->count();
        $page = $this->page($count, 20);
        $info = M('Product')->where($map)->limit($page->firstRow . ',' . $page->listRows)->order('listorder asc,id desc')->select();
        $this->assign('info',$info);
        $this->assign("Page", $page->show('Admin'));
        $this->display();
    }
    //复制
    public function copy(){
        if($_POST){
            $Categorys = getCategory($_POST['catid']);
            $modelname = getModel($Categorys['modelid'],'tablename');
            $map['id'] = $_POST['id'];
            $info = M($modelname)->where($map)->find();
            $info_data = M($modelname.'_data')->where($map)->find();
            
            foreach($_POST as $key=>$value){
                preg_match('/^category/',$key,$rel);
                if($rel){
                   $num = explode('category',$key);
                   $numrel[] = $num[1];
                }
            }
            foreach ($numrel as $key => $val) {
               $arr[$val]['category'] = $_POST['category'.$val];
               $arr[$val]['title'] = $_POST['title'.$val];
               $arr[$val]['seourl'] = $_POST['seourl'.$val];
            }
            foreach ($arr as $k => $v) {
                if(!$v['category']){
                    $this->error("分类为必填项！",U('Content/Contentshow/classlist',array('catid'=>$_POST['catid'])));
                }
                $_POST['updatetime'] = time();
                $_POST['inputtime'] = time();
                $data['catid'] = $v['category'];
                $data['title'] = $v['title'];
                $data['seourl'] = $v['seourl'];
                $data['updatetime'] = time();
                $data['inputtime'] = time();
                $result=array_diff_key($info,$_POST);
                $data = array_merge($result,$data);
                $result_data=array_diff_key($info_data,$_POST);
               
                if($v['seourl']){
                    //seourl 检查重复
                    $checkseourl = M($modelname)->where(" seourl='".$v['seourl']."'")->find();
                    if($checkseourl){
                        $this->error("seourl已经存在！",U('Content/Contentshow/classlist',array('catid'=>$_POST['catid'])));
                    
                    }
                    $pro_id = M($modelname)->add($data);
                }else{
                    $pro_id = M($modelname)->add($data);
                    if($pro_id){
                        $where['id'] = $pro_id;
                        $con['seourl'] = $pro_id;
                        M($modelname)->where($where)->save($con);
                    }
                }
                $f['id'] = $pro_id;
                $result_dataf = array_merge($result_data,$f);
                M($modelname.'_data')->add($result_dataf);
            }
            $this->success('复制成功',U('Content/Contentshow/classlist',array('catid'=>$_POST['catid'])));
        }else{
            $get = I('get.');
            $id = $get['id'];
            $Categorys = getCategory($get['catid']);
            $map['modelid'] = $Categorys['modelid'];
            $result = M('Category')->where($map)->select();
            //分类
            $tree = new \Common\Lib\Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            //print_r($result);exit;
            $newmenus=array();
            foreach ($result as $m){
                $newmenus[$m['catid']]=$m;
            }$result=$newmenus;
            foreach ($result as $n=> $r) {
                    if($r['type'] != 2){
                        if ($r['child'] == '1') {
                             $result[$n]['disabled'] = "disabled";
                        } else {
                            $result[$n]['disabled'] = "";
                        }
                        $result[$n]['level'] = $this->_get_level($r['catid'], $newmenus);
                        $result[$n]['parentid_node'] = ($r['parentid']) ? " class='child-of-node-".$r['parentid']."'" : '';
                        $result[$n]['catname'] = $r['catname'];
                    }
            }
            $tree->init($result);
            $str = "<option value='\$catid' \$disabled>\$spacer \$catname</option>";
            $categorys = $tree->get_tree(0, $str);
            $this->assign('category',$categorys);
            $this->assign('get',$get);
            $this->display();

        }
        
    }
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
    
        if ($array[$id]['parentid']==0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid']==$id){
            return  $i;
        }else{
            $i++;
            return $this->_get_level($array[$id]['parentid'],$array,$i);
        }
    
    }
   
}