<?php

use mysql_xdevapi\Result;

/**
 * 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
{
    public function control_run()
    {
        //$this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $name      = $_SESSION["user_id"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
            die;
        }

        $model     = parent::model('member', 'im');
        $data      = $model->getuserDataid($name);
        $user_id   = $data['id'];
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id' AND status='待付款'";
        $total1= $model->getordertotal($searchsql);
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id' AND status='待收货'";
        $total2= $model->getordertotal($searchsql);
        if(!empty($data)){
            $data['logintimeline'] = date("Y-m-d H:i:s", $data['last_login_time']);

        }
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id' AND status='1'";
        $orderby = ' ORDER BY time DESC';
        $model = parent::model('member', 'im');
        list($total, $list1) = $model->getAllprofitList(
            array(
                'page'      => $this->page,
                'pagesize'  => '1000000',
                'searchsql' => $searchsql,
                'orderby'   => $orderby,
            )
        );
        $yuji=0;
        foreach ($list1 as $value){
            $yuji+=$value['integral'];
        }
        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }
        $sql="SELECT * FROM 8cms_order WHERE user_id={$user_id} ORDER BY time DESC LIMIT 3";
        $order_list=parent::$obj->getall($sql);
        foreach($order_list as $k=>$v){
            $order_list[$k]['goodsname']=substr($v['goodsname'],0,10).'..';
        }

        $var_array             = array(
            'data'             => $data,
            'check'            => $check,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'yuji'=>$yuji,
            'hao'=>$hao,
            'total'=>$total1,
            'total1'=>$total2,
            'list'=>$order_list
        );

//        echo '<pre>';
//        print_r($var_array);die;

        $this->view($var_array, "member/user_center");

    }

    /**
     * 个人资料
     */
    public function control_user_datas(){
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id' AND status='待付款'";
        $total1= $model->getordertotal($searchsql);
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id' AND status='待收货'";
        $total2= $model->getordertotal($searchsql);
        if(!empty($data)){
            $data['logintimeline'] = date("Y-m-d H:i:s", $data['last_login_time']);

        }
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id' AND status='1'";
        $orderby = ' ORDER BY time DESC';
        $model = parent::model('member', 'im');
        list($total, $list1) = $model->getAllprofitList(
            array(
                'page'      => $this->page,
                'pagesize'  => '1000000',
                'searchsql' => $searchsql,
                'orderby'   => $orderby,
            )
        );
        $yuji=0;
        foreach ($list1 as $value){
            $yuji+=$value['integral'];
        }
        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }
        $sql="SELECT * FROM 8cms_order WHERE user_id={$user_id} ORDER BY time DESC LIMIT 0, 1000000";
        $order_list=parent::$obj->getall($sql);
        $var_array             = array(
            'data'             => $data,
            'check'            => $check,
            'yuji'=>$yuji,
            'hao'=>$hao,
            'total'=>$total1,
            'total1'=>$total2,
            'list'=>$order_list,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );

//        echo '<pre>';
//        print_r($var_array);die;

        $this->view($var_array, "member/user_info");

    }

    /**
     * 订单管理
     */
    public function control_w_order(){
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];

        $sql="SELECT * FROM 8cms_order WHERE user_id={$user_id} ORDER BY time DESC LIMIT 0, 1000000";
        $order_list=parent::$obj->getall($sql);


        $total=count($order_list);
        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }

        foreach($order_list as $k=>$v){
            $order_list[$k]['goodsname']=substr($v['goodsname'],0,15).'......';
        }
        $var_array             = array(
            'data'             => $data,
            'list'=>$order_list,
            'hao'=>$hao,
            'total'=>$total,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );
        //        echo '<pre>';
//        print_r($var_array);die;
        $this->view($var_array, "member/w_order");
    }

    /**
     * 地址管理
     */
    public function control_invoice_address(){
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];
        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }

        $model     = parent::model('member', 'im');

        $list = $model->getuseraddress(array('page' => $this->page, 'pagesize' => $this->pagesize, 'adminid' => $user_id));
        $total=count($list[1]);
        $address=$list[1];
        foreach($address as $k=>$v){
            $len=$v['province'].' '.$v['city'].' '.$v['county'].' '.$v['address'];
//            $address[$k]['len']=substr($len,0,15).'...';
            $address[$k]['len']=$len;
        }
        $var_array             = array(
            'data'             => $data,
            'list'=>$address,
            'hao'=>$hao,
            'total'=>$total,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );

//
//
//        echo '<pre>';
//        print_r($var_array);die;

        $this->view($var_array, "member/user_address");
    }

    /**
     * 设置默认地址
     */
    public function control_she_mo(){

        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];
        $a_id=intval($_REQUEST['a_id']);
        $array=array(
            'is_mo'=>0
        );
        $res=parent::$obj->update('8cms_member_address', $array, ' user_id='.$user_id.'');

        $where=" user_id=$user_id and id=$a_id";
        $array2=array(
            'is_mo'  =>1
        );
        $res2=parent::$obj->update('8cms_member_address', $array2,$where);
        if($res2){
            $arr=array(
                'msg'=>'设置成功'  ,
                'code'=>200  ,
            );
        }else{
            $arr=array(
                'msg'=>'设置失败'  ,
                'code'=>10001  ,
            );
        }
        print_r( json_encode($arr));
    }



    /**
     * 新增地址
     */
    public function control_add_user_address(){
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];

        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }
        $model1   = parent::model('product', 'im');
        $province = $model1->getprovince();
        $city     = $model1->getcity();
        $area     = $model1->getares();

        $a_id=intval($_REQUEST['a_id']);
        $address_info=parent::$obj->fetch_first("select * from 8cms_member_address where id=$a_id");

        $var_array             = array(
            'data'             => $data,
            'province'=>$province,
            'city'=>$city,
            'area'=>$area,
            'hao'=>$hao,
            'address_info'=>$address_info,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,

        );

        $this->view($var_array, "member/add_address");
    }

    /**
     * 支付页面
     */
    public function control_orderpay(){
        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];
        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }
        $id=intval($_REQUEST['id']);
        $order_info=parent::$obj->fetch_first("select * from 8cms_order where id=$id");
        $var_array             = array(
            'data'             => $data,
            'order_info'=>$order_info,
            'hao'=>$hao,
            'type'=>$_GET['type'],
//            'total'=>$total
        );
//        print_r($var_array);die;
        $this->view($var_array, "member/orderpay");
    }

    /**
     * 修改密码-退出登录
     */
    public function control_delLogin(){
        session_start();//将session销毁时调用destroy
        session_destroy();
        header("location:index.php");
    }

    public function control_user_info()
    {
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $var_array = array(
            'data'             => $data,
            'check'            => $check,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );
        $this->view($var_array, "member/user_info");
    }

    public function control_ajaxeditinfo()
    {
        $info['nickname']   = $_REQUEST['nickname'];
        $info['mobile_tel'] = $_REQUEST['phone'];
        $info['email']      = $_REQUEST['email'];
        $info['sex']        = $_REQUEST['sex'];
        $info['pic']        = $_REQUEST['pic'];
        if (empty($info['mobile_tel'])) {
            $data = array(
                'response' => 0,
                'result'   => '手机号不能为空'
            );
            echo json_encode($data);
            die;
        } else {
            if (false === XValid::isPhone($info['mobile_tel'])) {
                $data = array(
                    'response' => 0,
                    'result'   => '手机格式不正确'
                );
                echo json_encode($data);
                die;
            }
        }
        if (empty($info['email'])) {
            $data = array(
                'response' => 0,
                'result'   => '邮箱不能为空'
            );
            echo json_encode($data);
            die;
        } else {
            if (false === XValid::isEmail($info['email'])) {
                $data = array(
                    'response' => 0,
                    'result'   => '邮箱格式不正确'
                );
                echo json_encode($data);
                die;
            }
        }
        $name = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data  = $model->getuserData($name);
        $info['id'] = $data['id'];
        $res        = $model->saveinfo($info);
        if ($res == TRUE) {
            $data = array(
                'response' => 1,
                'result'   => '操作成功'
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '操作失败'
            );
            echo json_encode($data);
            die;
        }
    }
    public function control_user_edit()
    {
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $var_array = array(
            'data' => $data,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );
        $this->view($var_array, "member/user_edit");
    }
    public function control_ajaxeditpwd()
    {
        $oldpwd  = md5($_REQUEST['oldpwd']);
        $newpwd  = $_REQUEST['newpwd'];
        $aginpwd = $_REQUEST['aginpwd'];
        $name    = $_SESSION["username"];
        $model   = parent::model('member', 'im');
        $data    = $model->getuserData($name);
        if ($oldpwd != $data['password']) {
            $data = array(
                'response' => 0,
                'result'   => '原密码错误'
            );
            echo json_encode($data);
            die;
        }
        if ($newpwd != $aginpwd) {
            $data = array(
                'response' => 0,
                'result'   => '俩次密码输入不一致'
            );
            echo json_encode($data);
            die;
        }
        $info['password'] = md5($newpwd);
        $info['id']       = $data['id'];
        $res              = $model->saveinfo($info);
        if ($res == TRUE) {
            $data = array(
                'response' => 1,
                'result'   => '操作成功'
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '操作失败'
            );
            echo json_encode($data);
            die;
        }
    }
    public function control_ajaxeditpaypwd()
    {
        $name    = $_SESSION["username"];
        $model   = parent::model('member', 'im');
        $data    = $model->getuserData($name);

        $paypwd = $_REQUEST['paypwd'];
        $type=$_REQUEST['type'];
        if($type==1){
            $info['paypwd'] = md5($paypwd);
        }elseif ($type==2){
            $oldpwd  = md5($_REQUEST['oldpwd']);
            $aginpwd = $_REQUEST['aginpwd'];
            if ($oldpwd != $data['paypwd']) {
                $data = array(
                    'response' => 0,
                    'result'   => '原密码错误'
                );
                echo json_encode($data);
                die;
            }
            if ($paypwd != $aginpwd) {
                $data = array(
                    'response' => 0,
                    'result'   => '俩次密码输入不一致'
                );
                echo json_encode($data);
                die;
            }
            $info['paypwd'] = md5($paypwd);
        }

        $info['id']       = $data['id'];
        //  print_r($info);
        $res              = $model->saveinfo($info);
        if ($res == TRUE) {
            $data = array(
                'response' => 1,
                'result'   => '操作成功'
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '操作失败'
            );
            echo json_encode($data);
            die;
        }
    }
    public function control_user_log()
    {
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['userid'];
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id'";
        $orderby   = ' ORDER BY time DESC';
        list($total, $list) = $model->getAlllogList(
            array(
                'page'      => $this->page,
                'pagesize'  => $this->pagesize,
                'searchsql' => $searchsql,
                'orderby'   => $orderby,
            )
        );
        $price = 0;
        foreach ($list as $v) {
            $price += $v['price'];
        }

        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }
        $var_array = array(
            'data' => $data,
            'list'             => $list,
            'total'            => $total,
            'price'            => $price,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'hao'     => $hao,
        );

//        echo '<pre>';
//        print_r($var_array);die;
        $this->view($var_array, "member/user_log");

    }
    public function control_login()
    {

        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $type=$_REQUEST['res'];
        $var_array = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'type'=>$type
        );
        $this->view($var_array, "member/user_login");
    }
    public function control_exit()
    {
        session_start();//将session销毁时调用destroy
        session_destroy();
    }
    public function control_ajaxlogin()
    {
        session_start();
        parent::loadUtil('session');
        $args['username'] = $_REQUEST['username'];
        if($args['username']=='管理员'){
            $data = array(
                'response' => 0,
                'result'   => '账号不存在'
            );
            echo json_encode($data);
            die;
        }
        $args['password'] = $_REQUEST['password'];


        $model            = parent::model('member', 'im');
        $data             = $model->getuserData($args['username']);
        if (!empty($data)) {
            $res = $model->getusercheck($args);
            if (!empty($res)) {
                $model->savetime($res['id']);
                $_SESSION["user_id"]  = $res['id'];
                $_SESSION["username"] = $res['name'];
                $_SESSION["code"]     = mt_rand(0, 100000);//给session附一个随机值
                //   print_r($_SESSION);die;
                $data = array(
                    'response' => 1,
                    'result'   => '登陆成功'
                );
                echo json_encode($data);
                die;
            } else {
                $data = array(
                    'response' => 0,
                    'result'   => '密码错误'
                );
                echo json_encode($data);
                die;
            }
        } else {
            $data = array(
                'response' => 0,
                'result'   => '账号不存在'
            );
            echo json_encode($data);
            die;
        }
    }
    public function control_register()
    {
        $id=$_REQUEST['id'];
        $var_array = array(
            'id' => $id,
        );
        $this->view($var_array, "member/user_register");
    }
    public function control_ajaxreg()
    {

        $args = $this->_validAdd();
        $model = parent::model('member', 'im');
        $data  = $model->getuserData($args['username']);
        //    print_r($data);die;
        if (!empty($data)) {
            $data = array(
                'response' => 0,
                'result'   => '注册失败,该账户已存在'
            );
            echo json_encode($data);
            die;
        }
        // $args['phone']=$args['username'];
        $arr['name']       = $args['username'];
        $arr['mobile_tel'] = $args['username'];
        $arr['password']   = $args['password'];
        $arr['email']      = $args['email'];
        if($args['parent_id']==''){
            $arr['parent_id']      = 0;
        }else{
            $arr['parent_id']      = $args['parent_id'];
        }
   //     print_r($arr);die;
        $result            = $model->doAdduser($arr);
        // unset($model);
        if (true === $result) {
            if($arr['parent_id']!='0'){
                $data=$model->getuserDataid($arr['parent_id']);
                $set=$model->getsetup('integral');
                $array['integral']=$data['integral']+$set['setvalue'];
                $array['id']=$arr['parent_id'];
                $model->saveinfo($array);

                $log['user_id']=$arr['parent_id'];
                $log['integral']=$set['setvalue'];
                $log['`desc`']='新用户注册奖励'.$set['setvalue'].'积分';
                $log['time']=time();
                $log['type']=1;
                $model->addlog($log);
            }
            $data    = $model->getuserData($args['username']);
            $_SESSION["user_id"]  = $data['id'];
            $_SESSION["username"] = $data['name'];
            $_SESSION["code"]     = mt_rand(0, 100000);//给session附一个随机值
            $data = array(
                'response' => 1,
                'result'   => '注册成功'
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '注册失败'
            );
            echo json_encode($data);
            die;
        }
    }
    public function get_list()
    {
        $model_category = parent::model('category', 'im');
        $data           = $model_category->treelist();
        return $data;
    }
    public function checklogin()
    {
        session_start();
        // print_r($_SESSION["code"]);die;
        if ($_SESSION["code"] == '') {//判断code存不存在，如果不存在，说明异常登录
            $data = 0;
        } else {
            $data = 1;
        }
        return $data;
    }

    /**
     * 检测用户是否登录
     * @return int
     */
    public function isLogin()
    {
        $name = $_SESSION['username'];
        if(empty($name)){
            header("location: index.php?c=user&a=login");
        }
    }
    private function _validAdd()
    {
        $args = XRequest::getGpc(array(
            'username', 'password', 'email', 'assertpassword', 'checkcode','parent_id'
        ));

        if (empty($args['username'])) {
            $data = array(
                'response' => 0,
                'result'   => '请填写手机号'
            );
            echo json_encode($data);
            die;
            //   XHandle::halt('请填写用户名', '', 1);
        } else {
            if (false === XValid::isPhone($args['username'])) {
                $data = array(
                    'response' => 0,
                    'result'   => '手机式不正确'
                );
                echo json_encode($data);
                die;
            }
        }
        if (empty($args['password'])) {
            $data = array(
                'response' => 0,
                'result'   => '请填写密码'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['assertpassword'])) {
            $data = array(
                'response' => 0,
                'result'   => '请填写第二次密码'
            );
            echo json_encode($data);
            die;
        }
        if (empty($args['email'])) {
            $data = array(
                'response' => 0,
                'result'   => '请填写邮箱'
            );
            echo json_encode($data);
            die;
        } else {
            if (false === XValid::isEmail($args['email'])) {
                $data = array(
                    'response' => 0,
                    'result'   => '邮箱格式不正确'
                );
                echo json_encode($data);
                die;
            }
        }
        parent::loadUtil('session');
        if ($args['checkcode'] != XSession::get('verifycode')) {
            $data = array(
                'response' => 0,
                'result'   => '验证码不正确'
            );
            echo json_encode($data);
            die;
        }
        if ($args['password'] != $args['assertpassword']) {
            $data = array(
                'response' => 0,
                'result'   => '两次密码不一致'
            );
            echo json_encode($data);
            die;
        }
        unset($args['assertpassword']);
        unset($args['checkcode']);
        return $args;
    }
    public function control_orderinfo()
    {
        $ordernumber     = $_REQUEST['number'];
        $model           = parent::model('product', 'im');
        $data            = $model->getorderinfo($ordernumber);
        if(!empty($data['address'])){
            $data['address'] = $data['provincename'] . $data['cityname'] . $data['countyname'] . $data['address'];
        }
        if(!empty($data['time'])){
            $data['time'] = date('Y-m-d H:i:s', $data['time']);
        }
        echo json_encode($data);
    }
    public function control_user_address()
    {
        $res=$_REQUEST['res'];
        $type=$_REQUEST['type'];
        $id=$_REQUEST['id'];
        $num=$_REQUEST['num'];
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        if(empty($name)){
            header('Location: index.php?c=user&a=login');
        }

        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id'";
        list($total, $list) = $model->getuseraddress(array('page' => $this->page, 'pagesize' => $this->pagesize, 'adminid' => $user_id));
        $model1   = parent::model('product', 'im');
        $province = $model1->getprovince();
        $city     = $model1->getcity();
        $area     = $model1->getares();

        $var_array = array(
            'data' => $data,
            'list'  => $list,
            'total' => $total,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'province'         => $province,
            'city'             => $city,
            'area'             => $area,
            'res'             => $res,
            'type'            => $type,
            'id'            => $id,
            'num'            => $num
        );
//        echo '<pre>';
//        print_r($var_array);die;
        $this->view($var_array, "member/user_address");
    }

    public function control_adddizhi(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $addressid=$_REQUEST['id'];
        if($addressid){
            $model     = parent::model('member', 'im');
            $data      = $model->getaddressinfo($addressid);
            //   print_r($data);
        }
        $model1   = parent::model('product', 'im');
        $province = $model1->getprovince();
        $city     = $model1->getcity();
        $area     = $model1->getares();
        $var_array = array(
            'data' => $data,
            'addressid'=>$addressid,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'province'         => $province,
            'city'             => $city,
            'area'             => $area
        );
        $this->view($var_array, "member/user_adddizhi");
    }
    public function control_add_address()
    {
        $arr  = $_POST;
        //   print_r($arr);die;
        $name = $_SESSION["username"];
        if ($arr['name'] == '') {
            $data = array(
                'response' => 0,
                'result'   => '收件人姓名不能为空'
            );
            echo json_encode($data);
            die;
        }
        if ($arr['phone'] == '') {
            $data = array(
                'response' => 0,
                'result'   => '收件人电话不能为空'
            );
            echo json_encode($data);
            die;
        }
        if ($arr['provinceid'] == '') {
            $data = array(
                'response' => 0,
                'result'   => '省份不能为空'
            );
            echo json_encode($data);
            die;
        }
        if ($arr['cityid'] == '') {
            $data = array(
                'response' => 0,
                'result'   => '市不能为空'
            );
            echo json_encode($data);
            die;
        }
        if ($arr['countyid'] == '') {
            $data = array(
                'response' => 0,
                'result'   => '县/区不能为空'
            );
            echo json_encode($data);
            die;
        }
        if ($arr['address'] == '') {
            $data = array(
                'response' => 0,
                'result'   => '地址详情不能为空'
            );
            echo json_encode($data);
            die;
        }
        $addressid       = $arr['id'];
        $model           = parent::model('member', 'im');
        $data            = $model->getuserData($name);
        $user_id         = $data['id'];
        $arr['province'] = $model->getregionname($arr['provinceid']);
        $arr['city']     = $model->getregionname($arr['cityid']);
        $arr['county']   = $model->getregionname($arr['countyid']);
        if ($arr['is_mo'] == 'on') {
            $arr['is_mo'] = '1';
            //清楚默认
            $model->delmo();
        } else {
            unset($arr['is_mo']);
        }
        $arr=$this->SafeFilter($arr);
        if ($addressid) {
            $res = $model->saveaddress($arr);
        } else {
            unset($arr['id']);
            $count = $model->getaddresscount($user_id);
            if ($count >= 5) {
                $data = array(
                    'response' => 0,
                    'result'   => '最多保存5个地址'
                );
                echo json_encode($data);
                die;
            }
            $arr['user_id'] = $user_id;
            $arr['time']    = time();
            $res            = $model->addaddress($arr);
        }
        if ($res) {
            $data = array(
                'response' => 1,
                'result'   => '操作成功',
                'jumpurl'  => 'index.php?c=user&a=user_address'
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '操作失败'
            );
            echo json_encode($data);
            die;
        }
    }
    public function control_deladdress()
    {
        $id    = $_REQUEST['id'];
        $model = parent::model('member', 'im');
        $res   = $model->deladdress($id);
        if ($res) {
            $data = array(
                'response' => 1,
                'result'   => '操作成功'
            );
            echo json_encode($data);
            die;
        }
    }
    public function control_getaddressinfo()
    {
        $this->isLogin();
        $user_id= $_SESSION['user_id'];
        $id          = $_REQUEST['id'];
        $model       = parent::model('member', 'im');
        $addressinfo = $model->getaddressinfo($id);
        if($user_id != $addressinfo['user_id']){
           exit('提交的参数非法！');
            die;
        }
        echo json_encode($addressinfo);
    }

    public function control_upload(){

        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];

        $file=$_FILES;
//            print_r($_FILES);die;
        $saveurl = "";
        $tmp_name=str_replace('\\\\', '\\', $_FILES['file']['tmp_name']);

        $str =$file['file']['name'];
        $arr = explode('.', $str);
        $num = count($arr) - 1;
        if($type=="rar" || $type=="zip" || $type=="jpg" || $type=="gif" || $type=="png" || $type=="jpeg"){
            $type = $arr[$num];
        }else{
            $type = 'jpg';
        }
        $filename = date("YmdHis") . rand(0000, 9999) . "." . $type;
        if (!$this->checkNewName($filename)) {
            echo 'illegal_file_type';
            die;
        }

        if($type=="rar" || $type=="zip"){
            $destination_folder = 'data/attachment/template/' . date('Ym') . '/'; //上传文件路径
        } else {
            $destination_folder = 'data/attachment/kefu/' . date('Ym') . '/'; //上传文件路径
        }

        if (!file_exists($destination_folder)) {
            mkdir($destination_folder);
        }
        $destination = $destination_folder.$filename;

        $PHP_SELF=$_SERVER['PHP_SELF'];

        $url='http://'.$_SERVER['HTTP_HOST'].substr($PHP_SELF,0,strrpos($PHP_SELF,'/')+1);

        if(move_uploaded_file($tmp_name,$destination)){
            $array=array(
                'pic'=>$destination,
            );
            parent::$obj->update('oa_user', $array, ' id='.$user_id.'');
            $data['code']=200;
            $data['name']=$url.$destination;
            $data['name1']=$destination;
            echo json_encode($data);
        } else {
            $arr=array(
                'code'=>10001,
            );
            echo json_encode($arr);
        }
    }
    private function checkNewName($newName) {
        $newName = strtolower($newName);
        return (strpos($newName, '..') !== false || strpos($newName, '.php.') !== false || strpos($newName, '.asp.')) ? false : true;
    }
    public function control_shopping(){
        $check=$this->checklogin();
        $user_id= $_SESSION['user_id'];
//
        $model = parent::model('product', 'im');
        $spdata =$model->getusershopping($user_id);
        foreach ($spdata as $key => $value) {
            $arr[]=$value['productid'];
        }
        if (empty($arr)) {
            unset($model);
            $data=null;
            return $this->view(array('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'] = $spdata[$key]['productnum'];
            $data[$key]['catname'] = $value[2]['catname'];
        }
        foreach ($data as $k => $v) {
            //多的数组
            foreach ($spdata as $ke => $va) {
                //少的数组为主
                if ($v['productid'] == $va['productid']) {
                    $data[$k]['selected'] = $va['selected'];
                }
            }
        }
        unset($model);
        $this->view(array('data'=>$data), "member/user_shopping");
    }

    public function control_usupdateorder()
    {
        $check=$this->checklogin();
        $user_id=$_SESSION['user_id'];
        if($user_id==''){
            $data=array(
                'response'=>0,
                'result'=>'还未登陆'
            );
            echo json_encode($data);
            die;
        }
        $model = parent::model('product', 'im');
        //情况个人所有选中商品
        $model->updateselected($_SESSION['user_id']);
        // 商品ID数组
     //   $postgdarr=$_REQUEST['prarr'];
     $postgdarr=$this->SafeFilter($_REQUEST['prarr']);
        //   print_r($postgdarr);die;
        foreach ($postgdarr as $key => $value) {
            if($value['bynm'] <= 0){
                $return = array(
                    'response' => 0,
                    'result'   => '数量不能为0或者负数！',
                );
                echo json_encode($return);
                die;
            }elseif(floor($value['bynm'])!=$value['bynm']){
                $return = array(
                    'response' => 0,
                    'result'   => '数量必须是整数!',
                );
                echo json_encode($return);
                die;
            }
            $res=$model->updateshopping($value['pcid'],$_SESSION['user_id'],$value['bynm']);
        }
        unset($model);
        if($res){
            $data=array(
                'response'=>1,
                'result'=>'下单成功,正在跳转',
                'jumpurl'=>'index.php?c=user&a=order'
            );
            echo json_encode($data);
            die;
        } else {
            $data=array(
                'response'=>0,
                'result'=>'操作失败'
            );
            echo json_encode($data);
            die;
        }
    }
/**
 * 防SQL注入和XSS攻击
 * @param $arr
 */
public function SafeFilter($arr)
{
   
   $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/','/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/','/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/','/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/','/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');

   if (is_array($arr))
   {
     foreach ($arr as $key => $value)
     {
        if (!is_array($value))
        {
          if (!get_magic_quotes_gpc())             //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
          {
             $value  = addslashes($value);           //给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）加上反斜线转义
          }
          $value       = preg_replace($ra,'',$value);     //删除非打印字符，粗暴式过滤xss可疑字符串
          $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
        }
        else
        {
          $this->SafeFilter($arr[$key]);
        }
     }
   }
   return $arr;
}
    public function control_order()
    {
        $check=$this->checklogin();
        $user_id= $_SESSION['user_id'];
        $addressid=$_REQUEST['addressid'];
        $name= $_SESSION["username"];
        $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');
        $spdata =$model->getuserbuyshopping($user_id);
        foreach ($spdata as $key => $value) {
            $arr[]=$value['productid'];
        }
        if (empty($arr)) {
            unset($model);
            $data=null;
            return $this->view(array('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'] = $spdata[$key]['productnum'];
            $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,
            'check'=>$check,
        );
        unset($model);
        unset($mbrmodel);
        return $this->view($var_array, "member/user_order");
    }

    public function control_submitorder()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'GET' || empty($_SESSION['user_id'])) {
            $data=array(
                'response'=>0,
                'result'=>'非法请求，缺少参数'
            );
            echo json_encode($data);
            die;
        }
        $check=$this->checklogin();
        $user_id= $_SESSION['user_id'];
        $name= $_SESSION["username"];
        $addressid=$_REQUEST['addressid'];
        $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');
        $spdata =$model->getuserbuyshopping($user_id);

        foreach ($spdata as $key => $value) {
            $arr[]=$value['productid'];
        }
        $newarr = array_unique($arr, SORT_REGULAR);
        foreach ($newarr as $key => $value) {
            $pctinfo[] = $model->getOneData($value);
        }

        // 商品信息
        $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'][] = $spdata[$key]['productnum'];
            $odrarr['goodsproductsn'][] = $value[0]['productsn'];
            $odrarr['goodsimg'][]=$value[0]['thumbfiles'];

            $ordarr['orderprice'] += $value[0]['bprice']*$spdata[$key]['productnum'];

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

        $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['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_pay&ordernum='.$ordallnumbr
            );
            echo json_encode($data);

            $model->delshopping($_SESSION["user_id"]);

            unset($model);
            unset($mbrmodel);
            die;
        } else {
            $data=array(
                'response'=>0,
                'result'=>'操作失败'
            );
            echo json_encode($data);
            unset($model);
            unset($mbrmodel);
            die;
        }
    }

    public function control_order_pay(){
        $ordernum=$_REQUEST['ordernum'];
        $model = parent::model('member', 'im');
        $orderinfo= $model->getorderinfo($ordernum);
        $name      = $_SESSION["username"];
        $data=$model->getuserData($name);
        // print_r($data);
        $var_array = array(
            'orderinfo'=>$orderinfo,
            'data'=>$data
        );
        return $this->view($var_array, "member/user_order_pay");
    }

    public function control_order_list(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $user_id      = $_SESSION["user_id"];
        if($user_id==''){
            header('Location: index.php?c=user&a=login');
        }
        $user_id= $_SESSION['user_id'];
        $status=$_REQUEST['status'];
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id'";
        if($status=='1'){
            $searchsql .= " AND user_id='$user_id' AND status='待付款'";
        }elseif($status=='2'){
            $searchsql .= " AND user_id='$user_id' AND status='待发货'";
        }elseif($status=='3'){
            $searchsql .= " AND user_id='$user_id' AND status='待收货'";
        }elseif($status=='4'){
            $searchsql .= " AND user_id='$user_id' AND status='已完成'";
        }
        $orderby = ' ORDER BY time DESC';
        $model = parent::model('member', 'im');
        list($total, $list) = $model->getAllorderList(
            array(
                'page'      => $this->page,
                'pagesize'  => 50,
                'searchsql' => $searchsql,
                'orderby'   => $orderby,
            )
        );
        $mbrdata=$model->getuserDataid($user_id);
        //  print_r($mbrdata);
        foreach ($list as $key=>$value){
            $num = 0;
            $ordernum  =  $value['ordernum'];
            $where = " 1=1 AND ordernum='$ordernum'";
            $goodslist = $model->ordergoodslist($where);
            $goodsid=explode(",", $value['goodsid']);
            // print_r($goodsid);
            foreach($goodslist as $K=>$v){
                $num +=$v['goodsnum'];
                foreach ($goodsid as $k1=>$v1){
                    $goodslist[$k1]['goodsid']=$v1;
                }
            }
            $list[$key]['goodslist']=$goodslist;
            $list[$key]['num']=$num;
        }
        if (parent::$cfg['urlsuffix'] == 'html') {
            $url = parent::$urlpath.$this->catinfo['dirname'].'/';
            $showpage = XPage::indexHtml($total, 2, $this->page, $url, 10);
        }
        else {
            $url = XRequest::getPhpSelf().'?c=user&a=order_list';
            $showpage = XPage::index($total, 2, $this->page, $url, 10);
        }
        // print_r($list);die;
        $var_array             = array(
            'list'             => $list,
            'total'            => $total,
            'check'            => $check,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'status'           => $status,
            'showpage'=>$showpage,
            'mbrdata'=>$mbrdata
        );
        $this->view($var_array, "member/user_order_list");
    }


    public function control_order_detail(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $ordernum=$_REQUEST['order_number'];
        $type=$_REQUEST['type'];
        $model = parent::model('member', 'im');
        $user_id      = $_SESSION["user_id"];
        $mbrdata=$model->getuserDataid($user_id);
        $data=$model->getorderinfo($ordernum);
        $where = " 1=1 AND ordernum='$ordernum'";
        $goodslist = $model->ordergoodslist($where);
        $data['goodslist']=$goodslist;
        if($type=='1'){
            if(!empty($data)){
                $arr['response']=1;
                $arr['data']=$data;
                echo json_encode($arr);die; 
            }else{
                $arr['response']=0;
                $arr['result']='操作失败';
                echo json_encode($arr);die; 
            }
               
        }
        $var_array             = array(
            'data'             => $data,
            'check'            => $check,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'mbrdata'=>$mbrdata
        );
        $this->view($var_array, "member/user_order_detail");
    }
    public function control_confirm(){
        $ordernum=$_REQUEST['order_number'];
        $model = parent::model('product', 'im');
        $res=$model->confirmorder($ordernum);
        if($res){
            $model->confirmgoodsorder($ordernum);
            //最终状态下解冻佣金
            $this->fanyong($ordernum);
            $data=array(
                'response'=>1,
                'result'=>'操作成功',
            );
            echo json_encode($data);
            die;
        } else {
            $data=array(
                'response'=>0,
                'result'=>'操作失败'
            );
            echo json_encode($data);
            die;
        }
    }
    private function fanyong($ordernum){
        $model  = parent::model('member', 'im');
        $loglist = $model->getlog($ordernum);
        foreach ($loglist as $key=>$value){
            $user_data=$model->getuserDataid($value['user_id']);
            $array['integral']=$user_data['integral']+$value['integral'];
            $array['id']=$value['user_id'];
            $res=$model->saveinfo($array);
            if($res){
                $updata['status']='2';
                $updata['id']=$value['id'];
                $model->savelog($updata);
            }
        }
    }
    public function control_account(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );
        return $this->view($var_array, "member/user_account");

    }
    public function control_user_password(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );
        return $this->view($var_array, "member/user_password");

    }
    public function control_user_paypwd(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        //   print_r($data);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'data'             => $data
        );
        return $this->view($var_array, "member/user_paypwd");

    }
    public function control_user_data(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        //   print_r($data);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'data'             => $data
        );
        return $this->view($var_array, "member/user_data");

    }
    public function control_about(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        //   print_r($data);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
        );
        return $this->view($var_array, "member/user_about");

    }
    public function control_feedback(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        //   print_r($data);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'data'=>$data
        );
        return $this->view($var_array, "member/user_feedback");

    }
    public function control_ajaxfeedback(){
        $arr['content']=$_REQUEST['content'];
        $arr['linkmode']=$_REQUEST['linkmode'];
        if($arr['content']==''){
            $data=array(
                'response'=>0,
                'result'=>'反馈内容不能为空'
            );
            echo json_encode($data);
            die;
        }
        if($arr['linkmode']==''){
            $data=array(
                'response'=>0,
                'result'=>'请留下您的联系方式'
            );
            echo json_encode($data);
            die;
        }
        $arr['time']=time();
        $arr['user_id']=$_SESSION["user_id"];
        $model = parent::model('member', 'im');
        $res=$model->addfeedback($arr);
        if($res){
            $data=array(
                'response'=>1,
                'result'=>'操作成功',
            );
            echo json_encode($data);
            die;
        } else {
            $data=array(
                'response'=>0,
                'result'=>'操作失败'
            );
            echo json_encode($data);
            die;
        }
    }

    public function control_share(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);

        list($total, $parent_list)=$model->getparentlist($data['id']);
        $name=array();
        $time=array();
        $xiatotal=array();
        foreach ($parent_list as $k=>$v){
            $name[$k]['value']=$v['name'];
            $time[$k]['value']=$v['create_time'];
            $xiatotal[$k]['value']=$model->getparenttotal($v['id']);
        }
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'data'             => $data,
            'name'             => $name,
            'time'             => $time,
            'total'            => $total,
            'xiatotal'         => $xiatotal,
        );
        return $this->view($var_array, "member/user_share");
    }

    public function control_code(){
        $name  = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        //   print_r($data);die;
        require_once("source/plugin/phpqrcode/phpqrcode.php");
        $value = 'http://192.168.1.5/index.php?c=user&a=register&id='.$data['id'];         //二维码内容
        $errorCorrectionLevel = 'H';  //容错级别
        $matrixPointSize = 6;      //生成图片大小
        //生成二维码图片
        $filename= 'data/attachment/code/'.date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).'.png';
        $QR=QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
        $logo=$data['pic'];
        if($logo==''){
            $logo='tpl/templets/mshop/images/timg.png';
        }
        if (file_exists($logo)) {
            $QR = imagecreatefromstring(file_get_contents($filename));    //目标图象连接资源。
            $logo = imagecreatefromstring(file_get_contents($logo));  //源图象连接资源。
            $QR_width = imagesx($QR);      //二维码图片宽度
            $QR_height = imagesy($QR);     //二维码图片高度
            $logo_width = imagesx($logo);    //logo图片宽度
            $logo_height = imagesy($logo);   //logo图片高度
            $logo_qr_width = $QR_width / 4;   //组合之后logo的宽度(占二维码的1/5)
            $scale = $logo_width/$logo_qr_width;  //logo的宽度缩放比(本身宽度/组合后的宽度)
            $logo_qr_height = $logo_height/$scale; //组合之后logo的高度
            $from_width = ($QR_width - $logo_qr_width) / 2;  //组合之后logo左上角所在坐标点
            //重新组合图片并调整大小
            /*
             * imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
             */
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
        }
        imagepng($QR, $filename);

        $arr['codeimg']=$filename;
        $arr['id'] = $data['id'];
        $res        = $model->saveinfo($arr);
        if ($res) {
            $data = array(
                'response' => 1,
                'result'   => '操作成功',
                'codeimg'  => $filename
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '操作失败'
            );
            echo json_encode($data);
            die;
        }
    }

    public function control_profit(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $check     = $this->checklogin();
        $user_id      = $_SESSION["user_id"];
        if($user_id==''){
            header('Location: index.php?c=user&a=login');
        }
        $type=$_REQUEST['type'];
        $searchsql = " 1=1";
        $searchsql .= " AND user_id='$user_id'";
        if($type){
            $searchsql .= " AND user_id='$user_id' AND type='$type'";
        }
        $orderby = ' ORDER BY time DESC';
        $model = parent::model('member', 'im');
        list($total, $list) = $model->getAllprofitList(
            array(
                'page'      => $this->page,
                'pagesize'  => $this->pagesize,
                'searchsql' => $searchsql,
                'orderby'   => $orderby,
            )
        );
        $var_array             = array(
            'list'             => $list,
            'total'            => $total,
            'check'            => $check,
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'status'           => $type
        );
        $this->view($var_array, "member/user_profit");
    }

    public function control_user_balance(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        //   print_r($data);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'data'             => $data
        );
        return $this->view($var_array, "member/user_balance");
    }
    public function control_recharge(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        //   print_r($data);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'data'             => $data
        );
        return $this->view($var_array, "member/user_recharge");
    }
    public function control_ajaxaddorder()
    {

        if ($_POST['price'] == '0') {
            $data = array(
                'response' => 0,
                'result'   => '充值金额不能为0'
            );
            echo json_encode($data);
            die;
        }
        if ($_POST['member_id'] == '0') {
            $data = array(
                'response' => 0,
                'result'   => '参数错误'
            );
            echo json_encode($data);
            die;
        }
        $arr['price']        = $_POST['price'];
        $arr['member_id']    = $_POST['member_id'];
        $arr['order_number'] = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $arr['time']         = time();
        $model               = parent::model('member', 'im');
        $data                = $model->addorder($arr);
        if ($data) {
            $data = array(
                'response'     => 1,
                'order_number' => $arr['order_number'],
                'order_name'   => 'LJSHOP 增值服务',
                'oeder_price'  => $arr['price']
            );
            echo json_encode($data);
            die;
        } else {
            $data = array(
                'response' => 0,
                'result'   => '参数错误'
            );
            echo json_encode($data);
            die;
        }
    }
    public function control_pay_wan()
    {
        $option = $_REQUEST['option'];
        $action = $_REQUEST['action'];
        $model  = parent::model('member', 'im');
        $data   = $model->getpayorderinfo($option);

        if ($data['status'] == '0') {
            $userinfo          = $model->getuserDataid($data['member_id']);
            $info['balance']     = $userinfo['balance'] + $data['price'];
            $info['id'] = $data['member_id'];
            $res               = $model->saveinfo($info);
            if ($res) {
                $arr['`desc`']     = '通过' . $action . "充值" . $data['price'] . "元";
                $arr['price']      = $data['price'];
                $arr['user_money'] = $info['balance'];
                $arr['time']       = time();
                $arr['type']       = '1';
                $arr['user_id']    = $data['id'];
                $res1              = $model->addlog1($arr);
                if ($res1) {
                    $res           = $model->payorder($option);
                    $data1['slay'] = 1;
                    $data1["msg"]  = "修改成功";
                    echo json_encode($data1);

                }
            }

        }
    }

    public function control_order_pay_wan(){
        $option = $_REQUEST['ordernum'];
        $model  = parent::model('product', 'im');
        $data   = $model->getorderinfo($option);
        $var_array             = array(
            'data'             => $data
        );
        return $this->view($var_array, "member/order_pay_wan");
    }

    public function control_tixian(){
        $this->isLogin();
        list($page_title, $page_description, $page_keyword) = XSeo::buildSeo("ch_user", null, $this->catinfo);
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        //   print_r($data);
        $var_array             = array(
            'page_title'       => $page_title,
            'page_description' => $page_description,
            'page_keyword'     => $page_keyword,
            'data'             => $data
        );
        return $this->view($var_array, "member/user_tixian");
    }
    public function control_ajaxaddtixian(){
        $price=$_REQUEST['price'];
        $paypwd=$_REQUEST['paypwd'];
        $name      = $_SESSION["username"];
        $model = parent::model('member', 'im');
        $data=$model->getuserData($name);
        if($data['paypwd']!=md5($paypwd)){
            $data = array(
                'response' => 0,
                'result'   => '支付密码错误！'
            );
            echo json_encode($data);
            die;
        }
        if($price>$data['balance']){
            $data = array(
                'response' => 0,
                'result'   => '余额不足！'
            );
            echo json_encode($data);
            die;
        }
        $save['balance']=$data['balance']-$price;
        $save['id']=$data['id'];
        $res=$model->saveinfo($save);
        if($res){
            $arr['order_number']=date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $arr['user_id']=$data['id'];
            $arr['time']=time();
            $arr['price']=$price;
            $model->addtiorder($arr);
            $data = array(
                'response' => 1,
                'result'   => '提现成功，我们会在2-3个工作日之内方法到您的账户'
            );
            echo json_encode($data);
            die;
        }else{
            $data = array(
                'response' => 0,
                'result'   => '未知错误！'
            );
            echo json_encode($data);
            die;
        }


    }

    /**
     * 支付页面
     */
    public function control_express(){
        $check     = $this->checklogin();
        $name      = $_SESSION["username"];
        if($name==''){
            header('Location: index.php?c=user&a=login');
        }
        $model     = parent::model('member', 'im');
        $data      = $model->getuserData($name);
        $user_id   = $data['id'];
        $no=date("H",time());
        if ($no>0&&$no<=6){
            $hao =  "凌晨好";
        }
        if ($no>6&&$no<12){
            $hao =  "上午好";
        }
        if ($no>=12&&$no<=18){
            $hao =  "下午好";
        }
        if ($no>18&&$no<=24){
            $hao =  "晚上好";
        }
        $id=intval($_REQUEST['id']);
        $order_info=parent::$obj->fetch_first("select * from 8cms_order where id=$id");
        $var_array             = array(
            'data'             => $data,
            'order_info'=>$order_info,
            'hao'=>$hao,
            'type'=>$_GET['type'],
//            'total'=>$total
        );
//        print_r($var_array);die;
        $this->view($var_array, "member/express");
    }
    public function control_get_express(){
        $shipping_code=$_REQUEST['shipping_code'];
        $invoice_no=$_REQUEST['invoice_no'];
        $phone=$_REQUEST['phone'];
        $phone=substr($phone,-4);
        $requestData= "{'CustomerName':'$phone','ShipperCode':'SF','LogisticCode':'$invoice_no'}";
        $EBusinessID='1329259';
        $AppKey='bc85e05b-80f3-493f-9196-8f439b067a66';
        $ReqURL='http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';
        $datas = array(
            'EBusinessID' => $EBusinessID,
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $AppKey);
        $result=$this->sendPost($ReqURL, $datas);
        $data=json_decode($result);
        $data->Traces=array_reverse($data->Traces);
        echo json_encode($data);die;
    }
    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }
       public function control_ajaxorder_wx()
    {
        include_once("source/plugin/wxpay/WxPayPubHelper/WxPayPubHelper.php");

        //print_r(NOTIFY_URL_WL);die;
        //使用统一支付接口
        $unifiedOrder = new UnifiedOrder_pub();
        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $_REQUEST['order_number'];
        //订单名称，必填
        $subject = $_REQUEST['order_name'];
       // echo $out_trade_no;
        //付款金额，必填
        $total_fee = $_REQUEST['order_price']*100;
        //商品描述，可空
        $body = $_REQUEST['order_name'];
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("body", "$body");//商品描述
        //自定义订单号，此处仅作举例
        $timeStamp = time();


        $unifiedOrder->setParameter("out_trade_no", "$out_trade_no");//商户订单号
        $unifiedOrder->setParameter("total_fee", "$total_fee");//总金额
        $unifiedOrder->setParameter("notify_url", NOTIFY_URL);//通知地址
        $unifiedOrder->setParameter("trade_type", "NATIVE");//交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID

        //获取统一支付接口结果
        $unifiedOrderResult = $unifiedOrder->getResult();

        //商户根据实际情况设置相应的处理流程
        if ($unifiedOrderResult["return_code"] == "FAIL") {
            //商户自行增加处理流程
            echo "通信出错：" . $unifiedOrderResult['return_msg'] . "<br>";
        } elseif ($unifiedOrderResult["result_code"] == "FAIL") {
            //商户自行增加处理流程
            echo "错误代码：" . $unifiedOrderResult['err_code'] . "<br>";
            echo "错误代码描述：" . $unifiedOrderResult['err_code_des'] . "<br>";
        } elseif ($unifiedOrderResult["code_url"] != NULL) {
            //    print_r($unifiedOrderResult);die;
            //从统一支付接口获取到code_url
            $code_url = $unifiedOrderResult["code_url"];
            $data = array(
                'response' => 1,
                'code_url' => $code_url,
                'order_number' => $out_trade_no,
            );
            echo json_encode($data);
            die;
        }
    }
        public function control_order_query()
    {
        include_once("source/plugin/wxpay/WxPayPubHelper/WxPayPubHelper.php");

        //退款的订单号
        if (!isset($_REQUEST["out_trade_no"])) {
            $out_trade_no = " ";
        } else {
            $out_trade_no = $_REQUEST["out_trade_no"];

            //使用订单查询接口
            $orderQuery = new OrderQuery_pub();
            //设置必填参数
            //appid已填,商户无需重复填写
            //mch_id已填,商户无需重复填写
            //noncestr已填,商户无需重复填写
            //sign已填,商户无需重复填写
            $orderQuery->setParameter("out_trade_no", "$out_trade_no");//商户订单号
            //非必填参数，商户可根据实际情况选填
            //$orderQuery->setParameter("sub_mch_id","XXXX");//子商户号
            //$orderQuery->setParameter("transaction_id","XXXX");//微信订单号

            //获取订单查询结果
            $orderQueryResult = $orderQuery->getResult();

            //商户根据实际情况设置相应的处理流程,此处仅作举例
            if ($orderQueryResult["return_code"] == "FAIL") {
                echo "通信出错：" . $orderQueryResult['return_msg'] . "<br>";
            } elseif ($orderQueryResult["result_code"] == "FAIL") {
                echo "错误代码：" . $orderQueryResult['err_code'] . "<br>";
                echo "错误代码描述：" . $orderQueryResult['err_code_des'] . "<br>";
            } else {
                echo $orderQueryResult['trade_state'];
                exit();
//                echo "交易状态：".$orderQueryResult['trade_state']."<br>";
//                echo "设备号：".$orderQueryResult['device_info']."<br>";
//                echo "用户标识：".$orderQueryResult['openid']."<br>";
//                echo "是否关注公众账号：".$orderQueryResult['is_subscribe']."<br>";
//                echo "交易类型：".$orderQueryResult['trade_type']."<br>";
//                echo "付款银行：".$orderQueryResult['bank_type']."<br>";
//                echo "总金额：".$orderQueryResult['total_fee']."<br>";
//                echo "现金券金额：".$orderQueryResult['coupon_fee']."<br>";
//                echo "货币种类：".$orderQueryResult['fee_type']."<br>";
//                echo "微信支付订单号：".$orderQueryResult['transaction_id']."<br>";
//                echo "商户订单号：".$orderQueryResult['out_trade_no']."<br>";
//                echo "商家数据包：".$orderQueryResult['attach']."<br>";
//                echo "支付完成时间：".$orderQueryResult['time_end']."<br>";
            }
        }
    }
}
?>


