<?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 Jujiao extends Controller{
    
    // 大屏页面  
    public function index(){
        $auth = controller('crm/Jujiao', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $no_bids = config('no_bigScreen_bid');
        $no_bids = explode(',', $no_bids);
        
        $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
        // var_dump($shopList);
        // exit;

        $this->assign('shopList', $shopList);
        $this->assign('title','聚焦摄影集团  【电商战报大屏】');
        return $this->fetch();
    }

    // 页面基础数据
    public function baseData(){
        // echo 'START==>'.microtime(true).'<br />';     
        // 权限
        $auth = controller('crm/Jujiao', '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');

        // 如果有shop_code 查店下的数据 传的参数名叫 brandclass_id 
        $post = input('post.');
        $shop_code = $post['brandclass_id'] ? $post['brandclass_id'] : null;

        if ($shop_code) {
            $tData['add_shop_code'] = $shop_code;
            $mData['add_shop_code'] = $shop_code;
        }else{
            // 没有事业部查集团所有shop_code
            $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
            $shopCodes = '';
            foreach ($shopList as $key => $value) {
                $shopCodes .= $value['shop_code'].',';
            }
            $shopCodes = trim($shopCodes, ',');
            $tData['add_shop_code'] = $shopCodes;
            $mData['add_shop_code'] = $shopCodes;
        }

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

        //总获取（毛客资）
        $allCusT = controller('crm/Jujiao', 'lib')->getCustomerNum($tData);
        $allCusM = controller('crm/Jujiao', 'lib')->getCustomerNum($mData);
        $allCus  = $allCusT.' / '.$allCusM;
        // 有效客资
        $validCustomerT = controller('crm/Jujiao', 'lib')->getInvCustomerNum($tData);
        $validCustomerM = controller('crm/Jujiao', 'lib')->getInvCustomerNum($mData);
        $validCustomer  = $validCustomerT.' / '.$validCustomerM;
        // 获取成本 成本 / 有效
        $validObtail = round($costMoneyT/$validCustomerT).' / '.round($costMoneyM/$validCustomerM);

        // 网络进客 取消不要
        // $intoCustomerT = controller('crm/Jujiao', 'lib')->getIntoCustomerNum($tData);
        // $intoCustomerM = controller('crm/Jujiao', 'lib')->getIntoCustomerNum($mData);
        // $intoCustomer = $intoCustomerT.'/'.$intoCustomerM;

        // 自然进店  渠道标记为 ‘自然进店’
        $intoCustomerT = controller('crm/Jujiao', 'lib')->getIntoCustomerNum($tData);
        $intoCustomerM = controller('crm/Jujiao', 'lib')->getIntoCustomerNum($mData);
        $intoCustomer = $intoCustomerT.'/'.$intoCustomerM;

        // 网络新单
        $orderCustomerT = controller('crm/Jujiao', 'lib')->getOrderNumberNum($tData);
        $orderCustomerM = controller('crm/Jujiao', 'lib')->getOrderNumberNum($mData);
        $orderCustomer = $orderCustomerT.'/'.$orderCustomerM;
        // 网络营收 
        // $moneyT = controller('crm/Jujiao', 'lib')->incomeMoney($tData);
        // $moneyM = controller('crm/Jujiao', 'lib')->incomeMoney($mData);
        // $money = $moneyT.' / '.$moneyM;

        // 套系总额
        $moneyT = controller('crm/Jujiao', 'lib')->dealMoney($tData);
        $moneyM = controller('crm/Jujiao', 'lib')->dealMoney($mData);
        $money = $moneyT.' / '.$moneyM;

        // 日转化率  订单数量 / 毛客资
        $dayChangeRate = ($orderCustomerT / $allCusT)*100;
        $dayChangeRate = number_format($dayChangeRate, 2).'%';
        // 月转化率  订单数量 / 毛客资
        $monthChangeRate = ($orderCustomerM / $allCusM)*100;
        $monthChangeRate = number_format($monthChangeRate, 2).'%';
        // 成交率  订单数量 / 有效获取
        $succRate = (number_format($orderCustomerT/$validCustomerT,2)*100).'%  / '.(number_format($orderCustomerM/$validCustomerM,2)*100).'%';

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

    // 四个排行榜
    public function rankData(){
        $auth = controller('crm/Jujiao', '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]));

        $post = input('post.');
        $shop_code = $post['brandclass_id'] ? $post['brandclass_id'] : null;

        // echo microtime(true).'<hr />';
        // 当前店下的部门的排行
        if ($shop_code == 'JJ001' || $shop_code == 'JJET003') {
            $data['add_shop_code'] = $shop_code;
            $returnData = $this->groupRank($data);
        }
        // 所有店的排行
        else{
            $returnData = $this->shopRank();
            // echo microtime(true).'<hr />';
        }
        // exit;
        return json($returnData);        
    }

    // 店排行
    public function shopRank(){
        // 日 开始结束时间
        $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]));
        unset($date);
        $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
        $baseShop = [];
        $shopCodes = '';
        foreach ($shopList as $key => $value) {
            $baseShop[$key]['shop_code'] = $value['shop_code'];
            $baseShop[$key]['shop_name'] = $value['shop_name'];
            $baseShop[$key]['dayNum']    = 0;
            $baseShop[$key]['monthNum']  = 0;

            $shopCodes .= $value['shop_code'].',';
        }
        unset($shopList);
        $shopCodes = trim($shopCodes, ',');
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        $where['customer_type'] = 1;
        /* -----------------------------------------------------  毛客资排名开始  ----------------------------------------------------- */
        // echo '毛客资开始--'.microtime(true).'<hr />';
        $dayNewCus = db('c_customerinfo force index(dj)')
            ->where($where)
            ->where('add_shop_code', 'in', $shopCodes)
            ->where('dj_day', 'between time', [$today_start, $today_end])
            ->group('add_shop_code')
            ->field('COUNT(id) AS dayNum, 0 AS monthNum, add_shop_code as shop_code, add_shop_name as shop_name')
            ->order('dayNum', 'desc')
            ->select();
        $monthNewCus = db('c_customerinfo force index(dj)')
            ->where($where)
            ->where('add_shop_code', 'in', $shopCodes)
            ->where('dj_day', 'between time', [$month_start, $month_end])
            ->group('add_shop_code')
            ->field('COUNT(id) AS monthNum, 0 AS dayNum, add_shop_code as shop_code, add_shop_name as shop_name')
            ->order('dayNum', 'desc')
            ->select();

        $merge = array_merge($dayNewCus, $monthNewCus, $baseShop);
        $temp = [];
        foreach ($merge as $key => $value) {
            $temp[$value['shop_code']]['shop_code'] = $value['shop_code'];
            $temp[$value['shop_code']]['shop_name'] = $value['shop_name'];
            $temp[$value['shop_code']]['dayNum']   += $value['dayNum'];
            $temp[$value['shop_code']]['monthNum'] += $value['monthNum'];
        }

        unset($merge,$dayNewCus,$monthNewCus);

        $sort_order = 'SORT_DESC';
        $temp = my_sort($temp, 'dayNum', $sort_order);
        $shopDayNew = [];
        foreach ($temp as $key => $value) {
            array_push($shopDayNew, $value);
        }
        // var_dump($shopDayNew);
        // exit;
        /* -----------------------------------------------------  毛客资排名结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  有效排名开始  ----------------------------------------------------- */
        // echo '有效开始0--'.microtime(true).'<hr />';
        $dayIntoCus = db('c_customerinfo force index(dj)')
            ->where($where)
            ->where('is_valid', 1)
            ->where('shop_code', 'in', $shopCodes)
            ->where('dj_day', 'between time', [$today_start, $today_end])
            ->group('shop_code')
            ->field('COUNT(id) AS dayNum, 0 AS monthNum, shop_code, shop_name')
            ->order('dayNum', 'desc')
            ->select();
        // echo '有效开始1--'.microtime(true).'<hr />';
        $monthIntoCus = db('c_customerinfo force index(dj)')
            ->where($where)
            ->where('is_valid', 1)
            ->where('shop_code', 'in', $shopCodes)
            ->where('dj_day', 'between time', [$month_start, $month_end])
            ->group('shop_code')
            ->field('COUNT(id) AS monthNum, 0 AS dayNum, shop_code, shop_name')
            ->order('dayNum', 'desc')
            ->select();
        // echo db()->getLastSql().'<hr />';
        // echo '有效开始2--'.microtime(true).'<hr />';
        $merge = array_merge($dayIntoCus, $monthIntoCus, $baseShop);
        // exit;
        $temp = [];
        foreach ($merge as $key => $value) {
            $temp[$value['shop_code']]['shop_code'] = $value['shop_code'];
            $temp[$value['shop_code']]['shop_name'] = $value['shop_name'];
            $temp[$value['shop_code']]['dayNum']   += $value['dayNum'];
            $temp[$value['shop_code']]['monthNum'] += $value['monthNum'];
        }
        unset($merge);
        unset($dayIntoCus);
        unset($monthOrdeCus);
        $sort_order = 'SORT_DESC';
        $temp= my_sort($temp, 'dayNum', $sort_order);
        $shopDayInto = [];
        foreach ($temp as $key => $value) {
            array_push($shopDayInto, $value);
        }
        // echo '有效开始3--'.microtime(true).'<hr />';
        // var_dump($shopDayInto);
        // exit;
        /* -----------------------------------------------------  邀约排名结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  新单排名开始  ----------------------------------------------------- */
        // echo '新单开始--'.microtime(true).'<hr />';
        $dayOrdeCus = db('c_customer_order')
            // ->where($where)
            ->where('order_valid', 2)
            ->where('is_delete', 2)
            ->where('shop_code', 'in', $shopCodes)
            ->where('create_time', 'between time', [$today_start, $today_end])
            ->where('order_amount', '>', '0')
            ->group('shop_code')
            ->field('COUNT(id) AS dayNum, 0 AS monthNum, shop_code, shop_name')
            ->order('dayNum', 'desc')
            ->select();
        // echo db()->getLastSql();
        // exit;
        $monthOrdeCus = db('c_customer_order')
            // ->where($where)
            ->where('order_valid', 2)
            ->where('is_delete', 2)
            ->where('shop_code', 'in', $shopCodes)
            ->where('create_time', 'between time', [$month_start, $month_end])
            ->where('order_amount', '>', '0')
            ->group('shop_code')
            ->field('COUNT(id) AS monthNum, 0 AS dayNum, shop_code, shop_name')
            ->order('dayNum', 'desc')
            ->select();
        $merge = array_merge($dayOrdeCus, $monthOrdeCus, $baseShop);
        $temp = [];
        foreach ($merge as $key => $value) {
            $temp[$value['shop_code']]['shop_code'] = $value['shop_code'];
            $temp[$value['shop_code']]['shop_name'] = $value['shop_name'];
            $temp[$value['shop_code']]['dayNum']   += $value['dayNum'];
            $temp[$value['shop_code']]['monthNum'] += $value['monthNum'];
        }
        unset($merge);
        unset($dayOrdeCus);
        unset($monthOrdeCus);
        $sort_order = 'SORT_DESC';
        $temp = my_sort($temp, 'dayNum', $sort_order);
        $shopDayOrder = [];
        foreach ($temp as $key => $value) {
            array_push($shopDayOrder, $value);
        }
        // var_dump($shopDayOrder);
        // exit;
        /* -------------------------------------------------------  新单排名结束 ------------------------------------------------------- */

        /* ------------------------------------------------  各店营收（套系总额）排名开始 ------------------------------------------------ */
        $dayOrdeMoney = db('c_customer_order')
            ->where('order_valid', 2)
            ->where('is_delete', 2)
            ->where('shop_code', 'in', $shopCodes)
            ->where('create_time', 'between time', [$today_start, $today_end])
            ->group('shop_code')
            ->field('SUM(order_amount) AS dayNum, 0 AS monthNum, shop_code, shop_name')
            ->order('dayNum', 'desc')
            ->select();
        // $monthOrdeMoney = [];
        $monthOrdeMoney = db('c_customer_order')
            ->where('order_valid', 2)
            ->where('is_delete', 2)
            ->where('shop_code', 'in', $shopCodes)
            ->where('create_time', 'between time', [$month_start, $month_end])
            ->group('shop_code')
            ->field('SUM(order_amount) AS monthNum, 0 AS dayNum, shop_code, shop_name')
            ->order('dayNum', 'desc')
            ->select();

        $merge = array_merge($dayOrdeMoney, $monthOrdeMoney, $baseShop);
        $temp = [];
        foreach ($merge as $key => $value) {
            $temp[$value['shop_code']]['shop_code'] = $value['shop_code'];
            $temp[$value['shop_code']]['shop_name'] = $value['shop_name'];
            $temp[$value['shop_code']]['dayNum']   += $value['dayNum'];
            $temp[$value['shop_code']]['monthNum'] += $value['monthNum'];
        }
        unset($merge);
        unset($dayOrdeMoney);
        unset($monthOrdeMoney);
        $sort_order = 'SORT_DESC';
        $temp = my_sort($temp, 'dayNum', $sort_order);
        $shopDayOrderMoney = [];
        foreach ($temp as $key => $value) {
            array_push($shopDayOrderMoney, $value);
        }
        unset($temp);
        /* ------------------------------------------------  各店营收（套系总额）排名开始 ------------------------------------------------ */
        $returnData = [
            'brandDayNew'  => $shopDayNew,
            'brandDayInto' => $shopDayInto,
            'brandDayOrder'=> $shopDayOrder,
            'shopChannelOrder'=>$shopDayOrderMoney,

        ];
        unset($shopDayNew,$shopDayInto,$shopDayOrder,$shopDayOrderMoney);
        return $returnData;
    }
    // 小组排行
    public function groupRank_old($param){
        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // $today_start = date('Y-m-d 00:00:00', strtotime('-1 day'));
        // $today_end   = date('Y-m-d 23:59:59', strtotime('-1 day'));
        // 月 开始结束时间
        $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]));
        unset($date);
        // 根据shop_code 查看小组及小组成员
        $temp = db('c_staffGroup')->alias('g')
            ->join('c_staff_group_relation r','g.id=r.group_id')
            ->where('g.shop_code', $param['add_shop_code'])
            ->order('g.id')
            ->field('g.id,g.group_name,r.staff_id,r.staff_name')
            ->select();

        $groupInfo = [];
        $allIds = '';
        foreach ($temp as $key => $value) {
            $allIds.= $value['staff_id'].',';
            $groupInfo[$value['id']]['id']   = $value['id'];
            $groupInfo[$value['id']]['name'] = $value['group_name'];
            $groupInfo[$value['id']]['gids'].= $value['staff_id'].',';
            // $groupInfo[$value['id']]['staff'][$value['staff_id']]['staff_id']  = $value['staff_id'];
            // $groupInfo[$value['id']]['staff'][$value['staff_id']]['staff_name']= $value['staff_name'];
        }
        $allIds = trim($allIds, ',');
        unset($temp);
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        $where['customer_type'] = 1;
        /* -----------------------------------------------------  小组订单排名 开始  ----------------------------------------------------- */
        // echo '组订单排名--'.microtime(true).'<hr />';
        $groupOrderNum = [];
        foreach ($groupInfo as $key => $value) {
            $gStaffs = trim($value['gids'], ',');
            //var_dump($gStaffs);
            $groupDayOrder = db('c_customer_order')->alias('o')
                ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
                ->where('c.sales_staff_id', 'in', $gStaffs)
                //->where('o.order_valid', 2)
                ->where('o.is_delete', 2)
                ->where('o.shop_code', $param['add_shop_code'])
                ->where('o.create_time', 'between time', [$today_start, $today_end])
                ->count();
            if(session('staff_name')=='cs'){
                //echo db()->getLastSql().'<br>';
            }
            $groupMonthOrder = db('c_customer_order')->alias('o')
                ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
                ->where('c.sales_staff_id', 'in', $gStaffs)
                //->where('o.order_valid', 2)
                ->where('o.is_delete', 2)
                ->where('o.shop_code', $param['add_shop_code'])
                ->where('o.create_time', 'between time', [$month_start, $month_end])
                ->count();            
            $groupOrderNum[$key]['shop_code']= $value['id'];
            $groupOrderNum[$key]['shop_name']= $value['name'];
            $groupOrderNum[$key]['dayNum']   = $groupDayOrder ? (int)$groupDayOrder : 0;
            $groupOrderNum[$key]['monthNum'] = $groupMonthOrder ? (int)$groupMonthOrder : 0;
        }
        //exit;
        unset($groupDayOrder,$groupMonthOrder);
        $sort_order = 'SORT_DESC';
        $groupOrderNum = my_sort($groupOrderNum, 'dayNum', $sort_order);
        // var_dump($shopDayNew);
        // exit;
        /* -----------------------------------------------------  小组订单排名 结束  ----------------------------------------------------- */
        
        /* -----------------------------------------------------  小组业绩排名 开始  ----------------------------------------------------- */
        // echo '组业绩排名--'.microtime(true).'<hr />';
        $groupMoneyNum = [];
        foreach ($groupInfo as $key => $value) {
            $gStaffs = trim($value['gids'], ',');
            
            $groupDayMoney = db('c_customer_order')->alias('o')
                ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
                ->where('c.sales_staff_id', 'in', $gStaffs)
                //->where('o.order_valid', 2)
                ->where('o.is_delete', 2)
                ->where('o.shop_code', $param['add_shop_code'])
                ->where('o.create_time', 'between time', [$today_start, $today_end])
                ->sum('o.order_amount');
            if(session('staff_name')=='张俊'){
                //echo db()->getLastSql().'<br>';
            }

            $groupMoneyMoney = db('c_customer_order')->alias('o')
                ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
                ->where('c.sales_staff_id', 'in', $gStaffs)
                //->where('o.order_valid', 2)
                ->where('o.is_delete', 2)
                ->where('o.shop_code', $param['add_shop_code'])
                ->where('o.create_time', 'between time', [$month_start, $month_end])
                ->sum('o.order_amount');

            $groupMoneyNum[$key]['shop_code']= $value['id'];
            $groupMoneyNum[$key]['shop_name']= $value['name'];
            $groupMoneyNum[$key]['dayNum']   = $groupDayMoney ? (int)$groupDayMoney : 0;
            $groupMoneyNum[$key]['monthNum'] = $groupMoneyMoney ? (int)$groupMoneyMoney : 0;
        }
        //exit;
        unset($groupDayMoney,$groupMoneyMoney);
        $sort_order = 'SORT_DESC';
        $groupMoneyNum = my_sort($groupMoneyNum, 'dayNum', $sort_order);

        /* -----------------------------------------------------  小组业绩排名 结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  个人新单排名 开始  ----------------------------------------------------- */
        // echo '人订单排名--'.microtime(true).'<hr />';
        $staffDayNum = 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.shop_code', $param['add_shop_code'])
            ->where('o.create_time', 'between time', [$today_start, $today_end])
            ->where('c.sales_staff_id', 'in', $allIds)
            ->group('c.sales_staff_id')
            ->column('count(*) as dayNum, c.sales_staff', 'c.sales_staff_id');
        $staffMonthNum = 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.shop_code', $param['add_shop_code'])
            ->where('o.create_time', 'between time', [$month_start, $month_end])
            ->where('c.sales_staff_id', 'in', $allIds)
            ->group('c.sales_staff_id')
            ->column('count(*) as monthNum, c.sales_staff', 'c.sales_staff_id');

        $staffOrderNum = [];
        foreach ($staffMonthNum as $key => $value) {
            $temp['shop_code']= $value['sales_staff_id'];
            $temp['shop_name']= $value['sales_staff'];
            $temp['dayNum']   = $staffDayNum[$key]['dayNum'] ? (int)$staffDayNum[$key]['dayNum'] : 0;
            $temp['monthNum'] = $value['monthNum'] ? (int)$value['monthNum'] : 0;
            array_push($staffOrderNum, $temp);
        }
        unset($staffDayNum,$staffMonthNum);
        $sort_order = 'SORT_DESC';
        $staffOrderNum = my_sort($staffOrderNum, 'dayNum', $sort_order);
        $staffOrderNum = array_slice($staffOrderNum, 0, 8);
        /* -----------------------------------------------------  个人新单排名 结束 ----------------------------------------------------- */

        /* -----------------------------------------------------  个人新单业绩 开始  ----------------------------------------------------- */
        // echo '人业绩排名--'.microtime(true).'<hr />';
        $staffDayMoney = 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.shop_code', $param['add_shop_code'])
            ->where('o.create_time', 'between time', [$today_start, $today_end])
            ->where('c.sales_staff_id', 'in', $allIds)
            ->group('c.sales_staff_id')
            ->column('sum(totalpay_money) as dayNum, c.sales_staff', 'c.sales_staff_id');
        $staffMonthMoney = 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.shop_code', $param['add_shop_code'])
            ->where('o.create_time', 'between time', [$month_start, $month_end])
            ->where('c.sales_staff_id', 'in', $allIds)
            ->group('c.sales_staff_id')
            ->column('sum(totalpay_money) as monthNum, c.sales_staff', 'c.sales_staff_id');
        // var_dump($staffMonthMoney);
        // exit;
        $staffMoneyNum = [];
        foreach ($staffMonthMoney as $key => $value) {
            $temp['shop_code']= $value['sales_staff_id'];
            $temp['shop_name']= $value['sales_staff'];
            $temp['dayNum']   = $staffDayMoney[$key]['dayNum'] ? (int)$staffDayMoney[$key]['dayNum'] : 0;
            $temp['monthNum'] = $value['monthNum'] ? (int)$value['monthNum'] : 0;
            array_push($staffMoneyNum, $temp);
        }
        unset($staffDayMoney,$staffMonthMoney);
        $sort_order = 'SORT_DESC';
        $staffMoneyNum = my_sort($staffMoneyNum, 'dayNum', $sort_order);
        $staffMoneyNum = array_slice($staffMoneyNum, 0, 8);
        /* -----------------------------------------------------  个人新单业绩 结束  ----------------------------------------------------- */
        $returnData = [
            'brandDayNew'  => $groupOrderNum,
            'brandDayInto' => $groupMoneyNum,
            'brandDayOrder'=> $staffOrderNum,
            'shopChannelOrder'=>$staffMoneyNum,
        ];
        unset($groupInfo);
        unset($groupOrderNum);
        unset($groupMoneyNum);
        unset($staffOrderNum);
        unset($staffMoneyNum);
        return $returnData;
    }
    public function groupRank($param){
        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // $today_start = date('Y-m-d 00:00:00', strtotime('-1 day'));
        // $today_end   = date('Y-m-d 23:59:59', strtotime('-1 day'));
        // 月 开始结束时间
        $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]));
        unset($date);
        // 根据shop_code 查看小组及小组成员
        $temp = db('c_staffGroup')->alias('g')
            ->join('c_staff_group_relation r','g.id=r.group_id')
            ->where('g.shop_code', $param['add_shop_code'])
            ->order('g.id')
            ->field('g.id,g.group_name,r.staff_id,r.staff_name')
            ->select();

        $groupInfo = [];
        $allIds = '';
        foreach ($temp as $key => $value) {
            $allIds.= $value['staff_id'].',';
            $groupInfo[$value['id']]['id']   = $value['id'];
            $groupInfo[$value['id']]['name'] = $value['group_name'];
            $groupInfo[$value['id']]['gids'].= $value['staff_id'].',';
        }
        $allIds = trim($allIds, ',');
        unset($temp);
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        $where['customer_type'] = 1;
        /* -----------------------------------------------------  小组订单排名 开始  ----------------------------------------------------- */
        // echo '组订单排名--'.microtime(true).'<hr />';
        $groupOrderNum = [];
        $eo_tstart= date('Ymd', strtotime($today_start));
        $eo_tend  = date('Ymd', strtotime($today_end));
        $eo_mstart= date('Ymd', strtotime($month_start));
        $eo_mend  = date('Ymd', strtotime($month_end));
        foreach ($groupInfo as $key => $value) {
            $gStaffs = trim($value['gids'], ',');
            
            $sql = "SELECT COUNT(*) AS count FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$gStaffs.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_tstart."' AND '".$eo_tend."' AND d.payment_money>0 LIMIT 1";
            $count = db()->query($sql);
            $groupDayOrder = $count[0]['count'];

            $sql = "SELECT COUNT(*) AS count FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$gStaffs.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_mstart."' AND '".$eo_mend."' AND d.payment_money>0 LIMIT 1";
            $count = db()->query($sql);
            $groupMonthOrder = $count[0]['count'];
            $groupOrderNum[$key]['shop_code']= $value['id'];
            $groupOrderNum[$key]['shop_name']= $value['name'];
            $groupOrderNum[$key]['dayNum']   = $groupDayOrder ? (int)$groupDayOrder : 0;
            $groupOrderNum[$key]['monthNum'] = $groupMonthOrder ? (int)$groupMonthOrder : 0;
        }
        //exit;
        unset($groupDayOrder,$groupMonthOrder);
        $sort_order = 'SORT_DESC';
        $groupOrderNum = my_sort($groupOrderNum, 'dayNum', $sort_order);
        // var_dump($shopDayNew);
        // exit;
        /* -----------------------------------------------------  小组订单排名 结束  ----------------------------------------------------- */
        
        /* -----------------------------------------------------  小组业绩排名 开始  ----------------------------------------------------- */
        // echo '组业绩排名--'.microtime(true).'<hr />';
        $groupMoneyNum = [];
        foreach ($groupInfo as $key => $value) {
            $gStaffs = trim($value['gids'], ',');

            $sql = "SELECT SUM(`d`.`bargain_money`) AS count FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$gStaffs.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_tstart."' AND '".$eo_tend."' AND d.payment_money>0 LIMIT 1";
            $count = db()->query($sql);
            $groupDayMoney = $count[0]['count'];
            // echo db()->getLastSql();
            // var_dump($groupDayMoney);
            // exit;

            $sql = "SELECT SUM(`d`.`bargain_money`) AS count FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$gStaffs.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_mstart."' AND '".$eo_mend."' AND d.payment_money>0 LIMIT 1";
            $count = db()->query($sql);
            $groupMoneyMoney = $count[0]['count'];

            $groupMoneyNum[$key]['shop_code']= $value['id'];
            $groupMoneyNum[$key]['shop_name']= $value['name'];
            $groupMoneyNum[$key]['dayNum']   = $groupDayMoney ? (int)$groupDayMoney : 0;
            $groupMoneyNum[$key]['monthNum'] = $groupMoneyMoney ? (int)$groupMoneyMoney : 0;
        }
        //exit;
        unset($groupDayMoney,$groupMoneyMoney);
        $sort_order = 'SORT_DESC';
        $groupMoneyNum = my_sort($groupMoneyNum, 'dayNum', $sort_order);

        /* -----------------------------------------------------  小组业绩排名 结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  个人新单排名 开始  ----------------------------------------------------- */
        // echo '人订单排名--'.microtime(true).'<hr />';
        $sql = "SELECT count(*) AS dayNum,`c`.`sales_staff`,`c`.`sales_staff_id` FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$allIds.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_tstart."' AND '".$eo_tend."' AND d.payment_money>0 GROUP BY `c`.`sales_staff_id`";
        $staffDayNum = db()->query($sql);

        $sql = "SELECT count(*) AS monthNum,`c`.`sales_staff`,`c`.`sales_staff_id` FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$allIds.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_mstart."' AND '".$eo_mend."' AND d.payment_money>0 GROUP BY `c`.`sales_staff_id`";
        $staffMonthNum = db()->query($sql);

        $staffOrderNum = [];
        foreach ($staffMonthNum as $key => $value) {
            $temp['shop_code']= $value['sales_staff_id'];
            $temp['shop_name']= $value['sales_staff'];
            $temp['dayNum']   = $staffDayNum[$key]['dayNum'] ? (int)$staffDayNum[$key]['dayNum'] : 0;
            $temp['monthNum'] = $value['monthNum'] ? (int)$value['monthNum'] : 0;
            array_push($staffOrderNum, $temp);
        }
        unset($staffDayNum,$staffMonthNum);
        $sort_order = 'SORT_DESC';
        $staffOrderNum = my_sort($staffOrderNum, 'dayNum', $sort_order);
        $staffOrderNum = array_slice($staffOrderNum, 0, 8);
        /* -----------------------------------------------------  个人新单排名 结束 ----------------------------------------------------- */

        /* -----------------------------------------------------  个人新单业绩 开始  ----------------------------------------------------- */
        // echo '人业绩排名--'.microtime(true).'<hr />';
        $staffDayMoney = 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.shop_code', $param['add_shop_code'])
            ->where('o.create_time', 'between time', [$today_start, $today_end])
            ->where('c.sales_staff_id', 'in', $allIds)
            ->group('c.sales_staff_id')
            ->column('sum(totalpay_money) as dayNum, c.sales_staff', 'c.sales_staff_id');

        $sql = "SELECT SUM(`d`.`bargain_money`) AS dayNum,`c`.`sales_staff`,`c`.`sales_staff_id` FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$allIds.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_tstart."' AND '".$eo_tend."' AND d.payment_money>0 GROUP BY `c`.`sales_staff_id`";
        $staffDayMoney = db()->query($sql);

        $sql = "SELECT SUM(`d`.`bargain_money`) AS monthNum,`c`.`sales_staff`,`c`.`sales_staff_id` FROM `c_customer_order` `o` LEFT JOIN `c_customerinfo` `c` ON `c`.`id` = `o`.`customer_id` LEFT JOIN `sx_erp`.`c_customerorder` `d` ON `d`.`orderId` = `o`.`order_sn` WHERE `c`.`sales_staff_id` IN (".$allIds.") AND `d`.`shop_code` = '".$param['add_shop_code']."' AND d.targetdate BETWEEN '".$eo_mstart."' AND '".$eo_mend."' AND d.payment_money>0 GROUP BY `c`.`sales_staff_id`";
        $staffMonthMoney = db()->query($sql);

        $staffMoneyNum = [];
        foreach ($staffMonthMoney as $key => $value) {
            $temp['shop_code']= $value['sales_staff_id'];
            $temp['shop_name']= $value['sales_staff'];
            $temp['dayNum']   = $staffDayMoney[$key]['dayNum'] ? (int)$staffDayMoney[$key]['dayNum'] : 0;
            $temp['monthNum'] = $value['monthNum'] ? (int)$value['monthNum'] : 0;
            array_push($staffMoneyNum, $temp);
        }
        unset($staffDayMoney,$staffMonthMoney);
        $sort_order = 'SORT_DESC';
        $staffMoneyNum = my_sort($staffMoneyNum, 'dayNum', $sort_order);
        $staffMoneyNum = array_slice($staffMoneyNum, 0, 8);
        /* -----------------------------------------------------  个人新单业绩 结束  ----------------------------------------------------- */
        $returnData = [
            'brandDayNew'  => $groupOrderNum,
            'brandDayInto' => $groupMoneyNum,
            'brandDayOrder'=> $staffOrderNum,
            'shopChannelOrder'=>$staffMoneyNum,
        ];
        unset($groupInfo,$groupOrderNum,$groupMoneyNum,$staffOrderNum,$staffMoneyNum);
        return $returnData;
    }

    // 转化漏斗 （日） 图
    public function dayChangeRate(){
        $auth = controller('crm/Jujiao', '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'] = $post['brandclass_id'] ? $post['brandclass_id'] : 0;

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

        return json($returnData);
    }

    // 转化漏斗 （月） 图
    public function monthChangeRate(){
        $auth = controller('crm/Jujiao', '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'] = $post['brandclass_id'] ? $post['brandclass_id'] : 0;

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

        return json($returnData);
    }

    // 转化漏斗数据 
    public function getChangeLdData($data){
        $shop_code = $data['brandclass_id'];

        if ($shop_code) {
            $data['add_shop_code'] = $shop_code;
        }else{
            $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
            $shopCodes = '';
            foreach ($shopList as $key => $value) {
                $shopCodes .= $value['shop_code'].',';
            }
            $shopCodes = trim($shopCodes, ',');
            $data['add_shop_code'] = $shopCodes;
        }
        
        // 毛客资
        $customerNum = controller('crm/Jujiao', 'lib')->getCustomerNum($data);
        $returnData[0]['name'] = '毛客资量';
        $returnData[0]['data'] = $customerNum;
        // 有效客资
        $invCustomer = controller('crm/Jujiao', 'lib')->getInvCustomerNum($data);
        $returnData[1]['name'] = '有效客资';
        $returnData[1]['data'] = $invCustomer;
        // // 获取手机
        // $telCustomer = controller('crm/Statistics', 'lib')->getTelCustomerNum($data);
        // $returnData[2]['name'] = '获取手机';
        // $returnData[2]['data'] = $telCustomer;

        // 进店/邀约 量
        // $intoCustomer= controller('crm/Jujiao', 'lib')->getIntoCustomerNum($data);

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

    // 本月毛客资量走势 图
    public function monthCustomerNumber(){
        $auth = controller('crm/Jujiao', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $shop_code = $post['brandclass_id'] ? $post['brandclass_id'] : 0;
        
        if ($shop_code) {
            $data['add_shop_code'] = $shop_code;
        }else{
            $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
            $shopCodes = '';
            foreach ($shopList as $key => $value) {
                $shopCodes .= $value['shop_code'].',';
            }
            $shopCodes = trim($shopCodes, ',');
            $data['add_shop_code'] = $shopCodes;
        }


        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange(date('Y-m-d',strtotime($date[0])), date('Y-m-d',strtotime($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/Statistics', '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/Jujiao', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $shop_code = $post['brandclass_id'] ? $post['brandclass_id'] : 0;
        
        if ($shop_code) {
            $data['add_shop_code'] = $shop_code;
        }else{
            $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
            $shopCodes = '';
            foreach ($shopList as $key => $value) {
                $shopCodes .= $value['shop_code'].',';
            }
            $shopCodes = trim($shopCodes, ',');
            $data['add_shop_code'] = $shopCodes;
        }

        // 起始时间
        $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('Y-m-d',strtotime($date[0])), date('Y-m-d',strtotime($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/Jujiao', '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/Jujiao', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $shop_code = $post['brandclass_id'] ? $post['brandclass_id'] : 0;

        if ($shop_code) {
            $data['add_shop_code'] = $shop_code;
        }else{
            $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
            $shopCodes = '';
            foreach ($shopList as $key => $value) {
                $shopCodes .= $value['shop_code'].',';
            }
            $shopCodes = trim($shopCodes, ',');
            $data['add_shop_code'] = $shopCodes;
        }
        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange(date('Y-m-d',strtotime($date[0])), date('Y-m-d',strtotime($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/Jujiao', '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 monthCusOrderRateNumber(){
        // echo '开始 ==> '.microtime(true).'<br />';
        $auth = controller('crm/Jujiao', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $shop_code = $post['brandclass_id'] ? $post['brandclass_id'] : 0;
        if ($shop_code) {
            // 新单条件
            $dataInto['add_shop_code'] = $shop_code;
            // 有效条件
            $dataInv['add_shop_code'] = $shop_code;
        }else{
            $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
            $shopCodes = '';
            foreach ($shopList as $key => $value) {
                $shopCodes .= $value['shop_code'].',';
            }
            $shopCodes = trim($shopCodes, ',');

            // 新单条件
            $dataInto['add_shop_code'] = $shopCodes;
            // 有效条件
            $dataInv['add_shop_code'] = $shopCodes;
        }
        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange(date('Y-m-d',strtotime($date[0])), date('Y-m-d',strtotime($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/Jujiao', 'lib')->getOrderNumberNum($dataInto);
            // echo $intoNum.'<br />';
            $allInto += $intoNum;
            // 有效
            // echo '循环'.$key.'有效 ==> '.microtime(true).'<br />';
            $invNum = controller('crm/Jujiao', 'lib')->getCustomerNum($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);
        $allRate = $allRate>100 ? 100 : $allRate;
        // var_dump($allRate);
        // exit;
        // 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);
    }

    // 本月转化率 （ 新单 / 有效获取 ） 走势 图
    public function monthOrderRateNumber(){
        // echo '开始 ==> '.microtime(true).'<br />';
        $auth = controller('crm/Jujiao', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            // controller('crm/Index','controller')->index();
            exit;
        }
        $post = input('post.');
        $shop_code = $post['brandclass_id'] ? $post['brandclass_id'] : 0;
        if ($shop_code) {
            // 新单条件
            $dataInto['add_shop_code'] = $shop_code;
            // 有效条件
            $dataInv['add_shop_code'] = $shop_code;
        }else{
            $shopList = controller('crm/Jujiao', 'lib')->getShops(session('brandclass_id'));
            $shopCodes = '';
            foreach ($shopList as $key => $value) {
                $shopCodes .= $value['shop_code'].',';
            }
            $shopCodes = trim($shopCodes, ',');

            // 新单条件
            $dataInto['add_shop_code'] = $shopCodes;
            // 有效条件
            $dataInv['add_shop_code'] = $shopCodes;
        }
        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange(date('Y-m-d',strtotime($date[0])), date('Y-m-d',strtotime($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/Jujiao', 'lib')->getOrderNumberNum($dataInto);
            // echo $intoNum.'<br />';
            $allInto += $intoNum;
            // 有效
            // echo '循环'.$key.'有效 ==> '.microtime(true).'<br />';
            $invNum = controller('crm/Jujiao', '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);
        $allRate = $allRate>100 ? 100 : $allRate;
        // var_dump($allRate);
        // exit;
        // 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);
    }
    //店面下小组人员信息统计
    public function dayGroupStaffData(){
        $shop_code = input('param.shop_code');
        $arr = [];
        if ($shop_code == 'JJ001') {
            $group1 = $this->groupData($shop_code,1);
            $group2 = $this->groupData($shop_code,2);
            $group3 = $this->groupData($shop_code,3);
            $group6 = $this->groupData($shop_code,6);
            $returnData[0]['title'] = array_shift($group1);
            $returnData[0]['data']  = $group1;
            $returnData[1]['title'] = array_shift($group2);
            $returnData[1]['data']  = $group2;
            $returnData[2]['title'] = array_shift($group3);
            $returnData[2]['data']  = $group3;
            $returnData[3]['title'] = array_shift($group6);
            $returnData[3]['data']  = $group6;
            unset($group1,$group2,$group3,$group6);
            return json($returnData);
        }else if ($shop_code == 'JJET003') {
            $returnData = [];
            $groupIds = db('c_staff_group')->where('shop_code', $shop_code)->field('id')->select();
            foreach ($groupIds as $key => $value) {
                $temp = [];
                $groupData = $this->groupData($shop_code,$value['id']);
                $temp['title'] = array_shift($groupData);
                $temp['data']  = $groupData;
                array_push($returnData, $temp);
            }
            unset($groupData,$temp);
            return json($returnData);
        }
        
    }
    //店面下小组人员信息统计
    public function groupData($shop_code = 'JJ001',$gid = 1){
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        //小组名和人员
        $info = db('c_staff_group')->alias('a')->join('c_staff_group_relation b','a.id=b.group_id')->where('b.group_id',$gid)->column('a.group_name,b.group_id,b.staff_name','b.staff_id');
        $group_name = db('c_staff_group')->where('id',$gid)->value('group_name');
        $staffIds = array_column($info,'staff_id');
        //接入客资
        $jr = db('c_customerinfo force index(jr_day)')
            ->where('shop_code',$shop_code)
            ->where('is_status',1)
            // ->where('c_from',1)
            ->where('sales_staff_id','in',$staffIds)
            ->where('jr_day','between',[$start,$end])
            ->order('num desc')
            ->group('sales_staff_id')
            ->column('count(id) num','sales_staff_id');
        $t_jr = array_sum($jr);
        //有效客资
        $valid = db('c_customerinfo force index(dj)')
            ->where('shop_code',$shop_code)
            ->where('is_status',1)
            // ->where('c_from',1)
            ->where('is_valid',1)
            ->where('sales_staff_id','in',$staffIds)
            ->where('dj_day','between',[$start,$end])
            ->order('num desc')
            ->group('sales_staff_id')
            ->column('count(id) num','sales_staff_id');
        $t_valid = array_sum($valid);

        //订单
        // $order = db('c_customerinfo force index(order_day)')
        //     ->where('shop_code',$shop_code)
        //     ->where('is_status',1)
        //     ->where('is_success',1)
        //     // ->where('c_from',1)
        //     ->where('sales_staff_id','in',$staffIds)
        //     ->where('order_day','between',[$start,$end])
        //     ->order('num desc')
        //     ->group('sales_staff_id')
        //     ->column('count(id) num','sales_staff_id');
        $order = 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.shop_code', $shop_code)
            ->where('o.create_time', 'between time', [$start,$end])
            ->where('c.sales_staff_id', 'in', $staffIds)
            ->group('c.sales_staff_id')
            ->column('count(*) as num', 'c.sales_staff_id');

        $t_order = array_sum($order);
        $t_rate = $t_order ? sprintf('%.2f',$t_order/$t_jr*100).'%' : '0%';
        $return = [$group_name.'/'.$t_jr.'/'.$t_valid.'/'.$t_rate];
        $temp = [];
        foreach($info as $k=>$v){
            $arr['staff_name'] = $v['staff_name'];
            $arr['jr'] = $jr[$v['staff_id']] ? $jr[$v['staff_id']] : 0;
            $arr['valid'] = $valid[$v['staff_id']] ? $valid[$v['staff_id']] : 0;
            $arr['rate'] = $order[$v['staff_id']] ? sprintf('%.2f',$order[$v['staff_id']]/$jr[$v['staff_id']]*100).'%': '0%';
            array_push($temp,$arr);
        }
        $sort = 'SORT_DESC';
        $temp = my_sort($temp,'jr',$sort);
        $temp = array_slice($temp,0,3);
        $return = array_merge($return,$temp);
        return $return;
    }
}