<?php
/**
 *
 * @author  Mike <m@9026.com>
 * @version    1.0
 * @date 2015年10月12日
 *
 */

namespace App\Http\Controllers\Admin\Base;

use App\Http\Controllers\Admin\Controller;
use App\Models\AdminUserModel;
use App\Models\AlbumAgentModel;
use App\Models\AlbumStatisticalModel;
use App\Models\AlbumUserModel;
use App\Models\AlbumWatchRecord;
use App\Models\AppInfoModel;
use App\Models\CustomerDetailsModel;
use App\Models\UserInfoModel;
use Illuminate\Http\Request;
use App\Services\Base\Tree;
use App\Services\Base\BaseArea;
use App\Services\Admin\Menus;
use App\Services\Admin\Acl;
use Auth;

class IndexController extends Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        if ($this->_user['is_root']) {
            $obj = new Menus();
            $menus = $obj->search(array('level'=>2,'display'=>1),$orderby=array('sort'=>'desc'),$pagesize = 100000);
            $menus = $menus->toArray();
            $menus = list_to_tree($menus['data']);
        } else {
            $obj = new Acl();
            $data = $obj->getRoleMenu($this->_user['admin_role_id']);
            $menus = list_to_tree($data);
        }
        $user = $this->_user;
        return view('admin.base.index.index',compact('menus', 'user'));
    }
    function welcome()
    {

        $userAuth = Auth::guard('admin')->user();
        if ($userAuth->is_root == 1 && !empty(request('store_id'))) {
            session()->put('store_id', request('store_id'));
            $is_we7 = session()->get('is_we7');
            if($is_we7 == 'true'){
                return redirect('?route=Admin/Base/Index/index');
            }else if ($is_we7 == 'false') {
                return redirect('/admin');
            }

        }
        $time = mktime(24, 60, 60, date('m'), date('d'), date('Y'));
        $day = '[';
        $count = '[';
        for ($i = 15; $i >= 1; $i --) {
            $startTime = $time - $i * 86400;
            $day .= "\"" . date('m-d', $startTime) . "\",";
            $start_time = date('Y-m-d H:i:s', $startTime);
            $end_time = date('Y-m-d H:i:s', $startTime + 86400);
            $num = AlbumWatchRecord::where([['store_id',$this->getStoreId()],['created_at','>=',$start_time],['created_at','<=',$end_time],['action',4]])->groupBy('open_id')->count();
            $count .= $num . ",";
        }
        $agents = AlbumAgentModel::where('status', 1)->get()->toArray();
        $data = array();
        $geoCoordMap = (object)[];
        foreach ($agents as $key => $val) {
            $count_all = AlbumWatchRecord::where([
                ['agent_id', $val['id']],
                ['store_id', $this->getStoreId()]
            ])->groupBy('open_id')->count();
            $data[] = (object)[
                'name' => $val['realname'],
                'value' => ($count_all + 20),
                'num' => $count_all,
            ];
            $name = $val['realname'];
            if (empty($name) || empty($val['lon']) || $val['lat']) {
                continue;
            }
            $geoCoordMap->$name = [$val['lon'], $val['lat']];
        }
        //dd($geoCoordMap);
        $data = json_encode($data);
        $geoCoordMap = json_encode($geoCoordMap);
        $day = substr($day, 0, strlen($day) - 1) . ']';
        $count = substr($count, 0, strlen($count) - 1) . ']';
        return view('admin.base.index.welcome', [
            'day' => $day,
            'count' => $count,
            'data' => $data,
            'geoCoordMap' => $geoCoordMap
        ]);
    }

    public function getData(Request $request)
    {
        $data = $request->input();
        $time = mktime(24,60,60,date('m'),date('d'),date('Y'));
        $startTime = $time-$data['day']*86400;
        $start_time = date('Y-m-d H:i:s',$startTime);
        $newUser = AlbumUserModel::where([['created_at','>=',$start_time],['store_id',$this->getStoreId()]])->count();
        $shareTimes = AlbumStatisticalModel::where([['store_id',$this->getStoreId()],['time','>=',$startTime]])->sum('share_times');
        $favoriteTimes = AlbumStatisticalModel::where([['store_id',$this->getStoreId()],['time','>=',$startTime]])->sum('favorite_times');
        $watchCount = AlbumWatchRecord::where([['store_id',$this->getStoreId()],['created_at','>=',$start_time]])->groupBy('open_id')->count();
        $followCount = CustomerDetailsModel::where([['store_id',$this->getStoreId()],['created_at','>=',$start_time]])->groupBy('open_id')->count();
        return $this->api(['newUser'=>$newUser,'shareTimes'=>$shareTimes,'favoriteTimes'=>$favoriteTimes,'watchCount'=>$watchCount,'followCount'=>$followCount],0,'success');
    }

    function createAreaDate(){
        //Base-index-createareadate.do
        header("Content-type:text/html;charset=utf-8");
        $areaObj = new BaseArea();
        $data = $areaObj->getLevel();

        $treeObj = new Tree();
        $treeObj -> init($data);
        $info = $treeObj -> getTree();
        $output = array();

        foreach($info AS $key => $val){
            if($val['id'] == '100000') continue;
            $val['level'] = $val['level'] - 1;
            unset($val['grade'], $val['spacer']);
            $output[]= $val;
        }

        $str = json_encode($output);

        $area_path = public_path() . '/base/js/areadata.js';
        file_put_contents($area_path, $str);

        echo $str;exit;
    }


//    public function __construct()
//    {
//        parent::__construct();
//    }
//
//    function index(Request $request)
//    {
//
//        $menus = $this->getMenus($this->_user);
//
//        session('level', $this->_user->level);
//        $_user = $this->_user;
//        return view('admin.base.index.index', compact('menus', 'template_info', 'template_id', 'app_id','_user'));
//    }
//
//    function welcome()
//    {
//        return view('admin.base.index.welcome');
//    }
//
//    function createAreaDate()
//    {
//        //Base-index-createareadate.do
//        header("Content-type:text/html;charset=utf-8");
//        $areaObj = new BaseArea();
//        $data = $areaObj->getLevel();
//
//        $treeObj = new Tree();
//        $treeObj->init($data);
//        $info = $treeObj->getTree();
//        $output = array();
//
//        foreach ($info AS $key => $val) {
//            if ($val['id'] == '100000') continue;
//            $val['level'] = $val['level'] - 1;
//            unset($val['grade'], $val['spacer']);
//            $output[] = $val;
//        }
//
//        $str = json_encode($output);
//
//        $area_path = public_path() . '/base/js/areadata.js';
//        file_put_contents($area_path, $str);
//
//        echo $str;
//        exit;
//    }
//
//    public function getMenus($user)
//    {
//        if ($user->level >= 1) {
//            $menus = [
//                ['name' => '名片管理', 'path' => "/list?id=2", 'ico' => 'fa-bar-chart-o'],
//                ['name' => '公司管理', 'path' => "Sw/Company/Info/index?id=2", 'ico' => 'fa-bar-chart-o'],
//                ['name' => '画册管理', 'path' => "/Album/Manufacturer/list?isalbum=1", 'ico' => 'fa-bar-chart-o'],
//                ['name' => '家具管理', 'path' => "/Album/Manufacturer/list", 'ico' => 'fa-bar-chart-o'],
//            ];
//            return $menus;
//        }
//
//        if ($user->level === 0) {
//            $iscp = UserInfoModel::where('menus', 'like', '%' . '公司' . '%')->where('account', $user->account)->count();
//            $iscard = UserInfoModel::where('menus', 'like', '%' . '名片' . '%')->where('account', $user->account)->count();
//            $isalbum = UserInfoModel::where('menus', 'like', '%' . 'album' . '%')->where('account', $user->account)->count();
//            $isfurniture = UserInfoModel::where('menus', 'like', '%' . 'furniture' . '%')->where('account', $user->account)->count();
//
//
//            $_app_info = AppInfoModel::where('account','like','%' . $user->account . '%')->first();
//
//            $uniacid = isset($_app_info->uniacid)?$_app_info->uniacid:'';
//
//            if ($iscp) {
//                // 体验模板
//                $menus = [
//                    ['name' => '公司管理', 'path' => "/Sw/Company/Info/update?appid=$uniacid", 'ico' => 'fa-bar-chart-o'],
//                ];
//                return $menus;
//            }
//            if ($iscard) {
//                // 名片模板
//                $menus = [
//                    ['name' => '名片管理', 'path' => "/Card/User/Info/update?appid=$uniacid", 'ico' => 'fa-bar-chart-o'],
//                ];
//                return $menus;
//            }
//
//            if ($isalbum) {
//                // 画册模板
//                return $this->albumMenus($user,$user->user_template_id);
//            }
//
//            if ($isfurniture) {
//                // 家具模板
//                return $this->furntureMenus($user,$user->user_template_id);
//            }
//        }
//
//    }
//
//    public function albumMenus($user,$storeid){        //画册
//        session()->put('store_id', $storeid);
//        session()->put('app', 'album');
//        $baseMenus = $this->baseMenus();
//
//        $_menus = [
//            $baseMenus['base_setting'],
//            $baseMenus['album_goods'],
//            $baseMenus['album_user'],
//        ];
//        return $_menus;
//    }
//
//    public function furntureMenus($user,$storeid){
//        session()->put('store_id', $storeid);
//        session()->put('app', 'furniture');
//        $baseMenus = $this->baseMenus();
//        if($user->role == 1)       //客服
//        {
//            $_menus = [
//                $baseMenus['fur_user'],
//                $baseMenus['fur_service_order'],
//                $baseMenus['fur_service_review'],
//                $baseMenus['fur_service_goodsattr'],
//            ];
//        }elseif(!$user->role){    //超级管理员
//            $_menus = [
//                $baseMenus['base_setting'],
//                $baseMenus['fur_user'],
//                $baseMenus['fur_navbar'],
//                $baseMenus['fur_banner'],
//                $baseMenus['fur_goods'],
//                $baseMenus['fur_news'],
//                $baseMenus['fur_service_order'],
//                $baseMenus['fur_service_review'],
//                $baseMenus['fur_service_goodsattr']
//            ];
//        }else{                    //经理
//            $_menus = [
//                $baseMenus['fur_service_order'],
//                $baseMenus['fur_service_review'],
//            ];
//        }
//
//        return $_menus;
//    }
//
//
//
//    public function baseMenus(){
//        $menus = [
//            ['name' => 'CRUD', 'path' => "/Base/Crud/create", 'ico' => 'fa fa-bar-chart-o'],
//            ['name' => '字典', 'path' => "/Base/Dictionary/Option/index", 'ico' => 'fa fa-bar-chart-o'],
//
//            'base_setting'=>
//                ['name' => '系统设置', 'path' => "/Album/Manufacturer/index", 'ico' => 'glyphicon glyphicon-cog'],
//            'fur_navbar'=>
//                ['name' => '导航栏设置', 'path' => "/Album/Nav/index", 'ico' => 'glyphicon glyphicon-th-list'],
//
//            'fur_banner'=>
//                ['name' => '轮播图管理', 'path' => "Album/Banner/index", 'ico' => 'glyphicon glyphicon-picture'],
//            'fur_news'=>
//                ['name' => '新闻管理', 'path' => "#", 'ico' => 'fa fa-bar-chart-o', '_child' =>
//                    [
//                        ['name' => '新闻列表', 'path' => '/Album/News/index', 'ico' => ''],
//                        ['name' => '评论列表', 'path' => '/Album/Comments/index', 'ico' => ''],
//                    ]
//                ],
//            'fur_goods'=>
//                ['name' => '产品管理', 'path' => "#", 'ico' => 'fa fa-bar-chart-o', '_child' =>
//                    [
//                        ['name' => '产品列表', 'path' => '/furnitureWe7/Goods/index', 'ico' => ''],
//                    ]
//                ],
//            'fur_user'=>
//                ['name' => '用户管理', 'path' => "#", 'ico' => 'glyphicon glyphicon-user', '_child' =>
//                    [
//                        ['name' => '用户列表', 'path' => '/Album/User/index', 'ico' => ''],
//                    ]
//                ],
//            'fur_service_order'=>
//                ['name' => '订单管理', 'path' => "#", 'ico' => 'glyphicon glyphicon-briefcase', '_child' =>
//                    [
//                        ['name' => '待审核', 'path' => '/Album/Order/index?status=0', 'ico' => ''],
//                        ['name' => '待生产', 'path' => '/Album/Order/index?status=1', 'ico' => ''],
//                        ['name' => '生产中', 'path' => '/Album/Order/index?status=2', 'ico' => ''],
//                        ['name' => '待发货', 'path' => '/Album/Order/index?status=3', 'ico' => ''],
//                        ['name' => '待收货', 'path' => '/Album/Order/index?status=4', 'ico' => ''],
//                        ['name' => '已签收', 'path' => '/Album/Order/index?status=5', 'ico' => ''],
//                        ['name' => '逾期', 'path' => '/Album/Order/index?expected=1', 'ico' => ''],
//                    ]
//                ],
//            'fur_service_review'=>
//                ['name' => '评论管理', 'path' => "#", 'ico' => 'glyphicon glyphicon-briefcase', '_child' => [
//                    ['name' => '评论列表', 'path' => '/Album/Review/index', 'ico' => '']
//                ]
//            ],
//            'fur_service_goodsattr'=>['name' => '产品属性', 'path' => "#", 'ico' => 'glyphicon glyphicon-briefcase', '_child' => [
//                ['name' => '属性列表', 'path' => '/Album/Product/Attr/index', 'ico' => '']
//            ]
//            ],
//

//            'album_goods'=>
//                ['name' => '产品管理', 'path' => "#", 'ico' => 'glyphicon glyphicon-briefcase', '_child' =>
//                    [
//                            ['name' => '分类管理', 'path' => '/Album/Cat/index', 'ico' => ''],
//                            ['name' => '样式管理', 'path' => '/Album/Product/Style/index', 'ico' => ''],
//                            ['name' => '产品管理', 'path' => 'Album/Product/index', 'ico' => ''],
//                    ]
//            ],
//            'album_user'=>
//                ['name' => '用户管理', 'path' => "#", 'ico' => 'glyphicon glyphicon-user', '_child' =>
//                    [
//                        ['name' => '用户列表', 'path' => '/Album/Xyx/User/index', 'ico' => ''],
//                        ['name' => '经销商列表', 'path' => '/Album/Agent/index', 'ico' => ''],
//                    ]
//                ],
//        ];
//
//        return $menus;
//    }

}
