<?php
/**
 * 大屏控制器
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong<lilong@suxuantech.cn> $
 */
namespace app\crm\controller;
use think\Controller;
use app\index\controller\Base;
use think\Queue;
use think\Request;

class Bigscreen extends Base{

    public function test(){

    }

    /*
        当日/当月 推广费用（集团，事业部/店）
        当日/当月 录入客资数（集团，事业部/店）
        当日/当月 有效客资数（集团，事业部/店）
        当日/当月 进店数（集团，事业部/店）
        当日/当月 有效订单数（集团，事业部/店）
        当日/当月 有效订单套系总额（集团，事业部/店）
        当日/当月 实收金额（集团，事业部/店）
    */

    // public function _initialize(){}
    // 大屏页面  2018-03-11
    public function index(){
        //权限判断
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            $this->assign('hint','您无此权限，请联系管理员开通！');
            return $this->fetch();
        }
        $bg_controller = db_config('bg_controller');

        if (strtolower($bg_controller) !== 'bigscreen' && $bg_controller) {
            $this->redirect('/crm/'.$bg_controller);
        }else{
           /* $no_bids = config('no_bigScreen_bid');
            $no_bids = explode(',', $no_bids);
            
            $brandList = controller('crm/Bigscreen', 'lib')->getBrandInfo();
            foreach ($brandList as $key => $value) {
                if (in_array($value['id'], $no_bids)) {
                    continue;
                }else{
                    $baseBrand[$key]['brandclass_id'] = $value['id'];
                    $baseBrand[$key]['brandclass']    = $value['brandclass'];
                    if ($value['nickname']) {
                        $baseBrand[$key]['nickname']  = $value['nickname'];
                    }else{
                        $baseBrand[$key]['nickname']  = $value['brandclass'];
                    }
                }
            }
            
            $this->assign('baseBrand', $baseBrand);

            // 集团名称
            $gInfo = controller('crm/Bigscreen', 'lib')->getGName();
            $this->assign('title',$gInfo['group_company_name']);
            // 判断集团logo
            $logo = file_exists('bigscreennew/img/'.md5($gInfo['group_company_name']).'.png');
            $logo_btm = file_exists('bigscreennew/img/'.md5($gInfo['group_company_name']).'-btm.png');
            if ($logo && $logo_btm) {
                $md5 = md5($gInfo['group_company_name']);
                $this->assign('md5',$md5);
            }*/
            $this->assign('hint','未配置“数据大屏地址”，请点击去<a href="/crm/setting/erpset" style="color:blue;font-size:20px;">配置</a>');
            return $this->fetch();
        }
    }

    // 移动端大屏
    public function mobile(){
        $bg_controller = config('bg_controller');
        $get = input('get.');
        
        if ($get['sign']=='app') {
            $sid = $get['staff_id'];
            session('staff_id', $sid);
            $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
            if ($auth === false) {
                $this->redirect('/crm/Customer/index');
            }
        }

        if ($bg_controller) {
            $this->redirect('/crm/'.$bg_controller.'/mobile');
            exit;
        }else{
            $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
            if ($auth === false) {
                controller('crm/Index','controller')->index();
                exit;
            }
            $no_bids = config('no_bigScreen_bid');
            $no_bids = explode(',', $no_bids);
            
            $brandList = controller('crm/Bigscreen', 'lib')->getBrandInfo();
            foreach ($brandList as $key => $value) {
                if (in_array($value['id'], $no_bids)) {
                    continue;
                }else{
                    $baseBrand[$key]['brandclass_id'] = $value['id'];
                    $baseBrand[$key]['brandclass']    = $value['brandclass'];
                    if ($value['nickname']) {
                        $baseBrand[$key]['nickname']  = $value['nickname'];
                    }else{
                        $baseBrand[$key]['nickname']  = $value['brandclass'];
                    }
                }
            }
            $this->assign('baseBrand', $baseBrand);

            $gInfo = controller('crm/Bigscreen', 'lib')->getGName();
            $this->assign('title',$gInfo['group_company_name']);
        }
        
        return $this->fetch();
    }

    // 页面基础数据
    public function baseData(){
        // echo 'START==>'.microtime(true).'<br />';     
        // 权限
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

        //本月
        $mdate = getdateArea('this_month');
        $mData['start'] = date('Y-m-d 00:00:00',strtotime($mdate[0]));
        $mData['end']   = date('Y-m-d 23:59:59');

        //今天
        $tData['start'] = date('Y-m-d 00:00:00');
        $tData['end']   = date('Y-m-d 23:59:59');

        // 如果有事业部id，则查询事业部数据，
        $post = input('post.');
        $brandclass_id = (int)$post['brandclass_id'] ? (int)$post['brandclass_id'] : null;

        if ($brandclass_id) {
            //有事业部查当前事业部所有shop_code
            $tData['brandclass_id'] = $brandclass_id;
            $mData['brandclass_id'] = $brandclass_id;
            $shopCodes = getShopCode($brandclass_id);
            $tData['add_shop_code'] = $shopCodes;
            $mData['add_shop_code'] = $shopCodes;
        }else{
            //没有事业部查集团所有shop_code
            $shopCodes = getShopCode(0);
            $tData['add_shop_code'] = $shopCodes;
            $mData['add_shop_code'] = $shopCodes;
        }
        // 本月集团总客资 
        $all = cache('bigScreen_allCus');
        if (!$all) {
            $all = controller('crm/Bigscreen','lib')->getCustomerNum($mData);
            cache('bigScreen_allCus', $all);
        }

        //推广费用（渠道花费）
        $costMoneyT = controller('crm/Bigscreen', 'lib')->costMoney($tData);
        $costMoneyM = controller('crm/Bigscreen', 'lib')->costMoney($mData);
        $cost       = round($costMoneyT).' / '.round($costMoneyM);

        // //其它费用
        // $anotherT = controller('crm/Bigscreen', 'lib')->anotherCost($tData);
        // $anotherM = controller('crm/Bigscreen', 'lib')->anotherCost($mData);
        // $another  = round($anotherT).' / '.round($anotherM);
        // //花费合计
        // $total_cost = round($costMoneyT+$anotherT).' / '.round($costMoneyM+$anotherM);

        //总获取（毛客资）
        $allCusT = controller('crm/Bigscreen', 'lib')->getCustomerNum($tData);
        $allCusM = controller('crm/Bigscreen', 'lib')->getCustomerNum($mData);
        $allCus  = $allCusT.' / '.$allCusM;
        // 有效客资
        $validCustomerT = controller('crm/Bigscreen', 'lib')->getInvCustomerNum($tData);
        $validCustomerM = controller('crm/Bigscreen', 'lib')->getInvCustomerNum($mData);
        $validCustomer  = $validCustomerT.' / '.$validCustomerM;
        // 获取成本
        $validObtail = round($costMoneyT/$validCustomerT).' / '.round($costMoneyM/$validCustomerM);
        // var_dump($validObtail);
        // exit;
        // 网络营收
        $moneyT = controller('crm/Bigscreen', 'lib')->incomeMoney($tData);
        $moneyM = controller('crm/Bigscreen', 'lib')->incomeMoney($mData);
        $money = $moneyT.' / '.$moneyM;
        //下面的按网销查
        if ($brandclass_id) {
            $tData['brandclass_id'] = $brandclass_id;
            $mData['brandclass_id'] = $brandclass_id;
            $shopCodes = getShopCode($brandclass_id,'wx');
            $tData['shop_code'] = $shopCodes;
            $mData['shop_code'] = $shopCodes;
        }else{
            $shopCodes = getShopCode(0,'wx');
            $tData['shop_code'] = $shopCodes;
            $mData['shop_code'] = $shopCodes;
        }
        // 本月总新单 集团所有的订单数量 （婚纱类型，crm订单）
        if ($brandclass_id == 8) {
            $returnData['total_order'] = db('c_customerinfo')
                ->where('shop_code','in',$shopCodes)
                ->where('c_from',1)
                ->where('is_status',1)
                ->where('is_success',1)
                ->where('order_day', 'between time', [$mData['start'], $mData['end']])
                ->count('id');
        }else{
            $returnData['total_order'] = db('c_customerinfo')
                ->where('shop_code','in',$shopCodes)
                ->where('c_from',1)
                ->where('is_status',1)
                ->where('consultation_type_id',HS_TYPE)
                ->where('is_success',1)
                ->where('order_day', 'between time', [$mData['start'], $mData['end']])
                ->count('id');
        }

        // 网络进客
        $intoCustomerT = controller('crm/Bigscreen', 'lib')->getIntoCustomerNum($tData);
        $intoCustomerM = controller('crm/Bigscreen', 'lib')->getIntoCustomerNum($mData);
        $intoCustomer = $intoCustomerT.'/'.$intoCustomerM;
        // 网络新单
        $tData['type'] = 'shop';
        $orderCustomerT = controller('crm/Bigscreen', 'lib')->getOrderNumberNum($tData);
        $mData['type'] = 'shop';
        $orderCustomerM = controller('crm/Bigscreen', 'lib')->getOrderNumberNum($mData);
        // exit;
        $orderCustomer = $orderCustomerT.'/'.$orderCustomerM;
        // 毛客资转化率
        $allCusRate = number_format(($orderCustomerT/$allCusT)*100,2).'%'.' / '.number_format(($orderCustomerM/$allCusM)*100,2).'%';
        //订单数量 / 毛客资
        $dayChangeRate = ($orderCustomerT / $allCusT)*100;
        $dayChangeRate = number_format($dayChangeRate, 2).'%';
        // 月转化率
        $monthChangeRate = ($orderCustomerM / $allCusM)*100;
        $monthChangeRate = number_format($monthChangeRate, 2).'%';
        // 成交率
        $succRate = number_format($orderCustomerT/$validCustomerM,2).'%'.' / '.number_format($orderCustomerM/$validCustomerM,2).'%';

        $returnData['cost']            = $cost;
        // $returnData['another']         = $another;
        // $returnData['total_cost']      = $total_cost;
        $returnData['allCus']          = $allCus;
        $returnData['validCustomer']   = $validCustomer;
        $returnData['validObtail']     = $validObtail;
        $returnData['intoCustomer']    = $intoCustomer;
        $returnData['orderCustomer']   = $orderCustomer;
        $returnData['money']           = $money;
        $returnData['succRate']        = $succRate;
        $returnData['allCusRate']      = $allCusRate;
        $returnData['dayChangeRate']   = $dayChangeRate;
        $returnData['monthChangeRate'] = $monthChangeRate;
        return json($returnData);
    }

    // 四个排行榜
    public function rankData(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // 月 开始结束时间
        $date = getdateArea('this_month');
        $month_start= date('Y-m-d 00:00:00',strtotime($date[0]));
        $month_end  = date('Y-m-d 23:59:59',strtotime($date[1]));
        //所有事业部信息（缓存）
        // $brandInfo = cache('companyInfo');
        // if(empty($brandInfo)){
        //     $brandInfo = compact('crm/Customer','lib')->companyInfo();
        // }
        $add_shop_codes = getShopCode(0);
        $shop_codes     = getShopCode(0);
        // 取事业部列表
        $baseBrand = [];

        $no_bids = config('no_bigScreen_bid');
        $no_bids = explode(',', $no_bids);
        
        $brandList = controller('crm/Bigscreen', 'lib')->getBrandInfo();
        foreach ($brandList as $key => $value) {
            if (in_array($value['id'], $no_bids)) {
                continue;
            }else{
                $baseBrand[$key]['brandclass_id'] = $value['id'];
                $baseBrand[$key]['brandclass']    = $value['brandclass'];
                $baseBrand[$key]['nickname']      = $value['nickname'];
                $baseBrand[$key]['dayNum']        = 0;
                $baseBrand[$key]['monthNum']      = 0;
                $baseBrand[$key]['add_shop_code'] = $add_shop_codes;
                $baseBrand[$key]['shop_code']     = $shop_codes;
            }
        }
        // array_pop($baseBrand);
        unset($brandList);

        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        /* -----------------------------------------------------  毛客资排名开始  ----------------------------------------------------- */
        $dayNewCus = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where('add_shop_code', 'in', $add_shop_codes)
            ->where('dj_day', 'between time', [$today_start, $today_end])
            ->group('add_shop_code')
            ->field('brandclass_id, brandclass, "" AS nickname, COUNT(id) AS dayNum, 0 AS monthNum, add_shop_code')
            ->order('dayNum', 'desc')
            ->select();

        $monthNewCus = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where('add_shop_code', 'in', $add_shop_codes)
            ->where('dj_day', 'between time', [$month_start, $month_end])
            ->group('add_shop_code')
            ->field('brandclass_id, brandclass, "" AS nickname, COUNT(id) AS monthNum, 0 AS dayNum, add_shop_code')
            ->order('dayNum', 'desc')
            ->select();
        $merge = array_merge($dayNewCus, $monthNewCus, $baseBrand);

        $brandDayNew = [];
        foreach ($merge as $key => $value) {
            // 加权系数
            // $weight = controller('crm/Bigscreen', 'lib')->getShopWeight($value['add_shop_code']);
            // $shopDay = (int)round($value['dayNum'] * $weight);
            // $shopMon = (int)round($value['monthNum'] * $weight);
            if (!$value['brandclass_id']) {
                continue;
            }
            $brandDayNew[$value['brandclass_id']]['brandclass_id'] = $value['brandclass_id'];
            $brandDayNew[$value['brandclass_id']]['brandclass']    = $value['brandclass'];
            $brandDayNew[$value['brandclass_id']]['nickname']      = $value['nickname'];
            $brandDayNew[$value['brandclass_id']]['dayNum']       += $value['dayNum'];
            $brandDayNew[$value['brandclass_id']]['monthNum']     += $value['monthNum'];
        }
        
        unset($merge);
        unset($dayNewCus);
        unset($monthNewCus);
        $sort_order = 'SORT_DESC';
        $brandDayNew = my_sort($brandDayNew, 'dayNum', $sort_order);
        // var_dump($brandDayNew);
        // exit;
        /* -----------------------------------------------------  毛客资排名结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  有效客资排名开始  ----------------------------------------------------- */
        $dayValidCus = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where('is_valid', 1)
            ->where('add_shop_code', 'in', $add_shop_codes)
            ->where('yx_day', 'between time', [$today_start, $today_end])
            ->group('add_shop_code')
            ->field('brandclass_id, brandclass, "" AS nickname, COUNT(id) AS dayNum, 0 AS monthNum, add_shop_code')
            ->order('dayNum', 'desc')
            ->select();
        $monthValidCus = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where('is_valid', 1)
            ->where('add_shop_code', 'in', $add_shop_codes)
            ->where('yx_day', 'between time', [$month_start, $month_end])
            ->group('add_shop_code')
            ->field('brandclass_id, brandclass, "" AS nickname, COUNT(id) AS monthNum, 0 AS dayNum, add_shop_code')
            ->order('dayNum', 'desc')
            ->select();
        $merge = array_merge($dayValidCus, $monthValidCus, $baseBrand);

        $brandValidNew = [];
        foreach ($merge as $key => $value) {
            // 加权系数
            // $weight = controller('crm/Bigscreen', 'lib')->getShopWeight($value['add_shop_code']);
            // $shopDay = (int)round($value['dayNum'] * $weight);
            // $shopMon = (int)round($value['monthNum'] * $weight);
            if (!$value['brandclass_id']) {
                continue;
            }
            $brandValidNew[$value['brandclass_id']]['brandclass_id'] = $value['brandclass_id'];
            $brandValidNew[$value['brandclass_id']]['brandclass']    = $value['brandclass'];
            $brandValidNew[$value['brandclass_id']]['nickname']      = $value['nickname'];
            $brandValidNew[$value['brandclass_id']]['dayNum']       += $value['dayNum'];
            $brandValidNew[$value['brandclass_id']]['monthNum']     += $value['monthNum'];
        }
        
        unset($merge);
        unset($dayValidCus);
        unset($monthValidCus);
        $sort_order = 'SORT_DESC';
        $brandValidNew = my_sort($brandValidNew, 'dayNum', $sort_order);
        // var_dump($brandDayNew);
        // exit;
        /* -----------------------------------------------------  有效客资排名结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  邀约(进店)排名开始  ----------------------------------------------------- */
        $dayIntoCus = db('c_customerinfo')
            ->where($where)
            ->where('is_intostore', 2)
            ->where('shop_code', 'in', $shop_codes)
            ->where('syjd_day', 'between time', [$today_start, $today_end])
            ->group('shop_code')
            ->field('brandclass_id, brandclass, "" AS nickname, COUNT(id) AS dayNum, 0 AS monthNum, shop_code')
            ->order('dayNum', 'desc')
            ->select();
        // echo db()->getLastSql().'<br />';
        $monthIntoCus = db('c_customerinfo')
            ->where($where)
            ->where('is_intostore', 2)
            ->where('shop_code', 'in', $shop_codes)
            ->where('brandclass_id', '<>', 8)
            ->where('syjd_day', 'between time', [$month_start, $month_end])
            ->group('shop_code')
            ->field('brandclass_id, brandclass, "" AS nickname, COUNT(id) AS monthNum, 0 AS dayNum, shop_code')
            ->order('dayNum', 'desc')
            ->select();
        $merge = array_merge($dayIntoCus, $monthIntoCus, $baseBrand);
        // exit;
        $brandDayInto = [];
        foreach ($merge as $key => $value) {
            // 加权系数
            // $weight = controller('crm/Bigscreen', 'lib')->getShopWeight($value['shop_code']);
            // $shopDay = (int)round($value['dayNum'] * $weight);
            // $shopMon = (int)round($value['monthNum'] * $weight);
            if (!$value['brandclass_id']) {
                continue;
            }
            $brandDayInto[$value['brandclass_id']]['brandclass_id'] = $value['brandclass_id'];
            $brandDayInto[$value['brandclass_id']]['brandclass']    = $value['brandclass'];
            if ($value['nickname']) {
                $brandDayInto[$value['brandclass_id']]['nickname']  = $value['nickname'];
            }else{
                $brandDayInto[$value['brandclass_id']]['nickname']  = $value['brandclass'];
            }
            $brandDayInto[$value['brandclass_id']]['nickname']      = $value['nickname'];
            $brandDayInto[$value['brandclass_id']]['dayNum']       += $value['dayNum'];
            $brandDayInto[$value['brandclass_id']]['monthNum']     += $value['monthNum'];
        }
        unset($merge, $dayIntoCus, $monthOrdeCus);
        $sort_order = 'SORT_DESC';
        $brandDayInto = my_sort($brandDayInto, 'dayNum', $sort_order);
        // var_dump($brandDayInto);
        // exit;
        /* -----------------------------------------------------  邀约排名结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  新单排名开始  ----------------------------------------------------- */
        $dayOrdeCus = db('c_customer_order')->alias('o')
            ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
            ->where('o.order_valid', 2)
            ->where('o.is_delete', 2)
            ->where('o.valid_time', 'between time', [$today_start, $today_end])
            ->where('c.shop_code', 'in', $shop_codes)
            ->where('c.is_status', 1)
            ->where('c.c_from', 1)
            ->field('c.brandclass_id, c.brandclass, "" AS nickname, COUNT(o.id) AS dayNum, 0 AS monthNum, o.shop_code')
            ->order('dayNum', 'desc')
            ->select();
        $monthOrdeCus = db('c_customer_order')->alias('o')
            ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
            ->where('o.order_valid', 2)
            ->where('o.is_delete', 2)
            ->where('o.valid_time', 'between time', [$month_start, $month_end])
            ->where('c.shop_code', 'in', $shop_codes)
            ->where('c.is_status', 1)
            ->where('c.c_from', 1)
            ->field('c.brandclass_id, c.brandclass, "" AS nickname, COUNT(o.id) AS monthNum, 0 AS dayNum, o.shop_code')
            ->order('dayNum', 'desc')
            ->select();
        $merge = array_merge($dayOrdeCus, $monthOrdeCus, $baseBrand);
        $brandDayOrder = [];
        foreach ($merge as $key => $value) {
            // 加权系数
            // $weight = controller('crm/Bigscreen', 'lib')->getShopWeight($value['add_shop_code']);
            // $shopDay = (int)round($value['dayNum'] * $weight);
            // $shopMon = (int)round($value['monthNum'] * $weight);
            if (!$value['brandclass_id']) {
                continue;
            }
            $brandDayOrder[$value['brandclass_id']]['brandclass_id'] = $value['brandclass_id'];
            $brandDayOrder[$value['brandclass_id']]['brandclass']    = $value['brandclass'];
            if ($value['nickname']) {
                $brandDayOrder[$value['brandclass_id']]['nickname']  = $value['nickname'];
            }else{
                $brandDayOrder[$value['brandclass_id']]['nickname']  = $value['brandclass'];
            }
            $brandDayOrder[$value['brandclass_id']]['nickname']      = $value['nickname'];
            $brandDayOrder[$value['brandclass_id']]['dayNum']       += $value['dayNum'];
            $brandDayOrder[$value['brandclass_id']]['monthNum']     += $value['monthNum'];
        }
        unset($merge);
        unset($dayOrdeCus);
        unset($monthOrdeCus);
        // 给下面的转化率用
        $saveOrder = $brandDayOrder;
        $sort_order = 'SORT_DESC';
        $brandDayOrder = my_sort($brandDayOrder, 'dayNum', $sort_order);
        // var_dump($brandDayOrder);
        // exit;
        /* -------------------------------------------------------  新单排名结束 ------------------------------------------------------- */

        $returnData = [
            'brandDayNew'  => $brandDayNew,
            'brandValidNew'=> $brandValidNew,
            'brandDayInto' => $brandDayInto,
            'brandDayOrder'=> $brandDayOrder,

        ];
        unset($brandDayNew);
        unset($brandValidNew);
        unset($brandDayInto);
        unset($brandDayOrder);
        return json($returnData);
    }

    // 转化漏斗 （日） 图
    public function dayChangeRate(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }

        $post = input('post.');

        $data['start'] = date('Y-m-d 00:00:00', time());
        $data['end']   = date('Y-m-d 23:59:59', time());
        $data['brandclass_id'] = (int)$post['brandclass_id'] ? (int)$post['brandclass_id'] : 0;

        $returnData = $this->getChangeLdData($data);

        return json($returnData);
    }

    // 转化漏斗 （月） 图
    public function monthChangeRate(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }

        $post = input('post.');

        $date = getdateArea('this_month');
        $data['start'] = date('Y-m-d 00:00:00',strtotime($date[0]));
        $data['end'] = date('Y-m-d 23:59:59',strtotime($date[1]));
        $data['brandclass_id'] = (int)$post['brandclass_id'] ? (int)$post['brandclass_id'] : 0;

        $returnData = $this->getChangeLdData($data);

        return json($returnData);
    }

    // 转化漏斗数据 
    public function getChangeLdData($data){
        $brandclass_id = $data['brandclass_id'];
        if ($brandclass_id) {
            $data['brandclass_id'] = $brandclass_id;
            // $add_shop_code = $this->shop_codes;
            // $data['add_shop_code'] = $add_shop_code[$brandclass_id];
            $data['add_shop_code'] = getShopCode($brandclass_id);
        }else{
            // $data['add_shop_code'] = implode(',', $this->shop_codes);
            $data['add_shop_code'] = getShopCode(0);
        }
        
        // 毛客资
        $customerNum = controller('crm/Bigscreen', 'lib')->getCustomerNum($data);
        $returnData[0]['name'] = '毛客资量';
        $returnData[0]['data'] = $customerNum;
        // 有效客资
        $invCustomer = controller('crm/Bigscreen', 'lib')->getInvCustomerNum($data);
        // exit;
        $returnData[1]['name'] = '有效客资';
        $returnData[1]['data'] = $invCustomer;
        // // 获取手机
        // $telCustomer = controller('crm/Statistics', 'lib')->getTelCustomerNum($data);
        // $returnData[2]['name'] = '获取手机';
        // $returnData[2]['data'] = $telCustomer;

        if ($brandclass_id) {
            $data['brandclass_id'] = $brandclass_id;
            // $add_shop_code = $this->all_shop_codes;
            // $data['add_shop_code'] = $add_shop_code[$brandclass_id];
            $data['shop_code'] = getShopCode($brandclass_id);
        }else{
            // $data['add_shop_code'] = implode(',', $this->all_shop_codes);
            $data['shop_code'] = getShopCode(0);
        }
        // 进店/邀约 量
        $intoCustomer= controller('crm/Bigscreen', 'lib')->getIntoCustomerNum($data);

        $returnData[2]['name'] = '进店';
        $returnData[2]['data'] = $intoCustomer;
        // 新单 量
        $data['type'] = 'shop';
        $orderNumber = controller('crm/Bigscreen', 'lib')->getOrderNumberNum($data);
        $returnData[3]['name'] = '订单';
        $returnData[3]['data'] = $orderNumber;
        return $returnData;
    }

    // 本月毛客资量走势 图
    public function monthCustomerNumber(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $brandclass_id = (int)$post['brandclass_id'] ? (int)$post['brandclass_id'] : 0;
        if ($brandclass_id) {
            $data['brandclass_id'] = $brandclass_id;
            // $add_shop_code = $this->all_shop_codes;
            // $data['add_shop_code'] = $add_shop_code[$brandclass_id];
            $data['add_shop_code'] = getShopCode($brandclass_id);
        }else{
            // $data['add_shop_code'] = implode(',', $this->all_shop_codes);
            $data['add_shop_code'] = getShopCode(0);
        }
        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);

        $number = [];
        $today = date('Y-m-d');
        foreach ($timezone as $key => $value) {
            $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
            $data['end']   = date('Y-m-d 23:59:59', strtotime($value));
            $customerNum = controller('crm/Bigscreen', 'lib')->getCustomerNum($data);
            $number[$key] = $customerNum;
            if ($value == $today) {
                break;
            }
        }
        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'毛客资量',
                'data' =>$number,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('毛客资量');
        $returnData['data'] = $arr;
        return json($returnData);
    }

    // 本月网销邀约 （进店） 量走势 图
    public function monthIntoNumber(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $brandclass_id = (int)$post['brandclass_id'] ? (int)$post['brandclass_id'] : 0;
        if ($brandclass_id) {
            $data['brandclass_id'] = $brandclass_id;
            $data['add_shop_code'] = getShopCode($brandclass_id);
        }else{
            $data['add_shop_code'] = getShopCode(0);
        }
        // 起始时间
        $date = getdateArea('this_month');

        $data['start'] = date('Y-m-d 00:00:00', strtotime($date[0]));
        $data['end']   = date('Y-m-d 23:59:59', strtotime($date[1]));

        $timezone = getDateFromRange($date[0], $date[1]);
        $today = date('Y-m-d');
        $number = [];
        foreach ($timezone as $key => $value) {
            $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
            $data['end']   = date('Y-m-d 23:59:59', strtotime($value));
            $customerNum = controller('crm/Bigscreen', 'lib')->getIntoCustomerNum($data);
            $number[$key] = $customerNum;
            if ($value == $today) {
                break;
            }
        }
        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'邀约量',
                'data' =>$number,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('邀约量');
        $returnData['data'] = $arr;
        return json($returnData);
    }
    
    // 本月网络新单量走势 图
    public function monthNewOrderNumber(){
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $brandclass_id = (int)$post['brandclass_id'] ? (int)$post['brandclass_id'] : 0;
        if ($brandclass_id) {
            $data['brandclass_id'] = $brandclass_id;
            $data['add_shop_code'] = getShopCode($brandclass_id);
        }else{
            $data['add_shop_code'] = getShopCode(0);
        }
        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);
        $today = date('Y-m-d');
        $number = [];
        foreach ($timezone as $key => $value) {
            $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
            $data['end']   = date('Y-m-d 23:59:59', strtotime($value));
            $data['type']  = 'shop';
            $customerNum = controller('crm/Bigscreen', 'lib')->getOrderNumberNum($data);
            $number[$key] = $customerNum;
            if ($value == $today) {
                break;
            }
        }
        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'新单量',
                'data' =>$number,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('新单量');
        $returnData['data'] = $arr;
        return json($returnData);
    }

    // 本月转化率 （ 新单 / 有效获取 ） 走势 图
    public function monthOrderRateNumber(){
        // echo '开始 ==> '.microtime(true).'<br />';
        $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $brandclass_id = (int)$post['brandclass_id'] ? (int)$post['brandclass_id'] : 0;
        if ($brandclass_id) {
            // 新单条件
            $dataInto['brandclass_id'] = $brandclass_id;
            $dataInto['add_shop_code'] = getShopCode($brandclass_id);
            // 有效条件
            $dataInv['brandclass_id'] = $brandclass_id;
            $dataInv['add_shop_code'] = getShopCode($brandclass_id);
        }else{
            // 新单条件
            $dataInto['shop_code'] = getShopCode(0);
            // 有效条件
            $dataInv['add_shop_code'] = getShopCode(0);
        }
        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);

        $zone   = [];
        $number = [];
        $allInto= 0;
        $allInv = 0;
        $today = date('Y-m-d');
        // echo '开始循环 ==> '.microtime(true).'<br />';

        foreach ($timezone as $key => $value) {
            $start = date('Y-m-d 00:00:00', strtotime($value));
            $end   = date('Y-m-d 23:59:59', strtotime($value));
            $dataInto['start']= $start;
            $dataInto['end']  = $end;
            $dataInv['start'] = $start;
            $dataInv['end']   = $end;
            // 邀约
            // echo '循环'.$key.'邀约 ==> '.microtime(true).'<br />';
            $intoNum = controller('crm/Bigscreen', 'lib')->getOrderNumberNum($dataInto);
            // echo $intoNum.'<br />';
            $allInto += $intoNum;
            // 有效
            // echo '循环'.$key.'有效 ==> '.microtime(true).'<br />';
            $invNum = controller('crm/Bigscreen', 'lib')->getInvCustomerNum($dataInv);
            // echo $invNum.'<br />';
            $allInv += $invNum;
            $rate = $intoNum / $invNum;
            $number[$key] = number_format($rate*100, 2);
            $number[$key] = $number[$key]>100 ? 100 : $number[$key];
            if ($value == $today) {
                break;
            }
        }
        // exit;
        // echo '结束循环 ==> '.microtime(true).'<br />';

        $allRate = number_format(($allInto / $allInv)*100, 2);

        // echo '循环时间 ==> '.microtime(true).'<br />';
        foreach ($timezone as $key => $value) {
            $allNumber[$key] = $allRate;
            $zone[$key] = date('d', strtotime($value));
        }
        // echo '循环结束 ==> '.microtime(true).'<br />';
        $arr = [
            0=>[
                'name'=>'日转化率',
                'data' =>$number,
            ],
            1=>[
                'name'=>'月转化率',
                'data' =>$allNumber,
            ],
        ];
        $returnData['timezone'] = $zone;
        $returnData['name'] = array('转化率');
        $returnData['data'] = $arr;
        // echo '最后赋值 ==> '.microtime(true).'<br />';
        return json($returnData);
    }

}