<?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->_getIndexItems();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_product_index", null, $this->catinfo);
        $var_array = array(
            'catinfo'          => $this->catinfo,
            'treeid'           => $this->treeid,
            'rootid'           => $this->rootid,
            'cid'              => $this->cid,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );

        $this->view($var_array, $this->_tplname);
    }


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

        $searchsql .= " AND v.treeid='{$this->treeid}'";
        if ($this->cid > 0) {
            $m      = parent::model('category', 'am');
            $childs = $m->getChildIDs($this->cid);
            if (!empty($childs)) {
                $searchsql .= " AND v.catid NOT IN ('126')";
            } else {
                $searchsql .= " AND v.catid='" . $this->cid . "'";
            }
            unset($m);
        }

        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, $this->_tplname);
    }


    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,
            'cid'      => $_REQUEST['id'],
        );
        //if (true == mobile_device_detect()) {
        //    $url='m_product_detail';
        //    $this->view($var_array, $url);
        //   die;
        //  }
      $this->view($var_array, $this->_tplname);
//      $this->view($var_array, 'user_tpl/download_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 = 'product_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'];
      //  print_r($GLOBALS);die;
        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 = 'product_list';
                }
            } else {
                $this->_tplname = $this->catinfo['tpllist'];
            }
        }
    }

    public function control_ajaxaddorder()
    {
        $args = $this->_validAdd();
        //    print_r($args);
        $model = parent::model('product', 'im');
        list($data, $attr, $this->catinfo) = $model->getOneData($args['goodsid']);
        //  print_r($data);
        /*if ($args['addressid'] == '') {
            $address['name']       = $args['name'];
            $address['phone']      = $args['phone'];
            $address['provinceid'] = $args['provinceid'];
            $address['cityid']     = $args['cityid'];
            $address['countyid']   = $args['countyid'];
            $address['address']    = $args['address'];
            $address['province']   = $model->getregionname($args['provinceid']);
            $address['city']       = $model->getregionname($args['cityid']);
            $address['county']     = $model->getregionname($args['countyid']);
            $address['user_id']    = $_SESSION["user_id"];
            $address['is_mo']      = '1';
            $address['time']       = time();
            $model1                = parent::model('member', 'im');
            $model1->addaddress($address);
        }*/
        $arr['ordernum']       = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $arr['goodsid']        = $args['goodsid'];
        $arr['goodsname']      = $data['productname'];
        $arr['goodsprice']     = $data['bprice'];
        $arr['orderprice']     = $data['bprice'] * $args['goodsnum'];
        $arr['goodsnum']       = $args['goodsnum'];
        $arr['goodsproductsn'] = $data['productsn'];
        $arr['goodsimg']       = $data['thumbfiles'];
        $arr['linkman']        = $args['name'];
        $arr['linkphone']      = $args['phone'];
        $arr['provincename']   = $model->getregionname($args['provinceid']);
        $arr['cityname']       = $model->getregionname($args['cityid']);
        $arr['countyname']     = $model->getregionname($args['countyid']);
        $arr['address']        = $args['address'];
        $arr['status']         = '待付款';
        $arr['time']           = time();
        $arr['user_id']        = $_SESSION["user_id"];
        $res                   = $model->addorder($arr);
        if ($res) {
            $data = array(
                'response'   => 1,
                'result'     => '下单成功,正在跳转付款',
                'ordernum'   => $arr['ordernum'],
                'orderprice' => $arr['orderprice'],
                'num'        => $arr['goodsnum']
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '操作失败'
            );
            echo json_encode($data);
            die;
        }

    }

    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);
        }
    }

    private function _validAdd()
    {
        $args = XRequest::getGpc(array(
            'goodsid', 'goodsnum', 'provinceid', 'cityid', 'countyid', 'address', 'name', 'phone', 'addressid'
        ));
        if (empty($args['goodsid'])) {
            $data = array(
                'response' => 0,
                'result'   => '参数错误,goodsid不存在'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['goodsnum'])) {
            $data = array(
                'response' => 0,
                'result'   => '参数错误,goodsnum'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['name'])) {
            $data = array(
                'response' => 0,
                'result'   => '姓名不能为空'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['phone'])) {
            $data = array(
                'response' => 0,
                'result'   => '电话不能为空'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['provinceid'])) {
            $data = array(
                'response' => 0,
                'result'   => '请选择省份'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['cityid'])) {
            $data = array(
                'response' => 0,
                'result'   => '市不能为空'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['countyid'])) {
            $data = array(
                'response' => 0,
                'result'   => '区/县不能为空'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['address'])) {
            $data = array(
                'response' => 0,
                'result'   => '地址详情不能为空'
            );
            echo json_encode($data);
            die;
        }

        return $args;
    }

    //地址三级联动
    public function control_getRegion()
    {
        $parent_id = $_REQUEST['parent_id'];
        $level     = $_REQUEST['level'];
        $selected  = $_REQUEST['selected'];
        $model     = parent::model('product', 'im');
        $data      = $model->getregion($parent_id, $level);
        $html      = '';
        if ($data) {
            foreach ($data as $h) {
                if ($h['id'] == $selected) {
                    $html .= "<option value='{$h['id']}' selected>{$h['name']}</option>";
                }
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }
        echo $html;
    }

    public function control_pay_wan()
    {
        $option = $_REQUEST['option'];

        $action = $_REQUEST['action'];
        $model  = parent::model('product', 'im');
        $data   = $model->getorderinfo($option);

        if ($data['status'] == '待付款') {
            $arr['`desc`']     = '通过' . $action . "购买产品" . $data['goodsname'];
            $arr['price']      = $data['orderprice'];
            $arr['user_money'] = $data['orderprice'];
            $arr['time']       = time();
            $arr['type']       = '1';
            $arr['user_id']    = $data['user_id'];
            $res1              = $model->addlog($arr);
            if ($res1) {
                $this->fanyong($data);
                $res           = $model->payorder($option);
                $data1['slay'] = 1;
                $data1["msg"]  = "修改成功";
                echo json_encode($data1);

            }


        }
    }
    public function control_yue_pay(){
        $option = $_REQUEST['order_number'];
        $model  = parent::model('product', 'im');
        $data   = $model->getorderinfo($option);
        if ($data['status'] == '待付款') {
            $membermodel  = parent::model('member', 'im');
            $userdata=$membermodel->getuserDataid($data['user_id']);
            $array['balance']=$userdata['balance']-$data['orderprice'];
            $array['id']=$data['user_id'];
            $res=$membermodel->saveinfo($array);
            if($res){
                $arr['`desc`']     = '通过余额支付购买产品' . $data['goodsname'];
                $arr['price']      = $data['orderprice'];
                $arr['user_money'] = $array['balance'];
                $arr['time']       = time();
                $arr['type']       = '1';
                $arr['user_id']    = $data['user_id'];
                $res1              = $model->addlog($arr);
                if ($res1) {
                    $this->fanyong($data);
                    $res           = $model->payorder($option);
                    $data1['response'] = 1;
                    $data1["result"]  = "支付成功";
                    echo json_encode($data1);
                }
            }

        }
    }
    //三级分销返佣
    private function fanyong($data){
        $user_id=$data['user_id'];
        //一级返佣
        $model  = parent::model('member', 'im');
        //积分与金钱比例
        $integral_ratiodata = $model->getsetup('integral_ratio');
        $integral_ratio = $integral_ratiodata['setvalue'];
        //一级分销比例
        $onedata = $model->getsetup('one_ratio');
        $one_ratio = $onedata['setvalue'];
        //获取一级分销商个人信息
        $one_data=$model->getuserDataid($user_id);
        $fan_one_integral=$data['orderprice']*$integral_ratio*($one_ratio/100);
       // $array['integral']=$one_data['integral']+$fan_one_integral;
      //  $array['id']=$user_id;
       // $res=$model->saveinfo($array);
        //if($res){
            $log['user_id']=$user_id;
            $log['integral']=$fan_one_integral;
            $log['`desc`']='订单返佣奖励'.$fan_one_integral.'积分';
            $log['time']=time();
            $log['status']=1;
            $log['order_num']=$data['ordernum'];
            $log['type']=1;
            $model->addlog($log);
            //二级返佣
            if($one_data['parent_id']!='0'){
                //二级分销比例
                $twodata = $model->getsetup('two_ratio');
                $two_ratio = $twodata['setvalue'];
                $two_data=$model->getuserDataid($one_data['parent_id']);
                $fan_two_integral=$data['orderprice']*$integral_ratio*($two_ratio/100);
                //$array1['integral']=$two_data['integral']+$fan_two_integral;
               // $array1['id']=$two_data['id'];
              //  $res1=$model->saveinfo($array1);
             //   if($res1){
                    $log['user_id']=$two_data['id'];
                    $log['integral']=$fan_two_integral;
                    $log['`desc`']='订单返佣奖励'.$fan_two_integral.'积分';
                    $log['time']=time();
                    $log['status']=1;
                    $log['order_num']=$data['ordernum'];
                    $log['type']=1;
                    $model->addlog($log);
                    //三级返佣
                    if($two_data['parent_id']!='0'){
                        //三级分销比例
                        $threedata = $model->getsetup('three_ratio');
                        $three_ratio = $threedata['setvalue'];
                        $three_data=$model->getuserDataid($two_data['parent_id']);
                        $fan_three_integral=$data['orderprice']*$integral_ratio*($three_ratio/100);
                       // $array2['integral']=$three_data['integral']+$fan_three_integral;
                       // $array2['id']=$three_data['id'];
                       // $res2=$model->saveinfo($array2);
                       // if($res2){
                            $log['user_id']=$three_data['id'];
                            $log['integral']=$fan_three_integral;
                            $log['`desc`']='订单返佣奖励'.$fan_three_integral.'积分';
                            $log['time']=time();
                            $log['status']=1;
                            $log['order_num']=$data['ordernum'];
                            $log['type']=1;
                            $model->addlog($log);
                       // }
                    }
                //}
            }
        }

    //}
}

?>
