<?php
/**
 * [LJCMS] (C)2012-2099 LJdev,Inc.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2014.04.03
*/

class control extends salebase {
    
	private $_comeurl = NUll;
    private $_urlitem = NULL;
    
    private $tid = NULL;
    
    private $scatid = NULL;
    
    private $sname = NULL;
    
    private $modtitle = NULL;
    
    private $modalias = NULL;
    
	
    public function action_run() {
        $searchsql = "";
        $searchsql .= " AND v.treeid='".intval(2)."'";
        $scatid=$_REQUEST['catid'];
        $sname=$_REQUEST['title'];
        if ($scatid>0) {
            $m = parent::model('category', 'am');
            $childs = $m->getChildIDs($scatid);
            if (!empty($childs)) {
                $searchsql .= " AND v.catid IN (".$childs.$scatid.")";
            }
            else {
                $searchsql .= " AND v.catid='".$scatid."'";
            }
            unset($m);
        }
        if (!empty($sname)) {
            $searchsql .= " AND lower(v.productname) LIKE '%".strtolower($sname)."%'";
        }
        $model = parent::model('product', 'am');
        list($total, $data) = $model->getList(array('page'=>$this->page, 'pagesize'=>$this->pagesize, 'searchsql'=>$searchsql));
        $url = XRequest::getPhpSelf();
        $url .= '?c=Product';
        parent::loadLib('mod');
        $category_select = XMod::selectNodeEnableChilds($this->tid, $this->scatid ,'scatid', '所有分类');
        $var_array = array(
            'page'=>$this->page,
            'nextpage'=>$this->page+1,
            'prepage'=>$this->page-1,
            'pagecount'=>ceil($total/$this->pagesize),
            'pagesize'=>$this->pagesize,
            'total'=>$total,
            'showpage'=>XPage::sale($total, $this->pagesize, $this->page, $url, 10),
            'urlitem'=>$this->_urlitem,
            'comeurl'=>$this->_comeurl,
            'tid'=>$this->tid,
            'sname'=>$this->sname,
            'product'=>$data,
            'category_select'=>$category_select,
            'modtitle'=>$this->modtitle,
            'sname'=>$sname,
            'scatid'=>$scatid,
        );
        unset($model);
		TPL::assign($var_array);
		TPL::display($this->cptpl.'product/product.tpl');
	}
    
    
   
    
    
    public function action_add() {   
        $var_array = array(
          'timeline'=>time(),
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl.'product/add.tpl');
    }
    
    
    public function action_edit() {
       
        
        $id = XRequest::getInt('id');
        $this->_validID($id);
        $model = parent::model('product', 'am');
        list($data) = $model->getData($id);
        if (empty($data)) {
            XHandle::halt('对不起，读取数据不存在！', '', 1);
        }
        else {

            
            parent::loadLib('mod');
            $model = parent::model('modattr', 'am');
            $modattr = $model->getAttrList($this->modalias, $this->tid);
            foreach($modattr as $key=>$value){
                $extvalue = '';
                $extvalue = $model->getAttrExtValue($this->modalias, $value['aid'], $id);
                
                if ($value['inputtype'] == 'radio') {
                    $modattr[$key]['attr_select'] = XMod::attrRadioBox('attr_'.$value['aid'], $value['attrvalue'], $extvalue);
                }
                
                elseif ($value['inputtype'] == 'checkbox') {
                    $modattr[$key]['attr_select'] = XMod::attrCheckBox('attr_'.$value['aid'], $value['attrvalue'], $extvalue);
                }
                
                elseif ($value['inputtype'] == 'select') {
                    $modattr[$key]['attr_select'] = XMod::attrOptions('attr_'.$value['aid'], $value['attrvalue'], $extvalue); 
                }
                else {
                    $modattr[$key]['attr_select'] = '';
                }
                $modattr[$key]['extvalue'] = $extvalue;
            } 
            $var_array = array(
                'product'=>$data,
                'id'=>$id,
                'page'=>$this->page,
                'comeurl'=>$this->_comeurl,
                'category_select'=>XMod::selectNodeEnableChilds($this->tid, $data['catid'], 'catid'),
                'modtitle'=>$this->modtitle,
                'tid'=>$this->tid,
                'timeline'=>time(),
                'modattr'=>$modattr,
            );
            
            TPL::assign($var_array);
            TPL::display($this->cptpl.'product/edit.tpl');
        }
        unset($model);
    }
    
    
    public function action_saveadd() {
        $attrs=array();
        $args=$_POST;
        $args['treeid']='2';
        $args['lang']='cn';
        $args['addtime']= time();
        $model = parent::model('product', 'am');
        $result = $model->doAdd($args,$attrs);
        unset($model);
        if (true === $result) {
        	$res['code']=1;
            $res['msg']="添加成功";
            echo json_encode($res);die;
        }
        else {
        	$res['code']=0;
            $res['msg']="操作失败";
            echo json_encode($res);die;
        }
        
	}
    
    
    public function action_saveedit() {
         $attrs=array();
         $args=$_POST;
         $id=$_POST['id'];
        unset($args['id']);
        $model = parent::model('product', 'am');
        $result = $model->doEdit($id, $args, $attrs);
        unset($model);
                if (true === $result) {
                    	$res['code']=1;
                        $res['msg']="修改成功";
                        echo json_encode($res);die;
                }
                else {
                    	$res['code']=0;
                        $res['msg']="操作失败";
                        echo json_encode($res);die;
                }
    }
    
    
    public function action_del() {
        $ids = XRequest::getArray('id');
        $ids = substr($ids,0,strlen($ids)-1); 
        $this->_validID($ids);
        $array_id = explode(",", $ids);
      //  print_r($array_id);die;
        $model = parent::model('product', 'am');
        foreach ($array_id as $v){
            $result = $model->doDel($v);     
        }  
        unset($model);
        
        if (true === $result) {
                        $res['code']=1;
                        $res['msg']="删除成功";
                        echo json_encode($res);die;
        }
        else {
            $res['code']=0;
                        $res['msg']="操作失败";
                        echo json_encode($res);die;
        }
         
    }
    
    
    public function action_update() {
        $args = XRequest::getGpc(array('id', 'type'));
        $model = parent::model('product', 'am');
        $model->doUpdate(intval($args['id']), trim($args['type']));
        unset($model);
    }
    
    
    private function _validAdd() {
        $args = XRequest::getGpc(array(
            'treeid', 'catid', 'productsn', 'productname', 'oprice', 'bprice',
            'thumbfiles', 'uploadfiles', 'summary',
            'tags', 'metakeyword', 'metadescription',
            'istop', 'elite', 'flag', 'addtime', 
            'hits', 'linktype', 'linkurl', 'purview', 'tplname', 
            
        ));
        $content = XRequest::getArgs('content', '', false);
        
        if (empty($args['productname'])) {
            XHandle::halt('请填写名称', '', 1);
        }
        if (!empty($args['tplname'])) {
            if (false === XValid::isSpChar($args['tplname'])) {
                XHandle::halt('模板文件格式不正确', '', 1);
            }
        }
        $args['treeid'] = intval($args['treeid']);
        $args['catid'] = intval($args['catid']);
        $args['oprice'] = floatval($args['oprice']);
        $args['bprice'] = floatval($args['bprice']);
        $args['istop'] = intval($args['istop']);
        $args['elite'] = intval($args['elite']);
        $args['flag'] = intval($args['flag']);
        $args['hits'] = intval($args['hits']);
        $args['linktype'] = intval($args['linktype']);
        $args['purview'] = intval($args['purview']);
        $args['addtime'] = strtotime(trim(str_replace('&nbsp;', ' ', $args['addtime'])));
        if ($args['catid'] == 0) {
            $args['catid'] = $args['treeid'];
        }
        $args['content'] = $content;
         
        $albums = $this->_getAlbums();
        
        $args['albums'] = $albums;
        return array($args, $this->_getAttrValue());
    }
    
    
    private function _validEdit() {
        $id = XRequest::getInt('id');
        $args = XRequest::getGpc(array(
            'treeid', 'catid', 'productsn', 'productname', 'oprice', 'bprice',
            'thumbfiles', 'uploadfiles', 'summary',
            'tags', 'metakeyword', 'metadescription',
            'istop', 'elite', 'flag', 'addtime',
            'hits', 'linktype', 'linkurl', 'purview', 'tplname', 
            
        ));
        $content = XRequest::getArgs('content', '', false);
        if ($id<1) {
            XHandle::halt('ID丢失', '', 1);
        }
        
        if (empty($args['productname'])) {
            XHandle::halt('请填写名称', '', 1);
        }
        if (!empty($args['tplname'])) {
            if (false === XValid::isSpChar($args['tplname'])) {
                XHandle::halt('模板文件格式不正确', '', 1);
            }
        }
        
        $args['treeid'] = intval($args['treeid']);
        $args['catid'] = intval($args['catid']);
        $args['oprice'] = floatval($args['oprice']);
        $args['bprice'] = floatval($args['bprice']);
        $args['istop'] = intval($args['istop']);
        $args['elite'] = intval($args['elite']);
        $args['flag'] = intval($args['flag']);
        $args['hits'] = intval($args['hits']);
        $args['linktype'] = intval($args['linktype']);
        $args['purview'] = intval($args['purview']);
        $args['addtime'] = strtotime(trim(str_replace('&nbsp;', ' ', $args['addtime'])));
        if ($args['catid'] == 0) {
            $args['catid'] = $args['treeid'];
        }
        
        $albums = $this->_getAlbums();
        
        $args = array_merge($args, array('content'=>$content, 'albums'=>$albums));
        return array($id, $args, $this->_getAttrValue());
    }
    
    
    private function _validID($id) {
        if (empty($id)) {
            XHandle::halt('ID丢失，请选择要操作的ID', '', 1);
        }
    }
    
    
    private function _getAttrValue() {
        $array = array();
        
        $m = parent::model('modattr', 'am');
        $attrdata = $m->getAttrList($this->modalias, $this->tid);
        unset($m);
        foreach($attrdata as $key=>$value) {
            
            if ($value['inputtype'] == 'checkbox') {
                $arr = XRequest::getArray('attr_'.$value['aid']);
                $array_val = '';
                for($ii=0; $ii<count($arr); $ii++){
                    $array_val .= trim($arr[$ii]).',';
                }
                if (!empty($array_val)) {
                    $array_val = substr($array_val, 0, (strlen($array_val)-1));
                }
                $array[] = array(
                    'aid'=>$value['aid'],
                    'extvalue'=>$array_val,
                );
            }
            else {
                $array[] = array(
                    'aid'=>$value['aid'],
                    'extvalue'=>XRequest::getArgs('attr_'.$value['aid']),
                );
            }
        }
        return $array;      
    }
    
    
    private function _getAlbums() {
        $imgmaxsort = XRequest::getInt('imgmaxsort');
        $array = array();
        if ($imgmaxsort>0) {
            for($i=1;$i<($imgmaxsort+1);$i++) {
                
                $imgorders = XRequest::getInt('imgorders_'.$i);
                
                $imgname = XRequest::getArgs('imgname_'.$i);
                
                $imgthumb = XRequest::getArgs('imgthumb_'.$i);
                
                $imgurl = XRequest::getArgs('imgurl_'.$i);
                
                
                if (!empty($imgurl)) {
                    if (empty($imgthumb) || !file_exists(BASE_ROOT.'./'.$imgthumb)) {
                        $imgthumb = $imgurl;
                    }
                    
                    $array[] = array(
                        'imgorders'=>$imgorders,
                        'imgname'=>$imgname,
                        'imgthumb'=>$imgthumb,
                        'imgurl'=>$imgurl,
                    );
                }
            }
        }
        
        
        if (!empty($array) && is_array($array)) {
            
            $array = XHandle::sysSortArray($array, 'imgorders');
            return serialize($array);
        } 
        else {
            return '';
        }
        
    }
         public function action_ajax_get_action()
     {     
     	$advContrl = get_class_methods('control');
   
        
     	$html = '';
     	foreach ($advContrl as $val){
            if(strpos($val,'action') !== false){
                   
               $html .= "<option value='".$val."'>".$val."</option>";
                    
            } else {
               
            }
     		
     	}
     	exit($html);
     }
}
?>
