<?php
/**
 * Copyright (C) LJCMS All rights reserved.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2016.03.19
 */

class control extends indexbase {
    private $cid = 0;
    private $id = 0;
    private $treeid = 0;
    private $rootid = 0;
    private $catinfo = array();
    private $_tplname = NULL;
    private $_tplfile = NULL;


    public function control_run() {
        $this->_getListItems();
        $searchsql = "";

        $searchsql .= " AND v.treeid='{$this->treeid}'";
        $content=$_REQUEST['content'];
        $searchsql .= " AND v.catid='126'";
        if($content){
            $searchsql .= "  AND v.productname LIKE '%$content%'";
        }
        if ($this->catinfo['pagemax'] < 1) {
            $this->pagesize = parent::$cfg['productpagesize'];
        } else {
            $this->pagesize = $this->catinfo['pagemax'];
        }

        if ($this->catinfo['orderby'] == 1) {
            $orderby = ' ORDER BY v.updatetime DESC';
        } elseif ($this->catinfo['orderby'] == 2) {
            $orderby = ' ORDER BY v.addtime DESC';
        } elseif ($this->catinfo['orderby'] == 3) {
            $orderby = ' ORDER BY v.hits DESC';
        } elseif ($this->catinfo['orderby'] == 4) {
            $orderby = ' ORDER BY v.productid DESC';
        } elseif ($this->catinfo['orderby'] == 5) {
            $orderby = ' ORDER BY v.productid ASC';
        } else {
            $orderby = ' ORDER BY v.addtime DESC';
        }
        $model = M('product', 'im');

        list($total, $data) = $model->getList(
            array(
                'page'      => $this->page,
                'pagesize'  => $this->pagesize,
                'searchsql' => $searchsql,
                'orderby'   => $orderby,
            )
        );
        unset($model);

        if (parent::$cfg['urlsuffix'] == 'html') {
            $url      = parent::$urlpath . $this->catinfo['dirname'] . '/';
            $showpage = XPage::indexHtml($total, $this->pagesize, $this->page, $url, 10);
        } else {
            $url      = XRequest::getPhpSelf() . '?c=product&a=list&cid=' . $this->cid;
            $showpage = XPage::index($total, $this->pagesize, $this->page, $url, 10);
        }

        $m_cat   = parent::model('category', 'im');
        $thepath = $m_cat->getCategoryUrl($this->cid, 1, $this->catinfo['catname']);
        if ($this->rootid != $this->cid && $this->rootid > 0) {
            $thepath = $m_cat->getCategoryUrl($this->rootid, 1) . ' &gt;&gt; ' . $thepath;
        }
        unset($m_cat);

        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_product_list", array("page" => $this->page), $this->catinfo);
        $indexmodel= parent::model('index', 'im');
        $userid=$_SESSION['user_id'];
        list($total,$data1) = $indexmodel->keyword($userid);

        $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'         => $showpage,
            'treeid'           => $this->treeid,
            'rootid'           => $this->rootid,
            'catid'            => $this->cid,
            'cid'              => $this->cid,
            'product'          => $data,
            'catinfo'          => $this->catinfo,
            'page_title'       => $page_title,
            'page_keyword'     => $page_keyword,
            'page_description' => $page_description,
            'thepath'          => $thepath,
            'data'             => $data1
        );
        // if (true == mobile_device_detect()) {
        //     $url='m_product_list';
        //     $this->view($var_array, $url);
        //    die;
        //  }

        //    echo $this->_tplname;die;
        $this->view($var_array, 'integral');
    }


    public function control_detail()
    {
        $this->_getDetailItems();

        $model = parent::model('product', 'im');
        list($data, $attr, $this->catinfo) = $model->getOneData($this->id);
        if (empty($data)) {
            XHandle::halt("对不起，信息不存在！", "", 1);
        }
        $previous_item = $model->getPrevious($data['treeid'], $this->id);
        if (!empty($previous_item)) {
            $previous_item = "<a href='" . $previous_item['url'] . "'>" . $previous_item['productname'] . "</a>";
        } else {
            $lang = $_SESSION['lang'];
            if ($lang == 'en') {
                $previous_item = "no";
            } else {
                $previous_item = "没有了";
            }
        }
        $next_item = $model->getNext($data['treeid'], $this->id);
        if (!empty($next_item)) {
            $next_item = "<a href='" . $next_item['url'] . "'>" . $next_item['productname'] . "</a>";
        } else {
            $lang = $_SESSION['lang'];
            if ($lang == 'en') {
                $next_item = "no";
            } else {
                $next_item = "没有了";
            }

        }
        $userid = $_SESSION['user_id'];
        /*$model1 = parent::model('plugin', 'am');
        $region = $model1->getPluginsimg("region");
        if (!empty($region)) {
            $province    = $model->getprovince();
            $city        = $model->getcity($data['provinceid']);
            $area        = $model->getares($data['cityid']);
            $addressinfo = $model->getuseraddressinfo($userid);
        }*/
        $province    = $model->getprovince();
        $city        = $model->getcity($data['provinceid']);
        $area        = $model->getares($data['cityid']);
        $addressinfo = $model->getuseraddressinfo($userid);
        unset($model);
        if (!empty($data['tpldetail'])) {
            $this->_tplname = $data['tpldetail'];
        } else {
            if (!empty($this->catinfo['tpldetail'])) {
                $this->_tplname = $this->catinfo['tpldetail'];
            } else {
                $this->_tplname = $this->catinfo['mod_tpldetail'];
            }
        }
        if (empty($this->_tplname)) {
            $this->_tplname = 'product_detail';
        }
        $this->treeid = intval($this->catinfo['treeid']);
        $this->rootid = intval($this->catinfo['rootid']);

        $m_cat   = parent::model('category', 'im');
        $thepath = $m_cat->getCategoryUrl($data['catid'], 1) . " &gt;&gt; " . "<a href=" . $data['url'] . ">" . $data['productname'] . "</a>";
        if ($this->rootid != $data['catid'] && $this->rootid > 0) {
            $thepath = $m_cat->getCategoryUrl($this->rootid, 1) . ' &gt;&gt; ' . $thepath;
        }
        unset($m_cat);

        $var_array = array(
            'data'     => $data,
            'check'    => $check,
            'province' => $province,
            'city'     => $city,
            'area'     => $area
        );
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_product_detail", $data, $this->catinfo);
        $var_array = array(
            'product'          => $data,
            'attr'             => $attr,
            'catinfo'          => $this->catinfo,
            'thepath'          => $thepath,
            'page_title'       => $page_title,
            'page_keyword'     => $page_keyword,
            'page_description' => $page_description,
            'treeid'           => $this->treeid,
            'rootid'           => $this->rootid,
            'previous_item'    => $previous_item,
            'next_item'        => $next_item,
            'id'               => $this->id,
            'province'         => $province,
            'city'             => $city,
            'area'             => $area,
            'addressinfo'      => $addressinfo,
        );
        //if (true == mobile_device_detect()) {
        //    $url='m_product_detail';
        //    $this->view($var_array, $url);
        //   die;
        //  }
        $this->view($var_array, 'integral_detail');
    }


    private function _getIndexItems() {
        $path_info = $GLOBALS['path_info'];
        if (!empty($path_info) && isset($path_info['cid'])) {
            $this->cid = intval($path_info['cid']);
        }
        else {
            $this->cid = XRequest::getInt('cid');
        }
        if ($this->cid<1) {
            XHandle::halt('对不起，栏目/分类ID有错！', '', 1);
        }

        $m_cat = parent::model('category', 'im');
        $this->catinfo = $m_cat->getOneData($this->cid);
        unset($m_cat);

        if (empty($this->catinfo)) {
            XHandle::halt('对不起，载入栏目/分类失败！', '', 1);
        }
        else {

            if ($this->catinfo['treeid'] == 0) {
                $this->treeid = $this->cid;
                $this->rootid = $this->cid;
            }
            else {
                $this->treeid = $this->catinfo['treeid'];
                $this->rootid = $this->catinfo['rootid'];
            }

            if (empty($this->catinfo['tplindex'])) {
                if (!empty($this->catinfo['mod_tplindex'])) {

                    $this->_tplname = $this->catinfo['mod_tplindex'];
                }
                else {
                    $this->_tplname = 'photo_index';
                }
            }
            else {
                $this->_tplname = $this->catinfo['tplindex'];
            }
            if (false === $this->existsTplFile($this->_tplname)) {

                $this->_tplname = '';
                $this->control_list();
                exit;
            }
        }
    }


    private function _getListItems() {
        $path_info = $GLOBALS['path_info'];
        if (!empty($path_info) && isset($path_info['cid'])) {
            $this->cid = intval($path_info['cid']);
        }
        else {
            $this->cid = XRequest::getInt('cid');
        }
        if ($this->cid<1) {
            XHandle::halt('对不起，栏目/分类ID有错！', '', 1);
        }

        $m_cat = parent::model('category', 'im');
        $this->catinfo = $m_cat->getOneData($this->cid);
        unset($m_cat);
        if (empty($this->catinfo)) {
            XHandle::halt('对不起，载入栏目/分类失败！', '', 1);
        }
        else {

            if ($this->catinfo['treeid'] == 0) {
                $this->treeid = $this->cid;
                $this->rootid = $this->cid;
            }
            else {
                $this->treeid = $this->catinfo['treeid'];
                $this->rootid = $this->catinfo['rootid'];
            }

            if (empty($this->catinfo['tpllist'])) {
                if (!empty($this->catinfo['mod_tpllist'])) {

                    $this->_tplname = $this->catinfo['mod_tpllist'];
                }
                else {
                    $this->_tplname = 'photo_list';
                }
            }
            else {
                $this->_tplname = $this->catinfo['tpllist'];
            }
        }
    }


    private function _getDetailItems() {
        $path_info = $GLOBALS['path_info'];
        if (!empty($path_info) && isset($path_info['id'])) {
            $this->id = intval($path_info['id']);
        }
        else {
            $this->id = XRequest::getInt('id');
        }
        if ($this->id<1) {
            XHandle::halt('对不起，内容ID参数无效！', '', 1);
        }
    }
    public function control_shopping(){
        $goodsid=$_REQUEST['goodsid'];
        $username=$_SESSION['user_id'];
        $usbynum=  $_REQUEST['buynum'];
        if($usbynum <= '0'){
             $data=array(
                'response'=>0,
                'result'=>'兑换数量不能为0或者非法参数',
            );
            echo json_encode($data);
            die;
        }
        if (!is_numeric($usbynum)) {  
            $data=array(
                'response'=>0,
                'result'=>'提交的参数非法',
            );
            echo json_encode($data);
            die; 
            
        }  // 数字判断
        $model = parent::model('product', 'im');
        list($data, $attr, $this->catinfo) = $model->getOneData($goodsid);
        if (empty($data)) {
            $data=array(
                'response'=>0,
                'result'=>'对不起，信息不存在',
            );
            echo json_encode($data);
            die;
        }
        if($data['stock']=='0'){
            $data=array(
                'response'=>0,
                'result'=>'您来一晚一步，库存不足',
            );
            echo json_encode($data);
            die;
        }
            $data1=array(
                'response'=>1,
                'result'=>'操作成功',
                'jumpurl'=>'index.php?c=integral&a=order&id='.$goodsid.'&num='.$usbynum
            );
            echo json_encode($data1);
            die;

    }
    public function control_order()
    {

        $user_id= $_SESSION['user_id'];
        $addressid=$_REQUEST['addressid'];
        $name= $_SESSION["username"];
        $goodsid=$_REQUEST['id'];
        if (!is_numeric($goodsid)) {
             exit('提交的参数非法！');            
        }
        $usbynum=$_REQUEST['num'];
       if($usbynum <= '0'){
          exit('兑换数量不能为0或者非法参数！');
        }
        if (!is_numeric($usbynum)) {  
               exit('提交的参数非法！');                
        } 
        $mbrmodel = parent::model('member', 'im');
        $mbrdata=$mbrmodel->getuserData($name);
        //  echo $user_id;
        // list($total, $list) = $mbrmodel->getuseraddress(array('page'=>$this->page, 'pagesize'=>$this->pagesize, 'adminid'=>$user_id));
        if($addressid){
            $addressinfo=$mbrmodel->getuseraddressinfo1($addressid);
        }else{
            $addressinfo=$mbrmodel->getuseraddressinfo($user_id);
        }


        // 获取订单信息
        $model = parent::model('product', 'im');

        $arr[]=$goodsid;
        if (empty($arr)) {
            unset($model);
            $data=null;
            return $this->view(['data'=>$data], "member/user_shopping");
        }
        $newarr = array_unique($arr, SORT_REGULAR);
        foreach ($newarr as $key => $value) {
            $pctinfo[] = $model->getOneData($value);
        }
        foreach ($pctinfo as $key => $value) {
            $data[$key]['productid'] = $value[0]['productid'];
            $data[$key]['productname'] = $value[0]['productname'];
            $data[$key]['bprice'] = $value[0]['bprice'];
            $data[$key]['uploadfiles'] = $value[0]['uploadfiles'];
            $data[$key]['productnum'] = $_REQUEST['num'];
            $data[$key]['subtotal'] = $data[$key]['bprice'] * $data[$key]['productnum'];
            $data[$key]['catname'] = $value[2]['catname'];

        }
        foreach ($data as $key => $value) {
            $priceTotal += floatval($value['subtotal']);
            $goodsnum += floatval($value['productnum']);
        }

        $var_array = array(
            'addressinfo'=>$addressinfo,
            'djtotal'=>$priceTotal,
            'goodsnum'=>$goodsnum,
            'data'=>$data,
            'goodsid'=>$goodsid,
            'num'=>$usbynum,
        );
        unset($model);
        unset($mbrmodel);
        return $this->view($var_array, "integral_order");
    }
    public function control_submitorder()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' || empty($_SESSION['user_id'])) {
            $data=array(
                'response'=>0,
                'result'=>'非法请求，缺少参数'
            );
            echo json_encode($data);
            die;
        }
        $user_id= $_SESSION['user_id'];
        $name= $_SESSION["username"];
        $addressid=$_REQUEST['addressid'];
        $goodsid=$_REQUEST['goodsid'];
        $num=$_REQUEST['num'];
        if($num <= '0'){
             $data=array(
                'response'=>0,
                'result'=>'兑换数量不能为0或者非法参数',
            );
            echo json_encode($data);
            die;
        }
        if (!is_numeric($num)) {  
            $data=array(
                'response'=>0,
                'result'=>'提交的参数非法',
            );
            echo json_encode($data);
            die; 
            
        }
        $mbrmodel = parent::model('member', 'im');
        $mbrdata=$mbrmodel->getuserData($name);
        //  list($total, $list) = $mbrmodel->getuseraddress(array('page'=>$this->page, 'pagesize'=>$this->pagesize, 'adminid'=>$user_id));
        if($addressid){
            $addressinfo=$mbrmodel->getuseraddressinfo1($addressid);
        }else{
            $addressinfo=$mbrmodel->getuseraddressinfo($user_id);
        }
        // 获取订单信息
        $model = parent::model('product', 'im');
        $arr[]=$goodsid;
        if (empty($arr)) {
            unset($model);
            $data=null;
            return $this->view(['data'=>$data], "member/user_shopping");
        }
        $newarr = array_unique($arr, SORT_REGULAR);
        foreach ($newarr as $key => $value) {
            $pctinfo[] = $model->getOneData($value);
        }
        foreach ($pctinfo as $key => $value) {
             $price += $value[0]['bprice']*$num;
        }
        if($price > $mbrdata['integral']){
            $data=array(
                'response'=>0,
                'result'=>'积分不足'
            );
            echo json_encode($data);
            die;
        }
        // 商品信息
        $ordarr['ordernum']=date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        foreach ($pctinfo as $key => $value) {
            $odrarr['goodsid'][] = $value[0]['productid'];
            $odrarr['goodsname'][] = $value[0]['productname'];
            $odrarr['goodsprice'][] = $value[0]['bprice'];
            $odrarr['goodsnum'][] = $num;
            $odrarr['goodsproductsn'][] = $value[0]['productsn'];
            $odrarr['goodsimg'][]=$value[0]['thumbfiles'];

            $ordarr['orderprice'] += $value[0]['bprice']*$num;

            $model->submitorderinfo($ordarr['ordernum'],$value[0]['productname'],$value[0]['bprice'],$num,$value[0]['bprice']*$num,'待付款',$_SESSION["user_id"],$value[0]['thumbfiles']);
            //减库存 stock
            $model->doEditStock($value[0]['productid'],$num);
        }

        $ordarr['goodsid']=implode(',', $odrarr['goodsid']);
        $ordarr['goodsname']=implode(',', $odrarr['goodsname']);
        $ordarr['goodsprice']=implode(',', $odrarr['goodsprice']);
        $ordarr['goodsnum']=implode(',', $odrarr['goodsnum']);
        $ordarr['goodsproductsn']=implode(',', $odrarr['goodsproductsn']);
        $ordarr['goodsimg']=implode(',', $odrarr['goodsimg']);
        // 联系人信息
        $ordarr['linkman']=$addressinfo['name'];
        $ordarr['linkphone']=$addressinfo['phone'];
        $ordarr['provincename']=$model->getregionname($addressinfo['id']);
        $ordarr['cityname']=$model->getregionname($addressinfo['id']);
        $ordarr['countyname']=$model->getregionname($addressinfo['id']);
        $ordarr['address']=$addressinfo['address'];

        $ordarr['status']='待发货';
        $ordarr['time']= time();
        $ordarr['is_integral']= 1;
        $ordarr['user_id']= $_SESSION["user_id"];

        $repeatodrid = $model->checkorder($ordarr['goodsid'],$_SESSION["user_id"]);
        if ($repeatodrid) {
            $res=$model->doEdit($repeatodrid['id'], $ordarr);
            //
            $model->updateorderinfo($ordarr['ordernum'],$repeatodrid['id'],$_SESSION["user_id"]);
        } else {
            $res=$model->addorder($ordarr);
            $model->updateorderinfo($ordarr['ordernum'],$res,$_SESSION["user_id"]);
        }

        $ordallname= $ordarr['goodsname'];
        $ordallnumbr= $ordarr['ordernum'];
        $ordalltotal= floatval($ordarr['orderprice']);


        if($res){
            $data=array(
                'response'=>1,
                'result'=>'兑换成功',
                'ordallname'=>$ordallname,
                'ordallnumbr'=>$ordallnumbr,
                'ordalltotal'=>$ordalltotal,
                'jumpurl'   =>'index.php?c=user&a=order_list'
            );
            $info['integral']=$mbrdata['integral']-$price;
            $info['id']       = $user_id;
            $mbrmodel->saveinfo($info);
            $log['user_id']=$user_id;
            $log['integral']=$price;
            $log['`desc`']='兑换商品花费'.$price.'积分';
            $log['time']=time();
            $log['type']=2;
            $mbrmodel->addlog($log);
            echo json_encode($data);
            unset($model);
            unset($mbrmodel);
            die;
        } else {
            $data=array(
                'response'=>0,
                'result'=>'操作失败'
            );
            echo json_encode($data);
            unset($model);
            unset($mbrmodel);
            die;
        }
    }
}
?>
