<?php
namespace Smi\Controller;

use Think\Controller;
use Api\Controller\ApiController;
//use \Curl;

//use Think\Cache;

header("Content-Type:text/html;CharSet=UTF-8");
class SyssetController extends BaseController
{
    protected $dada;// 达达配送实例
    /**
     * 个人信息修改
     */
    public function edit_info()
    {
        if (IS_POST) {
            $data = I('post.');
            // 检测商户地址格式非法性
            $matchs = array();
            //$address_preg = '/^([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff]+区|县)([\x7f-\xff_a-zA-Z0-9]+)$/';
           /* $address_preg = '/^([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff_a-zA-Z0-9]+)$/';
            preg_match($address_preg, $data['business_address'], $matchs);
            if (empty($matchs[2]) || empty($matchs[3]) || empty($matchs[4])) {
                $this->error('商户地址入录非法！');die;  
            } */

            $delFile = M('admin')->where(array('id' => $data['id']))->getField("picture");
            $del_picture_environment = M('admin')->where(array('id' => $data['id']))->getField("picture_environment");
            // 商户LOGO上传
            if ($_FILES['picture']['error'] === 0) {
                $upload = new \Think\Upload();    // 实例化上传类   
                // $upload -> key = 'picture'; 
                // $upload->maxSize = 3145728 ;    // 设置附件上传大小 
                // 设置附件上传类型       
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath = './Uploads/';    // 设置附件上传根目录 
                $upload->savePath = 'admin_busisness/';    // 设置附件上传目录  
                $upload->autoSub = false;    //不要子文件夹
                // 上传文件
                $info = $upload->uploadOne($_FILES['picture']);
      
                if(!$info) {
                    // 上传错误提示错误信息                        
                    $this->error($upload->getError());die;
                }else{
                    // 上传成功 获取上传文件信息
                    $pic = $info["savepath"] . $info["savename"];
                    $data['picture'] = $pic;    // 修改数据对象
                }
            }
            
            // 商户换金图片上传
            if (!empty($_FILES['picture_environment']) && $_FILES['picture_environment']['error'] === 0) {
                $upload = new \Think\Upload();    // 实例化上传类    
                // $upload -> key = 'picture_environment'; 
                // $upload->maxSize = 3145728 ;    // 设置附件上传大小 
                // 设置附件上传类型       
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath = './Uploads/';    // 设置附件上传根目录 
                $upload->savePath = 'admin_busisness/';    // 设置附件上传目录  
                $upload->autoSub = false;    //不要子文件夹
                // 上传文件
                $info = $upload->uploadOne($_FILES['picture_environment']);

                if(!$info) {
                    // 上传错误提示错误信息                        
                    $this->error($upload->getError());die;
                }else{
                    // 上传成功 获取上传文件信息
                    $pic = $info["savepath"] . $info["savename"];
                    $data['picture_environment'] = $pic;    // 修改数据对象
                }
            }
            $result = M('admin')->save($data);
            // dump(M()->getLastSql());
            if ($result) {
                if (isset($data['picture'])) {
                    @unlink("./Uploads/{$delFile}");    // 删除旧图
                    session('picture', $data['picture']);
                } 
                if (isset($data['picture_environment'])) {
                    @unlink("./Uploads/{$del_picture_environment}");    // 删除旧图
                } 
                session('admin', $data['username']);
                $this->success('Successfully Edited');die;
            } else {
                $this->error('Fail to Save');die;
            }
        }

        $info = M('admin')->where(array('id' => session('admin_id')))->limit(1)->select()[0];
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 微信配置
     */
    public function edit_wechat()
    {
        // $info = M('admin')->where(array('id' => session('admin_id')))->find();

        // if ($info['is_business'] == 1) {
        //     $this->error('您没有访问权限');
        // }
        if ($_POST) {
            $info = M('wechat_config')->where(array('admin_id' => session('admin_id')))->limit(1)->select();
            if (empty($info)) {
                $_POST['create_time'] = time();
                $_POST['admin_id'] = session('admin_id');
                
                if (M('wechat_config')->add($_POST)) {
                    $this->success('Save success');die;
                } else {
                    $this->error('Save failed');die;
                }
            } else {
                $_POST['edit_time'] = time();
                $result = M('wechat_config')->where(array('id' => $_POST['id']))->save($_POST);
                if ($result) {
                    $this->success('Successfully Edited');die;
                } else {
                    $this->error('Fail to Saved');die;
                }
            }
        }

        $config = M('wechat_config')->where(array('admin_id' => session('admin_id')))->limit(1)->select()[0];

        $this->assign('config', $config);
        $this->display();
    }



    /**
     * 商户桌位号
     */
    public function index_seats($id = '')
    {
        $business_id = session('admin_id');
        $layer = M('table')->where(array('admin_id' => $business_id, 'pid' => 0))->select();
        $count = M('table')->where(array('admin_id' => $business_id, 'pid' => empty($id) ? $layer[0]['id'] : $id))->count();
        $Page = new \Think\Page($count, 15);
        $show = $Page->show();
        $table = M('table')->where(array('admin_id' => $business_id, 'pid' => empty($id) ? $layer[0]['id'] : $id))->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $seatlist = $this->seat_list();
        
        $layer_list = array();
        $seat_list = array();
        foreach ($seatlist as $key => $value) {
            $layer_list[] = $key;
            $seat_list[] = $value;
        }

        foreach ($layer as $key => $value) {
            foreach ($table as $k => &$v) {
                if ($value['id'] == $v['pid']) {
                    $v['layer'] = $value['name'];
                    $seat_index = '';
                    foreach ($seat_list as $kk => $vv) {
                        foreach ($vv as $kkk => $vvv) {
                            if ($vvv['id'] == $v['id']) {
                                $seat_index = $kkk;
                                break;
                            }
                        }
                        if ($seat_index !== '') {
                            break;
                        }
                    }
                    $v['ercode_url'] = $this->getwxacodeunlimit_url($v['id'], $key, $seat_index);
                }
            }
        }
        
        // $seat_list = $this->seats_list($business_id);
        // // dump($seat_list);die;
        // foreach ($table as $key => &$value) {
        //     foreach ($seat_list as $k => $v) {
        //            foreach ($v as $kk => $vv) {
        //                if ($vv['id'] == $value['id']) {
        //                  $value['layer'] = $k;
        //                  $value['ercode_url'] = $this->getwxacodeunlimit_url($value['id'], $k, $kk);
        //                  // $value['ercode_url'] = $this->getwxacodeunlimit_url($value['id'], $k, $vv['name']);
        //                  break;
        //                }
        //            }
        //     }   
        // }

        $this->assign('page', $show);
        $this->assign('layer', $layer);
        $this->assign('table', $table);// dump($table);die;
        $this->display();
    }

    /**
     * [seat_list 获取所有的桌位号列表]
     * @AuthorHTL
     * @DateTime  2018-02-23T18:21:25+0800
     * @return    [type]                   [description]
     */
    private function seat_list()
    {
        $array = M('table')->where(array('admin_id' => session('admin_id')))->field('id, name, pid')->select();
        if (!is_array($array)) return false;
        $arr = array();
        foreach ($array as $key => $value) {
            if ($value['pid'] == 0) {
                foreach ($array as $k => $v) {
                    if ($v['pid'] != 0 && $v['pid'] == $value['id']) {
                        // $arr[$value['name']][] = $v['name'];
                        $arr[$value['name']][] = ['id' => $v['id'], 'name' => $v['name']];
                    }
                }
            }
        }
        // dump(json_decode(json_encode($arr), true));
        // echo 111;
        // die;
        return $arr;
    }

     /**
     * 添加桌位
     */
    public function add_seat()
    {   
        if ($_POST) {
            // if (preg_match_all("/([\x{4e00}-\x{9fa5}]+)/u", $_POST['table'], $match)) {       
            //     $this->error("提示：桌位号不能含有中文！");die;
            // }
            $data = [
                'pid' => $_POST['layer_id'],
                'name' => $_POST['table'],
                'admin_id' => session('admin_id'),
                'create_time' => time(),
            ];
            if (M('table')->add($data)) {
                $this->success('Successfully Saved');die;
            } else {
               $this->error('Add failure');die;
            }
            
        }

        $layer = M('table')->where(array('admin_id' => session('admin_id'), 'pid' => 0))->select();
        $this->assign('layer', $layer);
        $this->display();
    }

     /**
     * 删除桌位或删除楼层
     */
    public function delete($id = '') 
    {
        $this->check_layer_have_seat($id);
        if (M('table')->delete($id)) {
            $this->success('Successfully Deleted');
        }  else {
            $this->error('Delete failed');
        }
    }

     /**
     * 编辑桌位
     */
    public function edit_seat($id = '')
    {
        if ($_POST) {
            // if (preg_match_all("/([\x{4e00}-\x{9fa5}]+)/u", $_POST['table'], $match)) {       
            //     $this->error("提示：桌位号不能含有中文！");die;
            // }
            $data = ['id' => $_POST['id'], 'pid' => $_POST['layer_id'], 'name' => $_POST['table'], 'update_time' => time()];
            if (M('table')->save($data)) {
                $this->success('Successfully Edited');die;
            }  else {
                $this->error('Fail to Saved');die;
            }
        }

        $layer = M('table')->where(array('admin_id' => session('admin_id'), 'pid' => 0))->select();
        $item = M('table')->where(array('id' => $id))->find();
        $this->assign('layer', $layer);
        $this->assign('item', $item);
        $this->display('add_seat');
    }

     /**
     * 楼层列表
     */
    public function layer_list()
    {
        $count = M('table')->where(array('admin_id' => session('admin_id'), 'pid' => 0))->count();
        $Page = new \Think\Page($count, 15);
        $show = $Page->show();
        $layer_list = M('table')->where(array('admin_id' => session('admin_id'), 'pid' => 0))->select();
        $this->assign('layer_list', $layer_list);
        $this->assign('page', $show);
        $this->display();
    }

     /**
     * 添加楼层
     */
    public function add_layer()
    {
        if ($_POST) { 
            // if (preg_match_all("/([\x{4e00}-\x{9fa5}]+)/u", $_POST['layer'], $match)) {       
            //     $this->error("提示：楼层名不能含有中文！");die;
            // }
            $data = [
                    'pid' => 0,
                    'admin_id' => session('admin_id'),
                    'name' => $_POST['layer'],
                    'create_time'   =>   time()
                ];
            if (M('table')->add($data)) {
                $this->success('Successfully Saved');die;
            } else {
                $this->error('Add failure');die;
            }
        }

        $this->display();
    }

     /**
     * 编辑楼层
     */
    public function edit_layer($id = '')
    {
        if ($_POST) {
            // if (preg_match_all("/([\x{4e00}-\x{9fa5}]+)/u", $_POST['layer'], $match)) {       
            //     $this->error("提示：楼层名不能含有中文！");die;
            // }
            $data = ['id' => $_POST['id'], 'name' => $_POST['layer'], 'update_time' => time()];
            if (M('table')->save($data)) {
                $this->success('Successfully Edited');die;
            } else {
                $this->error('Fail to Saved');die;
            }
        }
        $item = M('table')->where(array('id' => $id))->limit(1)->select();
        $this->assign('item', $item[0]);
        $this->display('add_layer');
    }

     /**
     * 判断该楼层下是否有桌位
     */
    private function check_layer_have_seat($id = '')
    {
        $result = M('table')->where(array('pid' => $id))->limit(1)->select();
        if (!empty($result)) {
           $this->error('There is a table number under this floor, which cannot be deleted');die;
       }
    }

    /**
     * 获取微信配置
     */
    private function get_wechat_param()
    {
        $config = M('wechat_config')->where(array('admin_id' => session('admin_id')))->find();
        if (empty($config)) {
            return false;
        } else {
            return $config;
        }
    }

    /**
     * 获取access_token
     * @return mixed|resource
     */
    private function get_access_token()
    {   
        $business_id = session('admin_id');
        $access_token = S($business_id.'_access_token');
        if ($access_token) {
//            echo 1122;die;
            return $access_token;
        } else {
            $param = $this->get_wechat_param();
//            dump($param);
            if (!$param) return false;
//            dump('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$param['appid'].'&secret='.$param['appsecret']);die;
            $return = curlGet('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$param['appid'].'&secret='.$param['appsecret']);
//            dump($return);die;
            if (!$return) return false;
            $json_arr = json_decode($return, true);
            S($business_id.'_access_token', $json_arr['access_token'], array('type' => 'file', 'expire' => $json_arr['expires_in']));
            return $json_arr['access_token'];
        }
    }

    /**
     * 桌子二维码路径
     * @param int $type
     * @param string $scene
     * @param string $page
     * @param int $width
     * @param bool $auto_color
     * @param string $line_color
     * @return bool|string
     */
    // $layer不能中文
    public function getwxacodeunlimit_url($id, $layer = '', $table = '', $type = 1, $page = 'pages/index/index', $width = 430, $auto_color = true, $line_color = '{"r":"0","g":"0","b":"0"}')
    {   
        $access_token = $this->get_access_token();
        $host = "https://api.weixin.qq.com";
        $path = "/wxa/getwxacodeunlimit";
        $method = "POST";
        $headers = array();
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = 'access_token='.$access_token;
        $bodys = array(
                    'scene' => 'business_id='.session('admin_id').'&table='.$table.'&layer='.$layer,// 长度最长32位
                    // 'scene' => 'business_id='.session('admin_id').'&table_id='.$id.'&layer='.$layer,
                    'page' => $page,
                    'width' => $width,
                    // 'auth_color' => $auth_color,
                    // 'line_color' => $line_color,
                );
        // dump($bodys);
        $bodys = json_encode($bodys);
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $data = curl_exec($curl);
        // if (!empty($data)) {
        //     M('table')->where(array('id' => $id))->save(array('img' => $data));
        // }
        $base64 = base64_encode($data);
        $mime = 'image/png';
        $data = 'data:' . $mime . ';base64,' . $base64;
        // dump($data);die;
        return $data;
    }
    /**
     * 所有打印机列表
     */
    public function print_list($search = '')
    {   
        $where = array();
        if (!empty($search)) {
            $where['print_name|uuid|business_name|am_admin.id'] = ['like', '%'.$search.'%'];
        }
        // $where['is_business'] = 1;

        $count = M('print')
        ->join('am_admin ON admin_id = am_admin.id')
        ->where($where)
        ->count();

        $Page = new \Think\Page($count, 15);
        $show = $Page->show();
        
        $list = M('print')
        ->join('am_admin ON am_admin.id = am_print.admin_id')
        ->where($where)
        ->field('am_print.id, print_name, business_name, uuid, am_print.create_time')
        ->limit($Page->firstRow, $Page->listRows)
        ->select();
        
        $this->assign('search', $search);
        $this->assign('page', $show);
        $this->assign('list', $list);// dump($list);die;
        $this->display();
    }

    /**
     * 删除打印机
     */
    public function print_delete($id = '')
    {
        $print = M('print')
            ->join('am_admin ON am_admin.id = am_print.admin_id')
            ->where(array('am_print.id' => $id))->find();
        if ($print['is_business'] == 2) {// 没有与商户号绑定
            if (M('print')->delete($id)) {
                $this->success('Successfully Deleted');die;
            } else {
                $this->error('Delete failed');die;
            }
        } else {
            $this->error('The printer has been bound to merchant and cannot be deleted');die;
        }
    }

    /**
     * 编辑打印机
     */
    public function print_edit($id = '')
    {
        if ($_POST) {
            $data = $_POST;
            // dump($data);// die;
            $info = M('print')
                ->join('am_admin ON am_print.admin_id = am_admin.id')
                ->where(array('am_print.id' => $data['id']))
                ->select();// 更新前打印机设备信息

            // 设备绑定商户id
            $admin = M('admin')->where(array('id' => $data['business_id']))->find();// 需要绑定设备的商户信息
            
            if ($info[0]['admin_id'] != $data['business_id']) {
                $return = $this->duiduiji_userbind($data['uuid'], $data['business_id']);
                $return = json_decode($return, true);
                // dump($return);die;
                if ($return['Code'] != 200) {
                    $this->error('Device and merchant binding failed, update failed!');die;
                }
                $data['open_user_id'] = $return['OpenUserId'];
            }
            $data['admin_id'] = $data['business_id'];
            $data['update_time'] = time();

            if (M('print')->save($data)) {
                $this->success('Successfully Edited');die;
            } else {
                $this->error('Fail to Saved');die;
            }
        }

        $item = M('print')->where(array('id' => $id))->find();
        $business_list = M('admin')->where(array('is_business' => 1, 'status' => 1))->select();
        $this->assign('business_list', $business_list);
        $this->assign('legend', 'Edit equipment');
        $this->assign('item', $item);
        $this->display('print_add');
    }

    /**
     * 添加打印机
     */
    public function print_add()
    {   
        if ($_POST) {
            $data = $_POST;
            $result = M('print')->where(array('uuid' => $data['uuid']))->limit(1)->select();
            // dump($result);
            if (!empty($result)) {
                $this->error('The number device already exists, adding failed');die;
            }

            // 设备绑定商户id
            $admin = M('admin')->where(array('id' => $data['business_id']))->find();
            if ($admin['is_business'] == 1) {
                $return = $this->duiduiji_userbind($data['uuid'], $data['business_id']);
                $return = json_decode($return, true);
                // dump($return);die;
                if ($return['Code'] != 200) {
                    $this->error('Failed to bind the device to the merchant. Failed to add!');die;
                }
                $data['open_user_id'] = $return['OpenUserId'];
            }

            $data['create_time'] = time();
            $data['admin_id'] = $data['business_id'];
            // dump($data);die;
            if (M('print')->add($data)) {
                $this->success('Successfully Saved');die;
            } else {
                $this->error('Add failure');die;
            }
        }
        $business_list = M('admin')->where(array('is_business' => 1, 'status' => 1))->select();
        $this->assign('business_list', $business_list);
        $this->assign('legend', 'Add new equipment');
        $this->display('print_add');
    }

    /**
     * 打印机配置
     */
    public function print_config()
    {
        if ($_POST) {
            $config_info = M('print_config')->limit(1)->select();
            if (empty($config_info)) {
                if (M('print_config')->add($_POST)) {
                    $this->success('Save success');die;
                } else {
                    $this->error('Save failed');die;
                }
            } else {
                if (M('print_config')->save($_POST)) {
                    $this->success('Successfully Edited');die;
                } else {
                    $this->error('Fail to Saved');die;
                }
            }
            
        }
        $item = M('print_config')->limit(1)->select();
        if (!empty($item)) {
            $this->assign('item', $item[0]);
        }

        $this->display();
    }

    private function get_duiduiji_base_url()
    {
        $url =  'http://www.open.mstching.com/home/';
        return $url;
    }

    private function get_duiduiji_appkey_appsecret()
    {
        $result = M('print_config')->limit(1)->select();
        if (empty($result)) {
            return false;
        } else {
            return $result[0];
        }
    }

    private function get_duiduiji_url_param()
    {
        $app_config = $this->get_duiduiji_appkey_appsecret();

        if (empty($app_config)) return false;

        $param = array();
        $param['appid'] = $app_config['app_key'];
        // $param['appsecret'] = $app_config['app_secret'];
        $param['nonce'] = strval(mt_rand(10000001, 99999999));
        $param['timestamp'] = strval(time());

        $params['appsecret'] = $app_config['app_secret'];
        $params['nonce'] = $param['nonce'];
        $params['timestamp'] = $param['timestamp'];
        asort($params, SORT_LOCALE_STRING);
        $str = '';
        foreach ($params as $value) {
            $str .= $value;
        }

        $param['signature'] = sha1($str);
        return $param;

    }

    private function duiduiji_userbind($uuid = '', $user_id = '')
    {
        $data_param_ = $this->get_duiduiji_url_param();
        // dump($data_param_);
        $url = $this->get_duiduiji_base_url();
        $post_data = array('Uuid' => $uuid, 'UserId' => $user_id);
        // dump($url.'userbind');
        // dump($post_data);
        // dump($data_param_);die;
        $return = ApiController::request_post($url.'userbind', true, $post_data, $data_param_);
        // dump($return);die;
        return $return;
    }

    /**
     * 会员设置
     */
    public function member()
    {
        $item = M('member_config')->where(array('admin_id' => $this->business_id))->find();

        if (empty($item)) {
            M('member_config')->add(array('admin_id' => $this->business_id, 'create_time' => time()));
            $item = M('member_config')->where(array('admin_id' => $this->business_id))->find();
        }

        $data = I('post.');
        if (!empty($data)) {
             $preg  = '/\d+:\d+/';
             $preg_result = array();
             preg_match($preg, $data['int_rate'],  $preg_result);
             if (empty($preg_result)) {
                $this->error('Please enter the correct format');die;
             }
             $save = array(
                        'int_rate' => $data['int_rate'],
                        'update_time' => time()
                    );
                $result = M('member_config')->where(array('id' => $data['id']))->save($save);

            if ($result) {
                $this->success('Successfully Saved');die;
            } else {
                $this->error('The operation failure');die;
            }
        }
        
        $this->assign('info', $item);
        $this->display();
    }

    /**
     * 预约配置
     */
    public function appointment_config()
    {
        $data = I('post.');

        if (!empty($data) && !empty($data['status'])) {
            $save = array(
                    'status' => $data['status'],
                    'money' => $data['money'],
                    'update_time' => time()
                );

            $result = M('appointment_config')->where(array('id' => $data['id']))->save($save);

            if ($result) {
                $this->success('Successfully Edited');die;
            } else {
                alertMsg('Fail to Saved');die;
            }
        }

        $info = M('appointment_config')->where(array('admin_id' => $this->business_id))->find();

        if (empty($info)) {
            M('appointment_config')->add(array('admin_id' => $this->business_id, 'create_time' => time()));
             $info = M('appointment_config')->where(array('admin_id' => $this->business_id))->find();
        }

        $this->assign('info', $info);
        $this->display();
    }

    //招商信息填写
    public function InvestmentInformation(){
    	$adminId = session('admin_id');

    	if(IS_POST){
    		$data['id'] = $adminId;
    		$data['investment_information'] = I('post.content');

    		$success = M('Admin') -> save($data);
    		if($success){
    			$this -> success('Successfully Edited',U('InvestmentInformation'));
    		}else{
    			$this -> error('Fail to Saved');
    		}

    	}else{
    		$data = M('Admin') -> field('investment_information') -> find($adminId);

    		$this -> assign('data',$data);

    		$this -> display('investment_information');
    	}
    	
    }

    //首页展示图片列表
    public function IndexShowPicture(){
		$adminId = session('admin_id');

		$data = M('Index_show_picture') -> field('id,picture') -> where("admin_id = {$adminId}") -> order('id DESC') -> select();

		$this -> assign('data',$data);

		$this -> display('index_show_picture');
    }

    //添加首页展示图片
    public function AddIndexShowPicture(){
    	$data['admin_id'] = session('admin_id');

    	if ($_FILES['picture']['error'] === 0) {
            $upload = new \Think\Upload();    // 实例化上传类    
            // $upload->maxSize = 3145728 ;    // 设置附件上传大小 
            // 设置附件上传类型       
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->rootPath = './Uploads/';    // 设置附件上传根目录 
            $upload->savePath = 'index_picture/';    // 设置附件上传目录  
            $upload->autoSub = true;    //不要子文件夹
            // 上传文件
            $info = $upload->upload();
            if(!$info) {
                // 上传错误提示错误信息                        
                $this->error($upload->getError());die;
            }else{
                // 上传成功 获取上传文件信息
                $pic = $info['picture']["savepath"] . $info['picture']["savename"];
                $data['picture'] = $pic;    // 修改数据对象
            }
        }

        $success = M('Index_show_picture') -> add($data);
        if($success){
        	$this -> success('Successfully Saved',U('IndexShowPicture'));
        }else{
        	$this -> error('Add failure');
        }
    }

    //删除首页展示图片
    public function DelIndexShowPicture(){
    	$adminId = session('admin_id');
    	$id = I('get.id');

    	$picture = M('Index_show_picture') -> where("id = {$id}") -> getField('picture');

    	$success = M('Index_show_picture') -> where("id = {$id} AND admin_id = {$adminId}") -> delete();
    	if($success){
    		unlink('./Uploads/'.$picture);
        	$this -> success('Successfully Deleted',U('IndexShowPicture'));
        }else{
        	$this -> error('Delete failed');
        }
    }

    //签到积分设置
    public function SignInPointSet(){
    	$adminId = session('admin_id');
    	if(IS_POST){
    		$data['id'] = $adminId;
    		$data['sign_in'] = I('post.sign_in');

    		$success = M('Admin') -> save($data);
    		if($success){
        		$this -> success('Modify the success',U('SignInPointSet'));
	        }else{
	        	$this -> error('Modify the failure');
        	}
    	}else{
    		$data = M('Admin') -> field('sign_in') -> find($adminId);

    		$this -> assign('data',$data);
    		$this -> display('sign_in_point_set');
    	}
    }

    /**
     * [member_level 会员等级设置]
     * @AuthorHTL
     * @DateTime  2018-02-08T14:28:11+0800
     * @return    [type]                   [description]
     */
    public function member_level()
    {   
        $list = M('member_level')->where(array('admin_id' => session('admin_id')))->select();
        $this->assign('list', $list);
        $this->display();        
    }

    /**
     * [member_add 添加会员等级]
     * @AuthorHTL
     * @DateTime  2018-02-08T14:37:02+0800
     * @return    [type]                   [description]
     */
    public function level_add()
    {
        $data = I('post.');

        if (!empty($data)) {
            $add = array(
                    'admin_id' => session('admin_id'),
                    'level_name' => $data['level_name'],
                    'money' => $data['money'],
                    'create_time' => time(),
                    'update_time' => time()
                );
            $result = M('member_level')->add($add);
        
            if ($result) {
                $this->success('Successfully Saved');die;
            } else {
                $this->error('Add failure');die;
            }
        }

        $this->assign('op', 'Add');
        $this->display();
    }

    /**
     * [member_add 编辑会员等级]
     * @AuthorHTL
     * @DateTime  2018-02-08T14:37:02+0800
     * @return    [type]                   [description]
     */
    public function level_edit($id)
    {
        $data = I('post.');

        if (!empty($data)) {
            $save = array(
                    'level_name' => $data['level_name'],
                    'money' => $data['money'],
                    'update_time' => time()
                );
            $result = M('member_level')->where(array('id' => $data['id']))->save($save);
        
            if ($result) {
                $this->success('The update is successful');die;
            } else {
                $this->error('Fail to Saved');die;
            }
        }

        $info = M('member_level')->where(array('id' => $id))->find();
        $this->assign('info', $info);
        $this->assign('op', 'Edit');
        $this->display('level_add');
    }

    /**
     * [level_del 删除会员等级]
     * @AuthorHTL
     * @DateTime  2018-02-08T14:52:56+0800
     * @param     [type]                   $id [会员等级id]
     * @return    [type]                       [description]
     */
    public function level_del($id)
    {
        $business_id = session('admin_id');

        $info = M('member_level')->where(array('id' => $id))->find();

        if ($info['admin_id'] != $business_id) {
            $this->error('Illegal operation');die;
        }

        $result = M('member_level')->where(array('id' => $id))->delete();

        if ($result) {
            $this->success('Successfully Deleted');
        } else {
            $this->error('Delete failed');
        }
    }

    /**
     * [reduction 满减活动设置-列表]
     * @AuthorHTL
     * @DateTime  2018-03-14T17:38:39+0800
     * @return    [type]                   [description]
     */
    public function reduction()
    {
        $list = M('reduction')->where(array('admin_id' => session('admin_id')))->select();
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * [reduction_delete 删除满减活动]
     * @AuthorHTL
     * @DateTime  2018-03-14T17:57:16+0800
     * @return    [type]                   [description]
     */
    public function reduction_delete($id)
    {
        $info = M('reduction')->where(array('id' => $id))->find();

        if ($info['admin_id'] != session('admin_id')) {
            $this->success('Illegal operation');die;
        }

        $result = M('reduction')->where(array('id' => $id))->delete();

        if ($result) {
            $this->success('Successfully Deleted');
        } else {
            $this->error('Delete failed');
        }
    }

    /**
     * [reduction_edit 编辑满减活动]
     * @AuthorHTL
     * @DateTime  2018-03-14T17:56:59+0800
     * @return    [type]                   [description]
     */
    public function reduction_edit()
    {
        $data = I('post.');

        if (empty($data['id'])) $this->ajaxReturn(['status' => -1, 'msg' => 'Id is empty']);

        if (empty($data['full_money'])) $this->ajaxReturn(['status' => -1, 'msg' => 'Total Purchase Empty']);

        if (empty($data['reduction_money'])) $this->ajaxReturn(['status' => -1, 'msg' => 'Minus amount is empty']);

        $save = array(
                'full_money' => $data['full_money'],
                'reduction_money' => $data['reduction_money']
            );

        $result = M('reduction')->where(array('id' => $data['id']))->save($save);

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => 'Successfully Edited']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => 'Fail to Saved']);
        }
    }

    /**
     * [reduction_add 添加满减活动]
     * @AuthorHTL
     * @DateTime  2018-03-14T18:00:40+0800
     * @return    [type]                   [description]
     */
    public function reduction_add()
    {
        $data = I('post.');

        if (empty($data['full_money'])) $this->ajaxReturn(['status' => -1, 'msg' => 'Full amount empty']);

        if (empty($data['reduction_money'])) $this->ajaxReturn(['status' => -1, 'msg' => 'Minus amount is empty']);

        $add = array(
                'admin_id' => session('admin_id'),
                'full_money' => $data['full_money'],
                'reduction_money' => $data['reduction_money']
            );

        $result = M('reduction')->add($add);

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => 'Successfully Saved']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => 'Add failure']);
        }
    }


     public function shengji()
    {
        $this->display();
    }
}