<?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 Controller{

    public function test(){

    }

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

    // public function _initialize(){}

    // 大屏页面  2018-03-11
    public function index(){
        $bg_controller = config('bg_controller');
        // var_dump($bg_controller);exit;
        if ($bg_controller) {
            $this->redirect('/crm/'.$bg_controller);
        }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']);
            // 判断集团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);
            }
            return $this->fetch();
        }
    }

    // 移动端报表列表
    public function reportList(){
        $info = controller('crm/Setting','lib')->statistics_list_data();
        $info = $info->getData()['data'];

        $data = [];
        foreach($info as $key=>$value){
            if($value['report_name'] == '渠道名称数据统计' || $value['report_name'] == '追踪人数据统计' || $value['report_name'] == '登记人数据统计'){
                $data[] = $value;
            }
        }

        $this->assign('info',$data);
        return $this->fetch();
    }

    // 移动端大屏
    public function mobile(){
        $bg_controller = config('bg_controller');
        $get = input('get.');
        if(!input('daping')){
            if(customize('xianfeisi')){
                $this->redirect('/crm/bigscreen/reportList');
            }
        }
        
        if ($get['sign']=='app') {
            $sid = $get['staff_id'];
            session('staff_id', $sid);
            $auth = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
            if ($auth === false) {
                echo '无查看此页面权限';die;
                // $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);
    }

    // ---------------------------------------- 事业部大屏 start ------------------------------------------- //
    // 事业部大屏首页 PC端
    public function brand(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            // controller('crm/Index', 'controller')->index();
            // exit;
        }
        $this->assign('brandclass', session('brandclass'));

        $temp = db('s_bg_brandshow')->where('brandclass_id',session('brandclass_id'))->select();

        if ($temp) {
            $bg_show = [];
            foreach ($temp as $key => $value) {
                array_push($bg_show, $value['bg_show']);
            }
        }else{
            $bg_show = [
                '0'  => "wxOrderRate",
                '1'  => "qdOrderRate",
                '2'  => "qdValidOrder",
                '3'  => "qdInto",
                '4'  => "wxValidOrder",
                '5'  => "wxRefundOrder",
                '6'  => "wxNewOrder",
                '7'  => "wxIntoNum",
                '8'  => "cusTNewOrder",
                '9'  => "valTNewOrderRate",
                '10' => "cusTOrder",
                '11' => "valTOrderRate",
                '12' => "intoRate",
                '13' => "orderRate",
                '14' => "validRate",
                '15' => "roi",
                '16' => "orderCost",
                '17' => "intoCost",
                '18' => "validCost",
                '19' => "orderNewNum",
                '20' => "money",
                '21' => "avePrice",
                '22' => "cusCost",
                '23' => "orderNum",
                '24' => "intoNum",
                '25' => "telNum",
                '26' => "validNum",
                '27' => "customerNum",
                '28' => "cost",
            ];
        }

        $this->assign('bg_show', $bg_show);
        // var_dump($bg_show);exit;

        $this->assign('title','中国时尚经典集团 【事业部电商战报大屏】');

        return $this->fetch();
    }

    // 事业部大屏 移动端
    public function brandmobile(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            // controller('crm/Index', 'controller')->index();
            // exit;
        }
        $this->assign('brandclass', session('brandclass'));

        $temp = db('s_bg_brandshow')->where('brandclass_id',session('brandclass_id'))->select();
        if ($temp) {
            $bg_show = [];
            foreach ($temp as $key => $value) {
                array_push($bg_show, $value['bg_show']);
            }
        }else{
            $bg_show = [
                '0'  => "wxOrderRate",
                '1'  => "qdOrderRate",
                '2'  => "qdValidOrder",
                '3'  => "qdInto",
                '4'  => "wxValidOrder",
                '5'  => "wxRefundOrder",
                '6'  => "wxNewOrder",
                '7'  => "wxIntoNum",
                '8'  => "cusTNewOrder",
                '9'  => "valTNewOrderRate",
                '10' => "cusTOrder",
                '11' => "valTOrderRate",
                '12' => "intoRate",
                '13' => "orderRate",
                '14' => "validRate",
                '15' => "roi",
                '16' => "orderCost",
                '17' => "intoCost",
                '18' => "validCost",
                '19' => "orderNewNum",
                '20' => "money",
                '21' => "avePrice",
                '22' => "cusCost",
                '23' => "orderNum",
                '24' => "intoNum",
                '25' => "telNum",
                '26' => "validNum",
                '27' => "customerNum",
                '28' => "cost",
            ];
        }

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

        $this->assign('title','中国时尚经典集团 【事业部电商战报大屏】');
        return $this->fetch();
    }

    // 事业部大屏 实时数据(电商)  参数 今天，昨天
    public function brandStatisticsDataDS(){
        // echo '-- 1 --'.microtime(true).'<br />';
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            // controller('crm/Index', 'controller')->index();
            // exit;
        }
        $param = input('post.');
        // 事业部id
        $bid = session('brandclass_id');
        if ($param['day'] == 'yestoday') {
            // 昨天的开始结束时间
            $paramT['start'] = date('Y-m-d 00:00:00', strtotime('-1 days'));
            $paramT['end']   = date('Y-m-d 23:59:59', strtotime('-1 days'));
            $paramT['brandclass_id'] = $bid;
            // 本月的开始结束时间
            $paramM['start'] = date('Y-m-01 00:00:00');
            $paramM['end']   = date('Y-m-d 23:59:59', strtotime('-1 days'));
            $paramM['brandclass_id'] = $bid;
        } else {
            // 当天的开始结束时间
            $paramT['start'] = date('Y-m-d 00:00:00');
            $paramT['end']   = date('Y-m-d 23:59:59');
            $paramT['brandclass_id'] = $bid;
            // 本月的开始结束时间
            $paramM['start'] = date('Y-m-01 00:00:00');
            $paramM['end']   = date('Y-m-d 23:59:59');
            $paramM['brandclass_id'] = $bid;
        }
        // echo '-- 2 --'.microtime(true).'<br />';
        // 调mc接口，查当前事业部下的  电商 店
        $data['brandclass_id'] = $bid;
        $data['is_marketing']  = 1;
        $dsShops = controller('crm/Bigscreen', 'lib')->getShopByType($data);
        $ds_shop_codes = '';
        // 客资查询基础条件
        $where['c_from'] = 1;
        $where['is_status'] = 1;
        $where['customer_type'] = 1;
        foreach ($dsShops as $key => $value) {
            $ds_shop_codes .= "'".$value['shop_code']."',";
        }
        $ds_shop_codes = trim($ds_shop_codes, ',');
        $paramT['add_shop_code'] = $ds_shop_codes;
        $paramM['add_shop_code'] = $ds_shop_codes;
        // echo '-- 3 --'.microtime(true).'<br />';
        // ---------------------------------- 日 ------------------------------------ //
        $sql = 'SELECT ';
        // 毛客资  总获取
        $sql .= 'SUM( dj_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'") AS tmkz,';
        // 有效客资  有效获取
        $sql .= 'SUM( yx_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_valid = 1 AND consultation_type_id='.HS_TYPE.') AS tyx,';
        // 总手机
        $sql .= 'SUM( yx_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_valid = 1 AND consultation_type_id='.HS_TYPE.' AND (customer_tel IS NOT NULL AND customer_tel <> "" AND customer_tel <> 0) ) AS tsj,';
        // 总进店
        $sql .= 'SUM( syjd_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_intostore IN (2,3,5) AND consultation_type_id='.HS_TYPE.'  ) AS tjd,';
        // 总订单  有效订单
        $sql .= 'SUM( order_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_success = 1 AND consultation_type_id = '.HS_TYPE.') AS tyxd,';
        // 总订单  新单
        $sql .= 'SUM( order_start_time between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND consultation_type_id = '.HS_TYPE.') AS txd,';
        // ---------------------------------- 月 ------------------------------------ //
        // 毛客资
        $sql .= 'SUM( dj_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'") AS mmkz,';
        // 有效客资
        $sql .= 'SUM( yx_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_valid = 1 AND consultation_type_id='.HS_TYPE.') AS myx,';
        // 总手机
        $sql .= 'SUM( yx_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_valid = 1 AND consultation_type_id='.HS_TYPE.' AND (customer_tel IS NOT NULL AND customer_tel <> "" AND customer_tel <> 0) ) AS msj,';
        // 总进店
        $sql .= 'SUM( syjd_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_intostore IN (2,3,5) AND consultation_type_id='.HS_TYPE.'  ) AS mjd,';
        // 总订单
        $sql .= 'SUM( order_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_success = 1 AND consultation_type_id = '.HS_TYPE.') AS myxd,';
        // 总订单  新单
        $sql .= 'SUM( order_start_time between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND consultation_type_id = '.HS_TYPE.') AS mxd,';

        $sql .= ' shop_code,shop_name FROM  c_customerinfo WHERE c_from=1 AND is_status=1 AND customer_type=1 AND add_shop_code in ('.$ds_shop_codes.')';
        $dsNums = db()->query($sql);

        $returnData = []; 
        // 总花费（渠道花费） 总花费：    16857/83709
        $costMoneyT = controller('crm/Bigscreen', 'lib')->costMoney($paramT);
        $costMoneyM = controller('crm/Bigscreen', 'lib')->costMoney($paramM);
        // 成交金额：   77272/155938  ( 不区分消费类型 实际收款(一销) )
        $orderMoneyT = controller('crm/Bigscreen', 'lib')->getOrderMoney($paramT);
        $orderMoneyM = controller('crm/Bigscreen', 'lib')->getOrderMoney($paramM);
        // 实收
        $incomeMoneyT = controller('crm/Bigscreen', 'lib')->incomeMoney($paramT);
        $incomeMoneyM = controller('crm/Bigscreen', 'lib')->incomeMoney($paramM);
        // var_dump($incomeMoneyT);
        // exit;
        foreach ($dsNums as $key => $value) {
            $returnData['ds']['cost']            = round($costMoneyT).' / '.round($costMoneyM);
            // 总获取
            $returnData['ds']['customerNum']     = round($value['tmkz']).' / '.round($value['tmkz']);
            // 有效获取
            $returnData['ds']['validNum']        = round($value['tyx']).' / '.round($value['myx']);
            // 总手机
            $returnData['ds']['telNum']          = round($value['tsj']).' / '.round($value['msj']);
            // 总进店
            $returnData['ds']['intoNum']         = round($value['tjd']).' / '.round($value['mjd']);
            // 有效订单
            $returnData['ds']['orderNum']        = round($value['tyxd']).' / '.round($value['myxd']);
            // 新单
            $returnData['ds']['orderNewNum']     = round($value['txd']).' / '.round($value['mxd']);
            // 营收
            $returnData['ds']['money']           = round($orderMoneyT).' / '.round($orderMoneyM);
            // 均价  套系除以有效订单量
            $returnData['ds']['avePrice']        = round($orderMoneyT/$value['tyxd']).' / '.round($orderMoneyM/$value['myxd']);
            // 毛客资成本   花费除以毛客资
            $returnData['ds']['cusCost']         = round(($costMoneyT/$value['tmkz'])*100,2).'% / '.round(($costMoneyM/$value['tmkz'])*100,2).'%';
            // 有效获取成本 花费除以有效客资
            $returnData['ds']['validCost']       = round(($costMoneyT/$value['tyx'])*100,2).'% / '.round(($costMoneyM/$value['tyx'])*100,2).'%';
            // 进店成本     花费除以进店客资
            $returnData['ds']['intoCost']        = round(($costMoneyT/$value['tjd'])*100,2).'% / '.round(($costMoneyM/$value['mjd'])*100,2).'%';
            // 成交成本     花费除以有效订单
            $returnData['ds']['orderCost']       = round(($costMoneyT/$value['tyxd'])*100,2).'% / '.round(($costMoneyM/$value['myxd'])*100,2).'%';
            // roi          花费/实收  最后显示结果为 1/xxx    例子:1/5
            $returnData['ds']['roi']             = '1:'.round($costMoneyT/$incomeMoneyT, 2).' / '.'1:'.round($costMoneyM/$incomeMoneyM, 2);
            // 有效率   有效除以毛客资
            $returnData['ds']['validRate']       = round(($value['tyx']/$value['tmkz'])*100,2).'% / '.round(($value['myx']/$value['mmkz'])*100,2).'%';
            // 进店率   进店除以有效
            $returnData['ds']['intoRate']        = round(($value['tjd']/$value['tyx'])*100,2).'% / '.round(($value['mjd']/$value['myx'])*100,2).'%';
            // 成交率   有效订单除以进店
            $returnData['ds']['orderRate']       = round(($value['tyxd']/$value['tyx'])*100,2).'% / '.round(($value['myxd']/$value['myx'])*100,2).'%';
            // 获取到成交转化率     有效订单除以有效客资
            $returnData['ds']['valTOrderRate']   = round(($value['tyxd']/$value['tyx'])*100,2).'% / '.round(($value['myxd']/$value['myx'])*100,2).'%';
            // 毛客资到成交转化率   有效订单除以毛客资
            $returnData['ds']['cusTOrder']       = round(($value['tyxd']/$value['tmkz'])*100,2).'% / '.round(($value['myxd']/$value['mmkz'])*100,2).'%';
            // 获取到订单转化率      订单除以有效客资
            $returnData['ds']['valTNewOrderRate']= round(($value['txd']/$value['tyx'])*100,2).'% / '.round(($value['mxd']/$value['myx'])*100,2).'%';
            // 毛客资到订单转化率    订单除以毛客资
            $returnData['ds']['cusTNewOrder']    = round(($value['txd']/$value['tmkz'])*100,2).'% / '.round(($value['mxd']/$value['mmkz'])*100,2).'%';
        }

        return json($returnData);

        

        // $nums = db('c_customerinfo')
        //     ->where($where)
        //     ->where('add_shop_code', 'in', $ds_shop_codes)
        //     ->field($sql.'add_shop_code,add_shop_name')
        //     ->group('add_shop_code')
        //     ->select();
        // echo '-- 4 --'.microtime(true).'<br />';
        // var_dump($nums);
        // ---------------------------------- 尾 ------------------------------------ //
        // foreach ($nums as $key => $value) {
        //     $allData[$key]['shop_code'] = $value['add_shop_code'];
        //     $allData[$key]['shop_name'] = $value['add_shop_name'];
        //     $paramT['add_shop_code'] = $value['add_shop_code'];
        //     $paramM['add_shop_code'] = $value['add_shop_code'];
        //     //推广费用（渠道花费） 总花费：    16857/83709
        //     $costMoneyT = controller('crm/Bigscreen', 'lib')->costMoney($paramT);
        //     $costMoneyM = controller('crm/Bigscreen', 'lib')->costMoney($paramM);
        //     $allData[$key]['cost'] = round($costMoneyT).' / '.round($costMoneyM);
            
        //     // 总获取：    110/618
        //     $allData[$key]['customerNum'] = round($value['tmkz']).' / '.round($value['mmkz']);
        //     // 总有效获取：  59/331
        //     $allData[$key]['validNum'] = round($value['tyx']).' / '.round($value['myx']);
        //     // 总获取手机：  48/277
        //     $allData[$key]['telNum'] = round($value['tsj']).' / '.round($value['msj']);
        //     // 总进店：    47/136
        //     $allData[$key]['intoNum'] = round($value['tjd']).' / '.round($value['mjd']);
        //     // 总订单：    16/30
        //     $allData[$key]['orderNum'] = round($value['txd']).' / '.round($value['mxd']);
        //     // 成交金额：   77272/155938  ( 不区分消费类型 实际收款(一销) )
        //     $orderMoneyT = controller('crm/Bigscreen', 'lib')->getOrderMoney($paramT);
        //     $orderMoneyM = controller('crm/Bigscreen', 'lib')->getOrderMoney($paramM);
        //     $allData[$key]['orderMoney'] = round($orderMoneyT).' / '.round($orderMoneyM);
        //     // 成交平均：   5759/5631  ( 有效套系婚纱的平均值 )
        //     $costOrderTotalT = controller('crm/Bigscreen', 'lib')->dealMoney($paramT);
        //     $costOrderTotalM = controller('crm/Bigscreen', 'lib')->dealMoney($paramM);
        //     $allData[$key]['costAvg'] = round($costOrderTotalT/$value['txd']).' / '.round($costOrderTotalM/$value['mxd']);
        //     // 获取成本：   286/253    (16857/59)
        //     $allData[$key]['cusCost'] = round($costMoneyT/$value['tyx']).' / '.round($costMoneyM/$value['myx']);
        //     // 成交成本：   1054/2790  (16857/16)
        //     $allData[$key]['orderCost'] = round($costMoneyT/$value['txd']).' / '.round($costMoneyM/$value['mxd']);
        //     // 获取到成交率： 27.1%/9.1%  (16/59)
        //     $allData[$key]['validRate'] = round( ($value['txd']/$value['tyx'])*100, 2).'% / '.round( ($value['mxd']/$value['myx'])*100, 2).'%';
        //     // 毛客资到成交转换率：  14.55%/4.85%  (16/110)
        //     $allData[$key]['cusRate'] = round( ($value['txd']/$value['tmkz'])*100, 2).'% / '.round( ($value['mxd']/$value['mmkz'])*100, 2).'%';
        // }
        // echo '-- 5 --'.microtime(true).'<br />';
        // exit;
        // var_dump($allData);exit;

        // return json($allData);
    }

    // 事业部大屏 实时数据(网销 渠道)  参数 今天，昨天
    public function brandStatisticsDataWX(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            //controller('crm/Index', 'controller')->index();
            //exit;
        }
        $param = input('post.');
        $bid = session('brandclass_id');
        if ($param['day'] == 'yestoday') {
            // 昨天的开始结束时间
            $paramT['start'] = date('Y-m-d 00:00:00', strtotime('-1 days'));
            $paramT['end']   = date('Y-m-d 23:59:59', strtotime('-1 days'));
            $paramT['brandclass_id'] = $bid;
            // 本月的开始结束时间
            $paramM['start'] = date('Y-m-01 00:00:00');
            $paramM['end']   = date('Y-m-d 23:59:59', strtotime('-1 days'));
            $paramM['brandclass_id'] = $bid;
        } else {
            // 当天的开始结束时间
            $paramT['start'] = date('Y-m-d 00:00:00');
            $paramT['end']   = date('Y-m-d 23:59:59');
            $paramT['brandclass_id'] = $bid;
            // 本月的开始结束时间
            $paramM['start'] = date('Y-m-01 00:00:00');
            $paramM['end']   = date('Y-m-d 23:59:59');
            $paramM['brandclass_id'] = $bid;
        }
        // 基础条件
        $where['c_from'] = 1;
        $where['is_status'] = 1;
        $where['customer_type'] = 1;
        $returnData = [];
        // ----------------------------------------------- 网销 ----------------------------------------------- //
        // 网络进店，网络订单(新单)，网络订单(有效)，网络订单(退单，即作废单)，网络成交率（网销的有效订单除以进店）
        // 网销 shop_code 
        $data['brandclass_id'] = $bid;
        $data['is_marketing']  = 3;
        $wxShops = controller('crm/Bigscreen', 'lib')->getShopByType($data);
        $wx_shop_codes = '';
        foreach ($wxShops as $key => $value) {
            $w_shop_codes .= $value['shop_code'].",";
            $wx_shop_codes .= "'".$value['shop_code']."',";
        }
        $wx_shop_codes = trim($wx_shop_codes, ',');
        $w_shop_codes = trim($w_shop_codes, ',');
        $wx_sql = 'SELECT ';
        // 网络进店:13/22
        $wx_sql .= ' SUM( syjd_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_intostore IN (2,3,5) AND consultation_type_id='.HS_TYPE.'  ) AS tjd,';
        $wx_sql .= ' SUM( syjd_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_intostore IN (2,3,5) AND consultation_type_id='.HS_TYPE.'  ) AS mjd,';
        // 线上支付：0/1
        $wx_sql .= ' SUM( order_start_time between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND consultation_type_id = '.HS_TYPE.') AS toxd,';
        $wx_sql .= ' SUM( order_start_time between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND consultation_type_id = '.HS_TYPE.') AS moxd,';
        // 网络新单:7/13
        $wx_sql .= ' SUM( order_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_success = 1 AND consultation_type_id = '.HS_TYPE.') AS txd,';
        $wx_sql .= ' SUM( order_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_success = 1 AND consultation_type_id = '.HS_TYPE.') AS mxd,';
        $wx_sql .= ' shop_code,shop_name FROM  c_customerinfo WHERE c_from=1 and is_status=1 and shop_code in ('.$wx_shop_codes.')';
        $wxNums = db()->query($wx_sql);
        
        $refund_sql = '';
        $refund_sql .= ' SUM(unvalid_time between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND refund=2) AS tref,';
        $refund_sql .= ' SUM(unvalid_time between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND refund=2) AS mref';
        $refund = db('c_customer_order')
            ->where('shop_code', 'in', $w_shop_codes)
            ->field($refund_sql)
            ->select();
        
        foreach ($wxNums as $key => $value) {
            $returnData['wx']['wxIntoNum']    = $value['tjd'].' / '.$value['mjd'];
            $returnData['wx']['wxNewOrder']   = $value['toxd'].' / '.$value['moxd'];
            $returnData['wx']['wxValidOrder'] = $value['txd'].' / '.$value['txd'];
            $returnData['wx']['wxRefundOrder']= $refund['tref'].' / '.$refund['mref'];
            $returnData['wx']['wxOrderRate']  = round( ($value['txd']/$value['tjd'])*100, 2).'% / '.round( ($value['mxd']/$value['mjd'])*100, 2).'%';
        }
        // ----------------------------------------------------- 渠道 ----------------------------------------------------- //
        // 渠道进店，渠道订单(有效)，渠道成交率（有效订单除以进店）
        // 渠道 shop_code 
        $data['brandclass_id'] = $bid;
        $data['is_marketing']  = 4;
        $qdShops = controller('crm/Bigscreen', 'lib')->getShopByType($data);
        $qd_shop_codes = '';
        foreach ($qdShops as $key => $value) {
            $qd_shop_codes .= "'".$value['shop_code']."',";
        }
        $qd_shop_codes = trim($qd_shop_codes, ',');
        $qd_sql = 'SELECT ';
        // 渠道进店：   1/6
        $qd_sql .= ' SUM( syjd_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_intostore IN (2,3,5) AND consultation_type_id='.HS_TYPE.'  ) AS tjd,';
        $qd_sql .= ' SUM( syjd_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_intostore IN (2,3,5) AND consultation_type_id='.HS_TYPE.'  ) AS mjd,';
        
        $qd_sql .= ' SUM( order_day between "'.$paramT['start'].'" AND "'.$paramT['end'].'" AND is_success = 1 AND consultation_type_id = '.HS_TYPE.') AS txd,';
        $qd_sql .= ' SUM( order_day between "'.$paramM['start'].'" AND "'.$paramM['end'].'" AND is_success = 1 AND consultation_type_id = '.HS_TYPE.') AS mxd,';
        $qd_sql .= ' shop_code,shop_name FROM  c_customerinfo WHERE c_from=1 and is_status=1 and shop_code in ('.$qd_shop_codes.')';

        $qdNums = db()->query($qd_sql);
        // echo db()->getLastSql();
        // var_dump($qdNums);exit;
        foreach ($qdNums as $key => $value) {
            $returnData['qd']['qdInto']      = $value['tjd'].' / '.$value['mjd'];
            $returnData['qd']['qdValidOrder']= $value['txd'].' / '.$value['mxd'];
            $returnData['qd']['qdOrderRate'] = round( ($value['txd']/$value['tjd'])*100, 2).'% / '.round( ($value['mxd']/$value['mjd'])*100, 2).'%';
        }
        
        return json($returnData);
    }

    // 事业部大屏基础数据
    public function brandBaseData(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            //controller('crm/Index', 'controller')->index();
            //exit;
        }
        $bid = session('brandclass_id');
        
        // 当天的开始结束时间
        $paramT['start'] = date('Y-m-d 00:00:00');
        $paramT['end']   = date('Y-m-d 23:59:59');
        $paramT['brandclass_id'] = $bid;
        // 本月的开始结束时间
        $paramM['start'] = date('Y-m-01 00:00:00');
        $paramM['end']   = date('Y-m-d 23:59:59');
        $paramM['brandclass_id'] = $bid;

        // 查看设定 当前事业部下  电商，有效客资设定
        $sta_set = db('s_sta_setting')
            ->where('brandclass_id', $bid)
            // ->where('is_marketing', 1)
            ->field('valid_customer_consumptiontype,shop_code,is_marketing,brandclass_id')
            ->select();
        // var_dump($sta_set);
        // exit;
        $validCustomerT = 0;
        $validCustomerM = 0;
        $noReceiveCustomer = 0;
        $onlineStaffs = 0;

        foreach ($sta_set as $key => $value) {
            // 电商
            if ($value['is_marketing'] == 1) {
                // 当日有效客资
                $paramT['shop_code'] = $value['shop_code'];
                $paramT['valid_customer_consumptiontype'] = $value['valid_customer_consumptiontype'];
                $validCustomerT += controller('crm/Bigscreen', 'lib')->getValidCustomer($paramT);
                // 今日未领取客资
                $noReceiveCustomer += controller('crm/Bigscreen', 'lib')->getNoReceiveCustomer($paramT);

                // 当月有效客资
                $paramM['shop_code'] = $value['shop_code'];
                $paramM['valid_customer_consumptiontype'] = $value['valid_customer_consumptiontype'];
                $validCustomerM += controller('crm/Bigscreen', 'lib')->getValidCustomer($paramM);
            }
            // 网销
            if ($value['is_marketing'] == 3) {
                // 网络顾问在线数
                $param['shop_code'] = $value['shop_code'];
                $onlineStaffs += controller('crm/Bigscreen', 'lib')->getOnlineStaffs($param);
            }   
        }

        $returnData['validCustomerT']    = $validCustomerT;
        $returnData['validCustomerM']    = $validCustomerM;
        $returnData['noReceiveCustomer'] = $noReceiveCustomer;
        $returnData['onlineStaffs']      = $onlineStaffs;

        return json($returnData);
    }

    // 事业部大屏 有效比例 饼状图
    public function brandValidRate(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            // controller('crm/Index', 'controller')->index();
            // exit;
        }
        $bid = session('brandclass_id');
        // 当天的开始结束时间
        $paramT['start'] = date('Y-m-d 00:00:00');
        $paramT['end']   = date('Y-m-d 23:59:59');
        $paramT['brandclass_id'] = $bid;
        // 本月的开始结束时间
        $paramM['start'] = date('Y-m-01 00:00:00');
        $paramM['end']   = date('Y-m-d 23:59:59');
        $paramM['brandclass_id'] = $bid;

        // 查看设定 当前事业部下  电商，有效客资设定
        $sta_set = db('s_sta_setting')
            ->where('brandclass_id', $bid)
            ->where('is_marketing', 1)
            ->field('valid_customer_consumptiontype,shop_code,is_marketing,brandclass_id')
            ->select();
        // var_dump($sta_set);
        // exit;
        $validCustomerT = 0;
        $validCustomerM = 0;
        $unvalidCustomerT = 0;
        $unvalidCustomerM = 0;

        foreach ($sta_set as $key => $value) {
            $paramT['shop_code'] = $value['shop_code'];
            $paramT['valid_customer_consumptiontype'] = $value['valid_customer_consumptiontype'];
            // 当月有效客资
            $validCustomerT  += controller('crm/Bigscreen', 'lib')->getValidCustomer($paramT);
            // 当月无效客资
            $unvalidCustomerT+= controller('crm/Bigscreen', 'lib')->getUnvalidCustomerNum($paramT);

            $paramM['shop_code'] = $value['shop_code'];
            $paramM['valid_customer_consumptiontype'] = $value['valid_customer_consumptiontype'];
            // 当月有效客资
            $validCustomerM  += controller('crm/Bigscreen', 'lib')->getValidCustomer($paramM);
            // 当月无效客资
            $unvalidCustomerM+= controller('crm/Bigscreen', 'lib')->getUnvalidCustomerNum($paramM);
        }

        $returnData['validCustomerT']   = $validCustomerT;
        $returnData['unvalidCustomerT'] = $unvalidCustomerT;
        $returnData['validCustomerM']   = $validCustomerM;
        $returnData['unvalidCustomerM'] = $unvalidCustomerM;

        return json($returnData);
    }

    // 事业部大屏无效客资柱状图
    public function brandUnvalidData(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            // controller('crm/Index', 'controller')->index();
            // exit;
        }
        $bid = session('brandclass_id');

        // 本月的开始结束时间
        $param['start'] = date('Y-m-01 00:00:00');
        $param['end']   = date('Y-m-d 23:59:59');
        $param['brandclass_id'] = $bid;

        // 查看设定 当前事业部下  电商，有效客资设定
        $sta_set = db('s_sta_setting')
            ->where('brandclass_id', $bid)
            ->where('is_marketing', 1)
            ->field('valid_customer_consumptiontype,shop_code,is_marketing,brandclass_id')
            ->select();
        $shop_codes = '';
        foreach ($sta_set as $key => $value) {
            $shop_codes .= $value['shop_code'].',';
        }

        $param['shop_codes'] = trim($shop_codes, ',');

        $unvalidCustomerNum = controller('crm/Bigscreen', 'lib')->getUnvalidCustomer($param);
        // return json($unvalidCustomerNum);
        $names = [];
        $data  = [];
        foreach ($unvalidCustomerNum as $key => $value) {
            // $names[$key] = mb_substr($value['reason'], 0, 6, 'utf-8').'...';
            $names[$key] = $value['reason'];
            $data[$key]  = $value['num'];

        }
        $returnData['names'] = $names;
        $returnData['data'] = $data;
        // var_dump($returnData);
        // exit;
        return json($returnData);
    }

    // 事业部大屏 渠道客资量 （日）
    public function brandChannelDay(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            // controller('crm/Index', 'controller')->index();
            // exit;
        }
        $bid = session('brandclass_id');
        // 当天的开始结束时间
        $param['start'] = date('Y-m-d 00:00:00');
        $param['end']   = date('Y-m-d 23:59:59');
        $param['brandclass_id'] = $bid;

        // 查看设定 当前事业部下  电商，毛客资设定
        $sta_set = db('s_sta_setting')
            ->where('brandclass_id', $bid)
            ->where('is_marketing', 1)
            ->field('all_customer_consumptiontype,shop_code,brandclass_id')
            ->select();

        $channelCustomerNum = 0;
        $shop_codes = '';
        foreach ($sta_set as $key => $value) {
            $shop_codes .= $value['shop_code'].',';
        }

        $param['shop_codes'] = trim($shop_codes, ',');

        $channelCustomerNum = controller('crm/Bigscreen', 'lib')->getChannelCustomerNum($param);
        
        // return json($channelCustomerNum);
        $names = [];
        $data  = [];
        foreach ($channelCustomerNum as $key => $value) {
            $names[$key] = $value['channel_name'];
            $data[$key]  = $value['num'];

        }
        $returnData['names'] = $names;
        $returnData['data'] = $data;
        return json($returnData);
    }

    // 事业部大屏 渠道客资量 （月）
    public function brandChannelMonth(){
        // 权限
        $auth = check_right('menu1526378178');
        if (!$auth) {
            // controller('crm/Index', 'controller')->index();
            // exit;
        }
        $bid = session('brandclass_id');

        // 本月的开始结束时间
        $param['start'] = date('Y-m-01 00:00:00');
        $param['end']   = date('Y-m-d 23:59:59');
        $param['brandclass_id'] = $bid;

        // 查看设定 当前事业部下  电商，毛客资设定
        $sta_set = db('s_sta_setting')
            ->where('brandclass_id', $bid)
            ->where('is_marketing', 1)
            ->field('all_customer_consumptiontype,shop_code,brandclass_id')
            ->select();
        $shop_codes = '';
        foreach ($sta_set as $key => $value) {
            $shop_codes .= $value['shop_code'].',';
        }

        $param['shop_codes'] = trim($shop_codes, ',');

        $channelCustomerNum = controller('crm/Bigscreen', 'lib')->getChannelCustomerNum($param);

        // return json($channelCustomerNum);
        $names = [];
        $data  = [];
        foreach ($channelCustomerNum as $key => $value) {
            $names[$key] = $value['channel_name'];
            $data[$key]  = $value['num'];

        }
        $returnData['names'] = $names;
        $returnData['data'] = $data;

        return json($returnData);
    }
    // ---------------------------------------- 事业部大屏 end ------------------------------------------- //

    // ---------------------------------------- 事业部大屏显示项目设定 start ------------------------------------------- //
    public function setBrandShow(){
        // 权限
        $auth = check_right('menu1554175732');
        if (!$auth) {
           // return $this->redirect('/');
        }
        $bid = session('brandclass_id');
        // 有事业部id
        if ($bid) {
            // 查看当前事业部的
            $temp = db('s_bg_brandshow')->where('brandclass_id',$bid)->select();
            if ($temp) {
                $setshow = [];
                foreach ($temp as $key => $value) {
                    array_push($setshow, $value['bg_show']);
                }
                $isset = 1;
            }
        }else{
            // 查看全部的  需要事业部列表
            $setshow = '';
            $isset = '';
        }
        // var_dump($setshow);exit;
        $this->assign('setshow', $setshow);
        $this->assign('isset', $isset);
        return $this->fetch();
    }
    public function setBrandShowAction(){
        $data = input('post.');
        // var_dump($data);exit;
        $inData = [];
        $num = db('s_bg_brandshow')->where('brandclass_id',session('brandclass_id'))->field('brandclass_id')->select();
        if ($num) {
            db('s_bg_brandshow')->where('brandclass_id',session('brandclass_id'))->delete();
        }
        foreach ($data['set'] as $key => $value) {
            $temp['staff_id'] = session('staff_id');
            $temp['staff_name'] = session('staff_name');
            $temp['brandclass_id'] = session('brandclass_id');
            $temp['brandclass'] = session('brandclass');
            $temp['bg_name'] = $value['bg_name'];
            $temp['bg_show'] = $value['bg_show'];
            $temp['create_time'] = date("Y-m-d H:i:s", time());
            array_push($inData,$temp);
        }
        // var_dump($inData);exit;
        $res = db('s_bg_brandshow')->insertAll($inData);
        if ($res === false) {
            $returnData['code'] = 100;
            $returnData['msg']  = '设定失败';
            $returnData['data'] = db()->getLastSql();
        }else{
            $returnData['code'] = 200;
            $returnData['msg']  = '设定成功';
            $returnData['data'] = '';
        }
        return $returnData;
    }
    // ---------------------------------------- 事业部大屏显示项目设定 end ------------------------------------------- //

}