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

    // 电商 一、二、三 部 部门id
    protected $ds_ids = '1,2,3,24';
    // 网销 一、二、三 部 部门id
    protected $wx_ids = '4,5,6,25';

    // 27°罗马风情电商shop_code
    protected $ds_shop_code = 'LM007';
    // 27°罗马风情网销shop_code
    protected $wx_shop_code = 'LM008';

    // 所有电商shop_code
    protected $ds_shop_codes = [
        '0' => [
            'shop_code' => 'LM007',
            'shop_name' => '电商中心',
            'base_name' => '27°罗马风情',
        ],
        '1' => [
            'shop_code' => 'LM009',
            'shop_name' => '旅拍电商中心',
            'base_name' => '27°环球旅拍',
        ],
        '2' => [
            'shop_code' => 'LM011',
            'shop_name' => '名匠电商中心',
            'base_name' => '27°名匠汇',
        ],
        '3' => [
            'shop_code' => 'LM013',
            'shop_name' => '依纱电商中心',
            'base_name' => '27°依莎嫁衣',
        ],
    ];

    // 所有网销shop_code
    protected $wx_shop_codes = [
        '0' => [
            'shop_code' => 'LM008',
            'shop_name' => '网销中心',
            'base_name' => '27°罗马风情',
        ],
        '1' => [
            'shop_code' => 'LM010',
            'shop_name' => '旅拍网销中心',
            'base_name' => '27°环球旅拍',
        ],
        '2' => [
            'shop_code' => 'LM012',
            'shop_name' => '名匠网销中心',
            'base_name' => '27°名匠汇',
        ],
        '3' => [
            'shop_code' => 'LM014',
            'shop_name' => '依纱网销中心',
            'base_name' => '27°依莎嫁衣',
        ],
    ];

    // 大屏页面  2018-07-26
    public function index(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        
        $this->assign('title','罗马风情 【电商战报大屏】');
        return $this->fetch();
    }

    // 移动端大屏
    public function mobile(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

        $this->assign('title','罗马风情 【电商战报大屏】');
        return $this->fetch();
    }

    // --------第一部分 四个目标进度
    public function getTarget(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

        // $shop_info = controller('crm/Rome', 'lib')->getShopByType('wx');
        $wx = '';
        foreach ($this->wx_shop_codes as $key => $value) {
            $wx .= $value['shop_code'].',';
        }
        $wx = trim($wx, ',');

        $this_month = date('Y-m');
        // 获取网销店下所有的部门目标设定
        $target = db('s_kpi_staffgoal')
            ->where('kpi_id', 'orderNumber')
            ->where('shop_code', 'in',$wx)
            // ->where('flag', 'null')
            //->where('department_id', '<>', 0)
            ->where('position_id', 0)
            ->where('month', $this_month)
            ->group('shop_code')
            ->column('sum(kpi_value) as count, shop_name, shop_code','shop_code');

        $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]));
        
        $alread = db('c_customerinfo')
            ->where('is_status', 1)
            ->where('c_from', 1)
            ->where('shop_code', 'in',$wx)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$month_start, $month_end])
            ->group('shop_code')
            ->column('count(*) as num','shop_code');
        // echo db()->getLastSql();
        // var_dump($alread);exit;

        $result = [];
        if (!$target) {
            $result['lm_target'] = 0;
            $result['lm_alread'] = 0;
        }else{
            foreach ($target as $key => $value) {
                $shop_code = $value['shop_code'];
                if ($shop_code == 'LM008') {
                    $result['lm_target'] = $value['count'] ? $value['count'] : 0;
                    $result['lm_alread'] = $alread[$shop_code] ? $alread[$shop_code] : 0;
                }else if ($shop_code == 'LM010') {
                    $result['lp_target'] = $value['count'] ? $value['count'] : 0;
                    $result['lp_alread'] = $alread[$shop_code] ? $alread[$shop_code] : 0;
                }else if ($shop_code == 'LM012') {
                    $result['mj_target'] = $value['count'] ? $value['count'] : 0;
                    $result['mj_alread'] = $alread[$shop_code] ? $alread[$shop_code] : 0;
                }else if ($shop_code == 'LM014') {
                    $result['ys_target'] = $value['count'] ? $value['count'] : 0;
                    $result['ys_alread'] = $alread[$shop_code] ? $alread[$shop_code] : 0;
                }
            }
        }
        
        return json($result);
    }

    // --------第二部分 1  页面实时数据
    public function baseData(){
        // echo 'START==>'.microtime(true).'<br />';
        // 权限
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }

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

        //本月
        $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');

        /* -------- 电商相关 -------- */
        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->ds_shop_code);
        $ds_d_ids = '';
        foreach ($departments as $key => $value) {
            $ds_d_ids .= $value['id'].',';
        }
        $ds_d_ids = trim($ds_d_ids, ',');
        $tData['ids']       = $ds_d_ids;
        $tData['shop_code'] = $this->ds_shop_code;
        $mData['ids']       = $ds_d_ids;
        $mData['shop_code'] = $this->ds_shop_code;

        //总获取（毛客资） getCustomerNum
        $allCusT = controller('crm/Rome', 'lib')->getCustomerNum($tData);
        $allCusM = controller('crm/Rome', 'lib')->getCustomerNum($mData);
        $allCus  = $allCusT.' / '.$allCusM;
        $returnData['allCus'] = $allCus;

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

        // 有效客资
        $validCustomerT = controller('crm/Rome', 'lib')->getInvCustomerNum($tData);
        $validCustomerM = controller('crm/Rome', 'lib')->getInvCustomerNum($mData);
        $validCustomer  = $validCustomerT.' / '.$validCustomerM;
        $returnData['validCustomer'] = $validCustomer;

        // 获取成本
        $validObtail = round($costMoneyT/$validCustomerT).' / '.round($costMoneyM/$validCustomerM);
        $returnData['validObtail'] = $validObtail;

        /* -------- 网销相关 -------- */
        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->wx_shop_code);
        $wx_d_ids = '';
        foreach ($departments as $key => $value) {
            $wx_d_ids .= $value['id'].',';
        }
        $wx_d_ids = trim($ds_d_ids, ',');
        $tData['ids']       = $wx_d_ids;
        $tData['shop_code'] = $this->wx_shop_code;
        $mData['ids']       = $wx_d_ids;
        $mData['shop_code'] = $this->wx_shop_code;

        // 网络营收
        $moneyT = controller('crm/Rome', 'lib')->incomeMoney($tData);
        $moneyM = controller('crm/Rome', 'lib')->incomeMoney($mData);
        $money = $moneyT.' / '.$moneyM;
        $returnData['money'] = $money;

        // 网络进客
        $intoCustomerT = controller('crm/Rome', 'lib')->getIntoCustomerNum($tData);
        $intoCustomerM = controller('crm/Rome', 'lib')->getIntoCustomerNum($mData);
        $intoCustomer = $intoCustomerT.'/'.$intoCustomerM;
        $returnData['intoCustomer'] = $intoCustomer;

        // 网络新单
        $orderCustomerT = controller('crm/Rome', 'lib')->getOrderNumberNum($tData);
        $orderCustomerM = controller('crm/Rome', 'lib')->getOrderNumberNum($mData);
        $orderCustomer = $orderCustomerT.'/'.$orderCustomerM;
        $returnData['orderCustomer'] = $orderCustomer;
            
        // 成交率
        $succRate = number_format($orderCustomerT/$validCustomerT,2).'%'.' / '.number_format($orderCustomerM/$validCustomerM,2).'%';
        $returnData['succRate'] = $succRate;

        // 日转化率  订单数量 / 毛客资
        $dayChangeRate = ($orderCustomerT / $allCusT)*100;
        $dayChangeRate = number_format($dayChangeRate, 2).'%';
        $returnData['dayChangeRate'] = $dayChangeRate;

        // 月转化率  订单数量 / 毛客资
        $monthChangeRate = ($orderCustomerM / $allCusM)*100;
        $monthChangeRate = number_format($monthChangeRate, 2).'%';
        $returnData['monthChangeRate'] = $monthChangeRate;

        return json($returnData);
    }
    // 第二部分 2  两个排名
    public function rankData(){
        $auth = controller('crm/Rome', '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());
        // 月 开始 结束时间
        $month_start= date('Y-m-01 00:00:00',time());
        $month_end  = date('Y-m-d 00:00:00', time());

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;

        $day = date('Ymd');

        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->ds_shop_code);
        $dsBaseDepartment = [];
        foreach ($departments as $key => $value) {
            if ( strpos($this->ds_ids, strval($value['id'])) !== false ) {
                $dsBaseDepartment[$key]['dj_department_id'] = $value['id'];
                $dsBaseDepartment[$key]['department_name']  = $value['department_name'];
                $dsBaseDepartment[$key]['dayNum']           = 0;
                $dsBaseDepartment[$key]['monthNum']         = 0;
            }
        }
        
        /* -----------------------------------------------------  毛客资排名开始  ----------------------------------------------------- */

        // 当日毛客资数
        $customerNumDay = db('c_customerinfo')
            ->where($where)
            ->where('dj_department_id', 'in', $this->ds_ids)
            ->where('dj_day', 'between time', [$today_start, $today_end])
            ->group('dj_department_id')
            ->field('dj_department_id, null as department_name, count(*) as dayNum, 0 as monthNum')
            ->select();

        // 当月毛客资数
        $customerNumMonth = json_decode( cache('rankData_cnum_'.$day) );

        if (!$customerNumMonth) {
            $customerNumMonth = db('c_customerinfo')
                ->where($where)
                ->where('dj_department_id', 'in', $this->ds_ids)
                ->where('dj_day', 'between time', [$month_start, $month_end])
                ->group('dj_department_id')
                ->field('dj_department_id, null as department_name, 0 as dayNum, count(*) as monthNum')
                ->select();
            cache('rankData_cnum_'.$day, json_encode($customerNumMonth), 3600);
        }
        $temp = array_merge($customerNumDay, $customerNumMonth, $dsBaseDepartment);
        $customerNum = [];
        foreach ($temp as $key => $value) {
            // var_dump($value);
            $customerNum[$value['dj_department_id']]['id']       = $value['dj_department_id'];
            $customerNum[$value['dj_department_id']]['name']     = $value['department_name'];
            $customerNum[$value['dj_department_id']]['dayNum']  += $value['dayNum'];
            $customerNum[$value['dj_department_id']]['monthNum']+= $value['monthNum'] + $value['dayNum'];
        }
        // var_dump($customerNum);exit;
        $sort_order = 'SORT_DESC';
        $customerNum = my_sort($customerNum, 'dayNum', $sort_order);
        unset($temp);
        unset($customerNumDay);
        unset($customerNumMonth);
        /* -----------------------------------------------------  毛客资排名结束  ----------------------------------------------------- */

        /* -----------------------------------------------------  新单排名开始  ----------------------------------------------------- */
        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->wx_shop_code);
        $wxBaseDepartment = [];
        foreach ($departments as $key => $value) {
            $wxBaseDepartment[$key]['sales_department_id'] = $value['id'];
            $wxBaseDepartment[$key]['department_name']     = $value['department_name'];
            $wxBaseDepartment[$key]['dayNum']              = 0;
            $wxBaseDepartment[$key]['monthNum']            = 0;
        }
        // 当日订单数
        $orderNumDay = db('c_customerinfo')
            ->where($where)
            ->where('sales_department_id', 'in', $this->wx_ids)
            ->where('order_day', 'between time', [$today_start, $today_end])
            ->group('sales_department_id')
            ->field('sales_department_id, null as department_name, count(*) as dayNum, 0 as monthNum')
            ->select();

        // 当月订单数
        $orderNumMonth = json_decode( cache('rankData_onum_'.$day) );
        if (!$orderNumMonth) {
            $orderNumMonth = db('c_customerinfo')
                ->where($where)
                ->where('sales_department_id', 'in', $this->ds_ids)
                ->where('order_day', 'between time', [$month_start, $month_end])
                ->group('sales_department_id')
                ->field('sales_department_id, null as department_name, 0 as dayNum, count(*) as monthNum')
                ->select();
            cache('rankData_onum_'.$day, json_encode($orderNumMonth));
        }
        $temp = array_merge($orderNumDay, $orderNumMonth, $wxBaseDepartment);
        $orderNum = [];
        foreach ($temp as $key => $value) {
            $orderNum[$value['sales_department_id']]['id']       = $value['sales_department_id'];
            $orderNum[$value['sales_department_id']]['name']     = $value['department_name'];
            $orderNum[$value['sales_department_id']]['dayNum']  += $value['dayNum'];
            $orderNum[$value['sales_department_id']]['monthNum']+= $value['monthNum'] + $value['dayNum'];
        }

        $sort_order = 'SORT_DESC';
        $orderNum = my_sort($orderNum, 'dayNum', $sort_order);
        unset($temp);
        unset($orderNumDay);
        unset($orderNumMonth);
        /* -------------------------------------------------------  新单排名结束 ------------------------------------------------------- */

        unset($department);
        $returnData = [
            'customerNum'=> $customerNum,
            'orderNum'   => $orderNum,
        ];
        return json($returnData);
    }
    // 第二部分 3  渠道分布柱状图 
    public function channelCustomer(){
        $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());
        $where = [
            'is_status'=> 1,
            'c_from'   => 1,
            'customer_type'=>1,
        ];
        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->ds_shop_code);
        $ds_ids = '';
        foreach ($departments as $key => $value) {
            $ds_ids .= $value['id'].',';
        }
        $ds_ids = trim($ds_ids, ',');

        $cInfo = db('c_customerinfo')
            ->where($where)
            ->where('dj_day', 'between time', [$today_start, $today_end])
            ->where('dj_department_id', 'in', $ds_ids)
            ->group('customer_channel')
            ->column('count(*) as num ,customer_channel', 'customer_channel_id');
        // echo db()->getLastSql();
        // var_dump($cInfo);
        // exit;
        // 获取所有电商渠道
        // $channels = db('s_channel')->where('shop_code',$this->ds_shop_code)->field('id,channel_name')->select();
        $channels = db('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->field('id,channel_name')->select();
        // var_dump($channels);exit;
        foreach ($channels as $key => $value) {
            $returnData['names'][] = $value['channel_name'];
            if ($cInfo[$value['id']]['num']) {
                $returnData['datas'][] = $cInfo[$value['id']]['num'];
            }else{
                $returnData['datas'][] = 0;
            }
        }

        return json($returnData);
    }
    // 第二部分 4  时段数据（客资数） 
    public function timeCustomer(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        // data: ['0/12点','12/16点','16/20点','20/24点'],
        $date = date('Y-m-d H:i:s');
        $hour = date('H');
        if ($hour<12) {
            $time[0] = [
                'start' => date('Y-m-d 00:00:00'),
                'end'   => date('Y-m-d 12:00:00'),
            ];
        }else if ($hour<16) {
            $time[0] = [
                'start' => date('Y-m-d 00:00:00'),
                'end'   => date('Y-m-d 12:00:00'),
            ];
            $time[1] = [
                'start' => date('Y-m-d 12:00:01'),
                'end'   => date('Y-m-d 16:00:00'),
            ];
        }else if ($hour<20) {
            $time[0] = [
                'start' => date('Y-m-d 00:00:00'),
                'end'   => date('Y-m-d 12:00:00'),
            ];
            $time[1] = [
                'start' => date('Y-m-d 12:00:01'),
                'end'   => date('Y-m-d 16:00:00'),
            ];
            $time[2] = [
                'start' => date('Y-m-d 16:00:01'),
                'end'   => date('Y-m-d 20:00:00'),
            ];
        }else{
            $time[0] = [
                'start' => date('Y-m-d 00:00:00'),
                'end'   => date('Y-m-d 12:00:00'),
            ];
            $time[1] = [
                'start' => date('Y-m-d 12:00:01'),
                'end'   => date('Y-m-d 16:00:00'),
            ];
            $time[2] = [
                'start' => date('Y-m-d 16:00:01'),
                'end'   => date('Y-m-d 20:00:00'),
            ];
            $time[3] = [
                'start' => date('Y-m-d 20:00:01'),
                'end'   => date('Y-m-d 23:59:59'),
            ];
        }
        
        $where = [
            'is_status'=> 1,
            'c_from'   => 1,
            'customer_type'=>1,
        ];

        $departments = controller('crm/Rome', 'lib')->getdeparments($this->ds_shop_code);
        $ds_ids = '';
        foreach ($departments as $key => $value) {
            $ds_ids .= $value['id'].',';
        }
        $ds_ids = trim($ds_ids, ',');

        $returnData = [];
        foreach ($time as $key => $value) {
            $cNum = db('c_customerinfo')
                ->where($where)
                ->where('dj_day', 'between time', [$value['start'], $value['end']])
                ->where('dj_department_id', 'in', $ds_ids)
                ->count('*');
            // echo db()->getLastSql();
            $returnData['datas'][] = $cNum;
        }

        // var_dump($returnData);exit;
        return json($returnData);
    }

    // --------第三部分 1 本月毛客资量走势 图
    public function monthCustomerNumber(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;

        $departments = controller('crm/Rome', 'lib')->getdeparments($this->ds_shop_code);
        $ds_ids = '';
        foreach ($departments as $key => $value) {
            $ds_ids .= $value['id'].',';
        }
        $ds_ids = trim($ds_ids, ',');

        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);
        // 查一下缓存
        $day = date('Ymd');
        $monthCustomerNumber = json_decode( cache('monthCustomerNumber_'.$day) );
        if (!$monthCustomerNumber) {
            $today = date('Y-m-d');
            foreach ($timezone as $key => $value) {
                if ($value == $today) {
                    break;
                }
                $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
                $data['end']   = date('Y-m-d 23:59:59', strtotime($value));
                $customerNum = db('c_customerinfo')
                    ->where($where)
                    ->where('dj_department_id', 'in', $ds_ids)
                    ->where('dj_day', 'between time', [$data['start'], $data['end']])
                    ->count();
                $monthCustomerNumber[$key] = $customerNum;
            }
            // 将除了今天之外的 本月数量缓存一下
            cache('monthCustomerNumber_'.$day, json_encode($monthCustomerNumber));
        }
        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // 今天的数量
        $customerNum = db('c_customerinfo')
            ->where($where)
            ->where('dj_department_id', 'in', $ds_ids)
            ->where('dj_day', 'between time', [$today_start, $today_end])
            ->count();
        array_push($monthCustomerNumber, $customerNum);
        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'毛客资量',
                'data' =>$monthCustomerNumber,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('毛客资量');
        $returnData['data'] = $arr;
        return json($returnData);
    }
    // 第三部分 2 本月网销邀约 （进店） 量走势 图
    public function monthIntoNumber(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->wx_shop_code);
        $wx_d_ids = '';
        foreach ($departments as $key => $value) {
            $wx_d_ids .= $value['id'].',';
        }
        $wx_d_ids = trim($wx_d_ids, ',');

        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);
        // 查缓存
        $day = date('Ymd');
        $monthIntoNumber = json_decode( cache('monthIntoNumber_'.$day) );
        if (!$monthIntoNumber) {
            $today = date('Y-m-d');
            foreach ($timezone as $key => $value) {
                if ($value == $today) {
                    break;
                }
                $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
                $data['end']   = date('Y-m-d 23:59:59', strtotime($value));
                
                // 实际进店 （进店进客）
                $inv = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('sales_department_id', 'in', $wx_d_ids)
                    ->where('syjd_day', 'between time', [$data['start'], $data['end']])
                    ->count();
                $monthIntoNumber[$key] = $inv;
            }
            // 将除了今天之外的 本月数量缓存一下
            cache('monthIntoNumber_'.$day, json_encode($monthIntoNumber));
        }
        
        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // 今天的数量
        $inv = db('c_customerinfo')
            ->where($where)
            ->where('is_intostore', 2)
            ->where('sales_department_id', 'in', $wx_d_ids)
            ->where('syjd_day', 'between time', [$today_start, $today_end])
            ->count();
        array_push($monthIntoNumber, $inv);

        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'邀约量',
                'data' =>$monthIntoNumber,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('邀约量');
        $returnData['data'] = $arr;
        return json($returnData);
    }
    // 第三部分 3 本月网络新单量走势 图
    public function monthNewOrderNumber(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;

        $wx_d_ids = '';
        foreach ($departments as $key => $value) {
            $wx_d_ids .= $value['id'].',';
        }
        $wx_d_ids = trim($wx_d_ids, ',');

        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);
        // 查缓存
        $day = date('Ymd');
        $monthNewOrderNumber = json_decode( cache('monthNewOrderNumber_'.$day) );
        if (!$monthNewOrderNumber) {
            $today = date('Y-m-d');
            foreach ($timezone as $key => $value) {
                if ($value == $today) {
                    break;
                }
                $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
                $data['end']   = date('Y-m-d 23:59:59', strtotime($value));

                $num = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 1)
                    ->where('sales_department_id', 'in', $wx_d_ids)
                    ->where('order_day', 'between time', [$data['start'], $data['end']])
                    ->count();
                $monthNewOrderNumber[$key] = $num;
            }
            // 将除了今天之外的 本月数量缓存一下
            cache('monthNewOrderNumber_'.$day, json_encode($monthNewOrderNumber));
        }
        
        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // 今天的数量
        $num = db('c_customerinfo')
            ->where($where)
            ->where('is_success', 1)
            ->where('sales_department_id', 'in', $wx_d_ids)
            ->where('order_day', 'between time', [$today_start, $today_end])
            ->count();
        array_push($monthNewOrderNumber, $num);


        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));
            
            $num = db('c_customerinfo')
                ->where($where)
                ->where('shop_code', 'in', $data['shop_code'])
                ->where('order_day', 'between time', [$data['start'], $data['end']])
                ->count();
            $number[$key] = $num;
            if ($value == $today) {
                break;
            }
        }
        $zone = [];
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }
        $arr = [
            0=>[
                'name'=>'新单量',
                'data' =>$monthNewOrderNumber,
            ],
        ];

        $returnData['timezone'] = $zone;
        $returnData['name'] = array('新单量');
        $returnData['data'] = $arr;
        return json($returnData);
    }
    // 第三部分 4 本月转化率 （ 新单 / 有效获取 ） 走势 图
    public function monthOrderRateNumber(){
        $auth = controller('crm/Rome', 'lib')->checkBigScreenAuth();
        if ($auth === false) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;

        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->wx_shop_code);
        $wx_d_ids = '';
        foreach ($departments as $key => $value) {
            $wx_d_ids .= $value['id'].',';
        }
        $wx_d_ids = trim($wx_d_ids, ',');

        // 起始时间
        $date = getdateArea('this_month');
        $timezone = getDateFromRange($date[0], $date[1]);

        $zone   = [];
        $number = [];
        $allInto= 0;
        $allInv = 0;
        $today = date('Y-m-d');

        // 查缓存
        $day = date('Ymd');
        // 新单缓存
        $monthNewOrderNumber = json_decode( cache('monthNewOrderNumber_'.$day) );
        if (!$monthNewOrderNumber) {
            $today = date('Y-m-d');
            foreach ($timezone as $key => $value) {
                if ($value == $today) {
                    break;
                }
                $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
                $data['end']   = date('Y-m-d 23:59:59', strtotime($value));

                $num = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 1)
                    ->where('sales_department_id', 'in', $wx_d_ids)
                    ->where('order_day', 'between time', [$data['start'], $data['end']])
                    ->count();
                $monthNewOrderNumber[$key] = $num;
            }
            // 将除了今天之外的 本月数量缓存一下
            cache('monthNewOrderNumber_'.$day, json_encode($monthNewOrderNumber));
        }

        // 有效客资缓存
        $monthVaildNumber = json_decode( cache('monthVaildNumber_'.$day) );
        if (!$monthVaildNumber) {
            $today = date('Y-m-d');
            foreach ($timezone as $key => $value) {
                if ($value == $today) {
                    break;
                }
                $data['start'] = date('Y-m-d 00:00:00', strtotime($value));
                $data['end']   = date('Y-m-d 23:59:59', strtotime($value));

                $num = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 1)
                    ->where('sales_department_id', 'in', $wx_d_ids)
                    ->where('yx_day', 'between time', [$data['start'], $data['end']])
                    ->count();
                $monthVaildNumber[$key] = $num;
            }
            // 将除了今天之外的 本月数量缓存一下
            cache('monthVaildNumber_'.$day, json_encode($monthVaildNumber), 3600);
        }

        $monthOrderRateNumber = [];
        foreach ($timezone as $key => $value) {
            if ($value == $today) {
                break;
            }
            $monthOrderRateNumber[$key] = number_format( ($monthNewOrderNumber[$key] / $monthVaildNumber[$key])*100, 2 );
        }

        // 日 开始结束时间
        $today_start = date('Y-m-d 00:00:00', time());
        $today_end   = date('Y-m-d 23:59:59', time());
        // 今天的数量
        $order_num = db('c_customerinfo')
            ->where($where)
            ->where('is_success', 1)
            ->where('sales_department_id', 'in', $wx_d_ids)
            ->where('order_day', 'between time', [$today_start, $today_end])
            ->count();

        $valid_num = $num = db('c_customerinfo')
            ->where($where)
            ->where('is_valid', 1)
            ->where('sales_department_id', 'in', $wx_d_ids)
            ->where('yx_day', 'between time', [$today_start, $today_end])
            ->count();
        $num = number_format( ($order_num / $valid_num)*100, 2 );

        array_push($monthOrderRateNumber, $num);

        foreach ($timezone as $key => $value) {
            $zone[$key] = date('d', strtotime($value));
        }

        $arr = [
            0=>[
                'name'=>'日转化率',
                'data' =>$monthOrderRateNumber,
            ],
        ];
        
        $returnData['timezone'] = $zone;
        $returnData['name'] = array('转化率');
        $returnData['data'] = $arr;
        return json($returnData);
    }
    // 第三部分 5 转化漏斗 （日） 图
    public function dayChangeRate(){
        $auth = controller('crm/Rome', '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());

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

        return json($returnData);
    }
    // 第三部分 6 转化漏斗 （月） 图
    public function monthChangeRate(){
        $auth = controller('crm/Rome', '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]));

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

        return json($returnData);
    }
    // 转化漏斗数据 
    public function getChangeLdData($data){
        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->ds_shop_code);
        $ds_d_ids = '';
        foreach ($departments as $key => $value) {
            $ds_d_ids .= $value['id'].',';
        }
        $ds_d_ids = trim($ds_d_ids, ',');
        $data['ids'] = $ds_d_ids;
        // 毛客资
        $customerNum = controller('crm/Rome', 'lib')->getCustomerNum($data);
        $returnData[0]['name'] = '毛客资量';
        $returnData[0]['data'] = $customerNum;
        // 有效客资
        $invCustomer = controller('crm/Rome', 'lib')->getInvCustomerNum($data);

        // exit;
        $returnData[1]['name'] = '有效客资';
        $returnData[1]['data'] = $invCustomer;

        // 根据shop_code 找部门
        $departments = controller('crm/Rome', 'lib')->getdeparments($this->wx_shop_code);
        $wx_d_ids = '';
        foreach ($departments as $key => $value) {
            $wx_d_ids .= $value['id'].',';
        }
        $wx_d_ids = trim($wx_d_ids, ',');

        $data['ids'] = $wx_d_ids;
        // 进店/邀约 量
        $intoCustomer= controller('crm/Rome', 'lib')->getIntoCustomerNum($data);
        $returnData[2]['name'] = '进店';
        $returnData[2]['data'] = $intoCustomer;
        // 新单 量
        $orderNumber = controller('crm/Rome', 'lib')->getOrderNumberNum($data);
        $returnData[3]['name'] = '订单';
        $returnData[3]['data'] = $orderNumber;
        return $returnData;
    }
    /***********************************罗马员工大屏****        start       **********************************/
    public function staff(){
        return $this->fetch();
    }
    //客资完成率  周
    public function cusCompleteWeek(){
        $week = getdateArea('week');
        $start = date('Y-m',strtotime($week[0]));
        $end = date('Y-m',strtotime($week[1]));
        //毛客资目标
        if($start == $end) {
            $kpi = db('s_kpi_staffgoal')
                ->where('month', date('Y-m'))
                ->where('kpi_id', 'validCustomerNumber')
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->where('shop_code', $this->ds_shop_code)
                ->group('department_id')
                ->limit(4)
                ->column('kpi_id,kpi_value,avg_value,department_name,department_id', 'department_id');
        }else{
            //本月占多少天
            //下月第一天
            $next_month_first_day = date('Y-m-01 00:00:00',strtotime($week[1]));
            //本月最后一天
            $last_month_day = date('Y-m-d',strtotime($next_month_first_day)-1);
            //本周在本月天数
            $this_week_last_day = date('Ymd',strtotime($last_month_day));
            $this_week_first_day = date('Ymd',strtotime($week[0]));
            $this_week = $this_week_last_day-$this_week_first_day+1;

            //下月占多少天
            //本周在下月天数
            $first_day = date('Ymd',strtotime($next_month_first_day));
            $last_day = date('Ymd',strtotime($week[1]));

            $last_week = $last_day-$first_day+1;
            $kpi = db('s_kpi_staffgoal')
                ->where('month', date('Y-m'))
                ->where('kpi_id', 'validCustomerNumber')
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->where('shop_code', $this->ds_shop_code)
                ->group('department_id')
                ->limit(4)
                ->column('kpi_id,kpi_value,avg_value,department_name,department_id', 'department_id');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month', $end)
                ->where('kpi_id', 'validCustomerNumber')
                ->where('group_id', 0)
                ->where('position_id', 0)
                ->where('staff_id', 0)
                ->where('shop_code', $this->ds_shop_code)
                ->group('department_id')
                ->limit(4)
                ->column('kpi_id,kpi_value,avg_value,department_name,department_id', 'department_id');
        }
        $mkz = db('c_customerinfo')
            ->where('c_from',1)
            ->where('is_valid',1)
            ->where('is_status',1)
            ->where('dj_department_id','>',0)
            ->where('add_shop_code',$this->ds_shop_code)
            ->where('yx_day','between',[$week[0],$week[1]])
            ->group('dj_department_id')
            ->order('num desc')
            ->limit(4)
            ->column('count(id) as num','dj_department_id');
        $department = controller('crm/Rome','lib')->getdeparments($this->ds_shop_code);
        $dep = [];
        foreach($department as $kk=>$vv){
            if($kk < 4){
                $dep[] = array_shift($department);
            }
        }
        $data = [];
        $i = 0;
        foreach($dep as $k=>$v){
            $data[$i]['index'] = $i+1;
            $data[$i]['department'] = $v['department_name'];
            if($start == $end){
                $data[$i]['kpi'] = ceil($kpi[$v['id']]['avg_value']*7);
                $data[$i]['rate'] = sprintf('%.2f',$mkz[$v['id']]/$data[$i]['kpi']*100).'%';
            }else{
                $data[$i]['kpi'] = ($kpi[$v['id']]['avg_value']*$this_week)+($kpi_next[$v['id']]['avg_value']*$last_week)>0 ? ceil(($kpi[$v['id']]['avg_value']*$this_week)+($kpi_next[$v['id']]['avg_value']*$last_week)) : 0;
                $data[$i]['rate'] = sprintf('%.2f',$mkz[$v['id']]/$data[$i]['kpi']*100).'%';
            }
            $i++;
        }
        return json($data);
    }
    //客资完成率  月
    public function cusCompleteMonth(){
        $month = getdateArea('month');
        //毛客资目标
        $kpi = db('s_kpi_staffgoal')
            ->where('month',date('Y-m'))
            ->where('kpi_id','validCustomerNumber')
            ->where('group_id',0)
            ->where('position_id',0)
            ->where('staff_id',0)
            ->where('shop_code',$this->ds_shop_code)
            ->group('department_id')
            ->limit(4)
            ->column('kpi_id,kpi_value,avg_value,department_name,department_id','department_id');
        $mkz = db('c_customerinfo')
            ->where('c_from',1)
            ->where('is_valid',1)
            ->where('is_status',1)
            ->where('dj_department_id','>',0)
            ->where('add_shop_code',$this->ds_shop_code)
            ->where('yx_day','between',[$month[0],$month[1]])
            ->group('dj_department_id')
            ->order('num desc')
            ->limit(4)
            ->column('count(id) as num','dj_department_id');

        $department = controller('crm/Rome','lib')->getdeparments($this->ds_shop_code);
        $dep = [];
        foreach($department as $kk=>$vv){
            if($kk < 4){
                $dep[] = array_shift($department);
            }
        }
        $data = [];
        $i = 0;
        foreach($dep as $k=>$v){
            $data[$i]['index'] = $i+1;
            $data[$i]['department'] = $v['department_name'];
            $data[$i]['kpi'] = $kpi[$v['id']]['kpi_value'] ? $kpi[$v['id']]['kpi_value'] : 0;
            $data[$i]['rate'] = sprintf('%.2f',$mkz[$v['id']]/$kpi[$v['id']]['kpi_value']*100).'%';
            $i++;
        }
        return json($data);
    }
    //订单完成率  周
    public function orderCompleteWeek(){
        $week = getdateArea('week');
        // $week = [
        //     '2018-07-30','2018-08-05'
        // ];
        $start = date('Y-m',strtotime($week[0]));
        $end = date('Y-m',strtotime($week[1]));
        //新单目标
        if($start == $end){
            $kpi = db('s_kpi_staffgoal')
                ->where('month',date('Y-m'))
                ->where('kpi_id','orderNumber')
                ->where('group_id',0)
                ->where('position_id',0)
                ->where('staff_id',0)
                ->where('shop_code',$this->wx_shop_code)
                ->group('department_id')
                ->limit(4)
                ->column('kpi_id,kpi_value,avg_value,department_name,department_id','department_id');
        }else{
            //本月占多少天
            //下月第一天
            $next_month_first_day = date('Y-m-01 00:00:00',strtotime($week[1]));
            //本月最后一天
            $last_month_day = date('Y-m-d',strtotime($next_month_first_day)-1);
            //本周在本月天数
            $this_week_last_day = date('Ymd',strtotime($last_month_day));
            $this_week_first_day = date('Ymd',strtotime($week[0]));
            $this_week = $this_week_last_day-$this_week_first_day+1;

            //下月占多少天
            //本周在下月天数
            $first_day = date('Ymd',strtotime($next_month_first_day));
            $last_day = date('Ymd',strtotime($week[1]));

            $last_week = $last_day-$first_day+1;

            $kpi = db('s_kpi_staffgoal')
                ->where('month',date('Y-m'))
                ->where('kpi_id','orderNumber')
                ->where('group_id',0)
                ->where('position_id',0)
                ->where('staff_id',0)
                ->where('shop_code',$this->wx_shop_code)
                ->group('department_id')
                ->limit(4)
                ->column('kpi_id,kpi_value,avg_value,department_name,department_id','department_id');
            $kpi_next = db('s_kpi_staffgoal')
                ->where('month',$end)
                ->where('kpi_id','orderNumber')
                ->where('group_id',0)
                ->where('position_id',0)
                ->where('staff_id',0)
                ->where('shop_code',$this->wx_shop_code)
                ->group('department_id')
                ->limit(4)
                ->column('kpi_id,kpi_value,avg_value,department_name,department_id','department_id');
        }
        $order = db('c_customerinfo')
            ->where('c_from',1)
            ->where('is_status',1)
            ->where('is_success',1)
            ->where('sales_department_id','>',0)
            ->where('shop_code',$this->wx_shop_code)
            ->where('order_day','between',[$week[0],$week[1]])
            ->group('sales_department_id')
            ->order('num desc')
            ->limit(4)
            ->column('count(id) as num','sales_department_id');
        $department = controller('crm/Rome','lib')->getdeparments($this->wx_shop_code);
        $dep = [];
        foreach($department as $kk=>$vv){
            if($kk < 4){
                $dep[] = array_shift($department);
            }
        }
        $data = [];
        $i = 0;
        foreach($dep as $k=>$v){
            $data[$i]['index'] = $i+1;
            $data[$i]['department'] = $v['department_name'] ? $v['department_name'] : '';
            if($start == $end){
                $data[$i]['kpi'] = $kpi[$v['id']]['avg_value'] ? ceil($kpi[$v['id']]['avg_value']*7) : 0;
                $data[$i]['rate'] = sprintf('%.2f',$order[$v['id']]/ceil($kpi[$v['id']]['avg_value']*7)*100).'%';
            }else{
                $data[$i]['kpi'] = $kpi[$v['id']]['avg_value'] ? ceil(($kpi[$v['id']]['avg_value']*$this_week)+($kpi_next[$v['id']]['avg_value']*$last_week)) : 0;
                $data[$i]['rate'] = sprintf('%.2f',$order[$v['id']]/$data[$i]['kpi']*100).'%';
            }
            $i++;
        }
        return json($data);
    }
    //订单完成率  月
    public function orderCompleteMonth(){
        $month = getdateArea('month');
        //新单目标
        $kpi = db('s_kpi_staffgoal')
            ->where('month',date('Y-m'))
            ->where('kpi_id','orderNumber')
            ->where('group_id',0)
            ->where('position_id',0)
            ->where('staff_id',0)
            ->where('shop_code',$this->wx_shop_code)
            ->group('department_id')
            ->limit(4)
            ->column('kpi_id,kpi_value,avg_value,department_name,department_id','department_id');
        $order = db('c_customerinfo')
            ->where('c_from',1)
            ->where('is_status',1)
            ->where('is_success',1)
            ->where('sales_department_id','>',0)
            ->where('shop_code',$this->wx_shop_code)
            ->where('order_day','between',[$month[0],$month[1]])
            ->group('sales_department_id')
            ->order('num desc')
            ->limit(4)
            ->column('count(id) as num','sales_department_id');
        $department = controller('crm/Rome','lib')->getdeparments($this->wx_shop_code);
        $dep = [];
        foreach($department as $kk=>$vv){
            if($kk < 4){
                $dep[] = array_shift($department);
            }
        }
        $data = [];
        $i = 0;
        foreach($dep as $k=>$v){
            $data[$i]['index'] = $i+1;
            $data[$i]['department'] = $v['department_name'] ? $v['department_name'] : '';
            $data[$i]['kpi'] = $kpi[$v['id']]['kpi_value'] ? $kpi[$v['id']]['kpi_value'] : 0;
            $data[$i]['rate'] = sprintf('%.2f',$order[$v['id']]/$kpi[$v['id']]['kpi_value']*100).'%';
            $i++;
        }
        return json($data);
    }
    //订单排名
    public function orderSort(){
        $today = getdateArea('today');
        $month = getdateArea('month');
        $sql = '';
        $sql .= 'sum(order_day between "'.$today[0].'" and "'.$today[1].'") as today_order,';
        $sql .= 'sum(order_day between "'.$month[0].'" and "'.$month[1].'") as month_order,sales_staff';
        $data = db('c_customerinfo')
            ->where('is_success',1)
            ->where('c_from',1)
            ->where('is_status',1)
            ->where('shop_code',$this->wx_shop_code)
            ->where('sales_staff_id','>',0)
            ->group('sales_staff_id')
            ->order('today_order desc,month_order desc')
            ->limit(10)
            ->column($sql,'sales_staff_id');
        foreach($data as $k=>$v){
            $data[$k]['sales_staff'] = $v['sales_staff'] ? $v['sales_staff'] : '';
        }
        return json(array_values($data));
    }
    //实收排名
    public function factSort(){
        $month = getdateArea('month');
        $monthData = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where('c.is_success',1)
            ->where('c.c_from',1)
            ->where('c.is_status',1)
            ->where('d.pay_type',1)
            ->where('c.sales_staff_id','>',0)
            ->where('c.shop_code',$this->wx_shop_code)
            ->where('d.pay_time','between',[$month[0],$month[1]])
            ->group('c.sales_staff_id')
            ->order('num desc')
            ->limit(10)
            ->column('sum(d.order_fact) as num,c.sales_staff,c.sales_staff_id','c.sales_staff_id');
        $data = [];
        $i = 1;
        foreach($monthData as $k=>$v){
            $data[$i-1]['index'] = $i;
            $data[$i-1]['sales_staff'] = $v['sales_staff'] ? $v['sales_staff'] : '';
            $data[$i-1]['fact'] = $v['num'] ? intval($v['num']) : 0;
            $i++;
        }

        return json($data);
    }
    /***********************************罗马员工大屏****      end       **********************************/
}