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

class Statistics extends Controller{
    // 根据事业部id获取事业部信息
    public function getBrandInfo($id){
        if (!$id || $id==0) {
            $mark = 'all';
        }else{
            $mark = $id;
        }
        $brandclassInfo = cache('brandclassInfo_'.$mark);
        if(empty($brandclassInfo)){
            $url = '5a38840b15ba9';
            $data['id'] = $id;
            $res = sx_call($url, $data);
            if($res['code'] == 200){
                // var_dump($res['data']);
                if ($mark == 'all') {
                    $brandclassInfo = $res['data'];
                }else{
                    $brandclassInfo = $res['data'][0];
                }
                cache('brandclassInfo_'.$mark,$brandclassInfo);
            }
        }
        return $brandclassInfo;
    }

    // 根据事业部获取  店 （电商，网销，渠道）
    public function getShops($brandclass_id){
        $url = '5a37a1503264d';
        $data['brandclass_id']= $brandclass_id;
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $shopList = $res['data'];
        }else{
            $shopList = '';
        }
        return $shopList;
    }

    // 获取所有部门信息
    public function getdeparments($shop_code = ''){
        $url = '5a0aef152b750';
        $data['shop_code'] = $shop_code;
        $res = sx_call($url, $data);
        $return = $res['data'];
        return $return;
    }

    // 根据部门id获取所有  小组  信息 0609
    public function getGroups($deparment_id){
        $where = [
            'department_id' => $deparment_id,
        ];
        $groups = db('c_staff_group')->where($where)->select();
        return $groups;
    }

    // 根据部门id获取所有  员工  信息
    public function getDepartmentStaffs($department_id){
        $url = '5a0e6f272bb38';
        $data['department_id'] = $department_id;
        $data['get_leave'] = 2;
        $res = sx_call($url, $data);
        return $res['data'];
    }
    // 根据岗位id获取所有  员工  信息
    public function getStaffInfoByPositon($position_id,$shop_code){
        $url = '5a0a624728618';
        $data['position_id']= $position_id;
        $data['shop_code']  = $shop_code;
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $return = $res['data'];
        }else{
            $return = [];
        }
        return $return;
    }

    // 根据shop_code  获取该店下所有的员工信息
    public function getStaffInfoByShop($shop_code){
        $url = '5a7424f13aa54';
        $data['shop_code']  = $shop_code;
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $return = $res['data'];
        }else{
            $return = [];
        }
        return $return;
    }
    // 根据 组id 获取所有 小组成员 信息 0609
    public function getStaffs($group_id){
        $where = [
            'group_id' => $group_id,
        ];
        $staffs = db('c_staff_group_relation')->where($where)->column('staff_id');
        $staffs = implode(',', $staffs);
        $url = '5a18e3fa516a1';
        $data['staff_id'] = $staffs;
        $res = sx_call($url, $data);

        return $res['data'];
    }

    // 根据员工  id  获取   员工名字
    public function getStaffInfo($staff_id){
        /*$url = '59f933a395abe';
        $data['staff_id']= $staff_id;
        $info = sx_call($url, $data);*/
        $data['staff_id']= $staff_id;
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->getOneStaff($data);
        $name = $info['data']['staffname'];
        return $name;
    }

    // 根据员工id，获取员工所属部门及小组 0609
    public function getDGForStaff($staff_id){
        /*$url = '59f933a395abe';
        $data['staff_id']= $staff_id;
        $info = sx_call($url, $data);*/
        $data['staff_id']= $staff_id;
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->getOneStaff($data);
        
        $res = db('c_staff_group')->where('department_id', $info['data']['department_id'])->find();
        
        $return['dname'] = $info['data']['department_name'];
        $return['gname'] = $res['group_name'];
        return $return;
    }
    // 根据shop_code 获取该店加权系数
    public function getShopWeight($shop_code){
        $weight = cache('shopWeight_'.$shop_code);
        if (!$weight) {
            $url = '5a005e0038270';
            $data['shop_code'] = $shop_code;
            $info = sx_call($url, $data);
            if ($info['code'] == 200) {
                $weight = $info['data'][0]['weight'];
                if ($weight == 0) {
                    $weight = 1;
                }
                cache('shopWeight_'.$shop_code, $weight);
            }else{
                $weight = '1';
            }
        }
        return $weight;
    }
    
    // 根据员工id 获取 事业部 店 部门 列表
    public function getLists($staff_id){
        $staffInfo = getStaffInfoById($staff_id);
        // 判断所属
        switch ($staffInfo['is_belong']) {
            // 集团     事业部列表
            case '1':
                $url = '5a38840b15ba9';
                $data['id'] = '';
                $res = sx_call($url,$data);
                if ($res['code'] == 200) {
                    $brandclassList = $res['data'];
                }else{
                    $brandclassList = '';
                }
                $shopList = '';
                $departmentList = '';
                break;
            // 事业部   店列列表（电商，网销，渠道）
            case '2':
                $brandclassList = [
                    '0' =>[
//                        'id'=>$staffInfo['brandclass_id'],
//                        'brandclass'=>$staffInfo['brandclass']
                    'id'=>session('brandclass_id'),
                    'brandclass'=>session('brandclass'),
                    ]
                ];
                $url = '5a37a1503264d';
//                $data['brandclass_id'] = $staffInfo['brandclass_id'];
                $data['brandclass_id'] = session('brandclass_id');
                $res = sx_call($url,$data);
                if ($res['code'] == 200) {
                    $shopList = $res['data'];
                }else{
                    $shopList = '';
                }
                $departmentList = '';
                break;
            // 店   部门列表
            case '3':
                $brandclassList = [
                    '0' =>[
//                        'id'=>$staffInfo['brandclass_id'],
//                        'brandclass'=>$staffInfo['brandclass']
                         'id'=>session('brandclass_id'),
                    'brandclass'=>session('brandclass'),
                    ]
                ];
                $shopList = [
                    '0' =>[
//                        'shop_code'=>$staffInfo['shop_code'],
//                        'shop_name'=>$staffInfo['shop_name']
                        'shop_code'=>session('shop_code'),
                        'shop_name'=>session('shop_name')
                    ]
                ];
                $url = '5a0aef152b750';
                $data['shop_code'] = session('shop_code');
                $res = sx_call($url, $data);
                if ($res['code'] == 200) {
                    $departmentList = $res['data'];
                }else{
                    $departmentList = '';
                }
                break;
            default:
                $brandclassList = [
                    '0' =>[
//                        'id'=>$staffInfo['brandclass_id'],
//                        'brandclass'=>$staffInfo['brandclass']
                         'id'=>session('brandclass_id'),
                    'brandclass'=>session('brandclass'),
                    ]
                ];
                $shopList = [
                    '0' =>[
//                        'shop_code'=>$staffInfo['shop_code'],
//                        'shop_name'=>$staffInfo['shop_name']
                         'shop_code'=>session('shop_code'),
                        'shop_name'=>session('shop_name')
                    ]
                ];
                $url = '5a0aef152b750';
                $data['shop_code'] = $staffInfo['shop_code'];
                $res = sx_call($url, $data);
                if ($res['code'] == 200) {
                    $departmentList = $res['data'];
                }else{
                    $departmentList = '';
                }
                break;
        }

        $lists = [
            'brandclassList' => $brandclassList,
            'shopList'       => $shopList,
            'departmentList' => $departmentList,
        ];
        return $lists;
    }

    public function getBlong($staff_id,$whereC){
        $staffInfo = getStaffInfoById($staff_id);
        // 判断所属
        switch ($staffInfo['is_belong']) {
            // 集团     
            case '1':
                $where = $whereC;
                break;
            // 事业部   
            case '2':
                
                break;
            // 店   
            case '3':
                
                break;
        }
        return $where;
    }

    // 格式化  表格显示 
    public function formatDjCustomer($data){
        foreach ($data as $key => $value) {
            $names = $this->getDGForStaff($value['dj_staff_id']);
            // 登记时间
            if ($value['dj_day']) {
                $dj_day = date('Y-m-d', strtotime($value['dj_day']));
            }else{
                $dj_day = '';
            }
            // 进店时间
            if ($value['syjd_day']) {
                $syjd_day = date('Y-m-d', strtotime($value['syjd_day']));
            }else{
                $syjd_day = '';
            }
            // $return[$key]['id']               = $value['id'];
            // 事业部
            $return[$key]['brandclass']       = $value['brandclass'];
            // 部门名称
            $return[$key]['dname']            = $names['dname'];
            // 小组名称
            $return[$key]['gname']            = $names['gname'];
            // 提报日期
            $return[$key]['dj_day']           = $dj_day;
            // 登记人
            $return[$key]['dj_staff']         = $value['dj_staff'];
            // 客户姓名
            $return[$key]['customer_name']    = $value['customer_name'];
            // 客户手机
            $return[$key]['customer_tel']     = $value['customer_tel'];
            // 提报类型
            $return[$key]['customer_type']    = $value['customer_type']==1 ? '新客资' : '转介绍';
            // 标记类型
            $return[$key]['op_signinfo']      = $value['op_signinfo'];
            // 介绍人编号
            $return[$key]['introducer_number']= $value['introducer_number'];
            // 介绍人姓名
            $return[$key]['introducer_name']  = $value['introducer_name'];
            // 介绍人电话
            $return[$key]['introducer_tel']   = $value['introducer_tel'];
            // 是否进店
            switch ($value['is_intostore']) {
                case '1':
                    $return[$key]['is_intostore'] = '未进店';
                    break;
                case '2':
                    $return[$key]['is_intostore'] = '进店进客';
                    break;
                case '3':
                    $return[$key]['is_intostore'] = '进店非进客';
                    break;
                case '4':
                    $return[$key]['is_intostore'] = '邀约未进店';
                    break;
            }
            // 进店时间
            $return[$key]['syjd_day']         = $syjd_day;
            // 成交金额
            $return[$key]['totalpay_money']   = $value['totalpay_money'];
            // 备注
            $return[$key]['customer_remark']  = $value['customer_remark'];
        }
        return $return;
    }

    // 根据员工id获取时间段内的客资   表格显示 
    public function getDjCustomerByStaffid($shop_code, $data){
        // 分页
        $page = $data['page'];
        $limit= $data['limit'];
        // 时间段
        $timeArea = $data['timeArea'] ? $data['timeArea'] : 'last_week';
        $timeArea = getdateArea($timeArea);
        $where['is_status'] = 1;
        $where['c_from'] = 1;
//        if($data['consultation_type_id']){
//            $where['consultation_type_id'] = $data['consultation_type_id'];
//        }
        if($page && $limit) {
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', $data['staff'])
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->limit($limit)
                ->page($page)
                ->select();
        }else{
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', $data['staff'])
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->select();
        }
        // 统计总条数
        $count = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', $data['staff'])
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->count();

        $return['code'] = 0;
        $return['msg']  = '';
        $return['count']= $count;
        // 格式化输出数据
        $dataOut = $this->formatDjCustomer($res);
        $return['data'] = $dataOut;
        return $return;
    }

    // 根据 组id 获取时间段内的客资   表格显示 
    public function getDjCustomerByGroupid($shop_code, $data){
        // 分页
        $page = $data['page'];
        $limit= $data['limit'];
        // 时间段
        $timeArea = $data['timeArea'] ? $data['timeArea'] : 'last_week';
        $timeArea = getdateArea($timeArea);

        // 获取组 成员
        $staffs = $this->getStaffs($data['group']);
        foreach ($staffs as $key => $value) {
            $ids[$key] = $value['id'];
        }
        $ids = implode($ids, ',');
        $where['is_status'] = 1;
        $where['c_from'] = 1;
//        if($data['consultation_type_id']){
//            $where['consultation_type_id'] = $data['consultation_type_id'];
//        }
        // 获取值
        if($page && $limit) {
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', 'in', $ids)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->limit($limit)
                ->page($page)
                ->select();
        }else{
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', 'in', $ids)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->select();
        }
        // 统计总条数
        $count = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', 'in', $ids)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->count();
        $return['code'] = 0;
        $return['msg']  = '';
        $return['count']= $count;
        // 格式化输出数据
        $dataOut = $this->formatDjCustomer($res);
        $return['data'] = $dataOut;
        return $return; 
    }

    // 根据 部门id 获取时间段内的客资   表格显示 
    public function getDjCustomerByDepartmentid($shop_code, $data){
        // 分页
        $page = $data['page'];
        $limit= $data['limit'];
        // 时间段
        $timeArea = $data['timeArea'] ? $data['timeArea'] : 'last_week';
        $timeArea = getdateArea($timeArea);
        $where['is_status'] = 1;
        $where['c_from'] = 1;
//        if($data['consultation_type_id']){
//            $where['consultation_type_id'] = $data['consultation_type_id'];
//        }
        // 获取  部门  成员
        // $staffs = $this->getGroupStaffs($data['department']);
        $staffs = $this->getDepartmentStaffs($data['department']);

        foreach ($staffs as $key => $value) {
            $ids[$key] = $value['id'];
        }
        $ids = implode($ids, ',');

        // 获取值
        if($page && $limit){
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', 'in', $ids)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->limit($limit)
                ->page($page)
                ->select();
        }else{
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', 'in', $ids)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->select();
        }


        // 统计总条数
        $count = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_staff_id', 'in', $ids)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->count();

        $return['code'] = 0;
        $return['msg']  = '';
        $return['count']= $count;
        // 格式化输出数据
        $dataOut = $this->formatDjCustomer($res);
        $return['data'] = $dataOut;

        return $return;
    }

    // 客资登记表格 默认方法 获取上一周，该店下所有新客资   表格显示 
    public function getDjCustomer($shop_code, $data){
        // 分页
        $page = $data['page'];
        $limit= $data['limit'];
        // 时间阶段
        $timeArea = $data['timeArea'] ? $data['timeArea'] : 'last_week';
        $timeArea = getdateArea($timeArea);
        $where['is_status'] = 1;
        $where['c_from'] = 1;
//        if($data['consultation_type_id']){
//            $where['consultation_type_id'] = $data['consultation_type_id'];
//        }
        if($page && $limit) {
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->limit($limit)
                ->page($page)
                ->select();
        }else{
            $res = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->select();
        }

        // 统计总条数
        $count = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_day', 'between', [$timeArea[0], $timeArea[1]])
                ->count();
        $return['code'] = 0;
        $return['msg']  = '';
        $return['count']= $count;
        // 格式化输出数据
        $dataOut = $this->formatDjCustomer($res);
        $return['data'] = $dataOut;
        return $return;
    }

    // 获取该店面下的  每个部门  毛客资量    echarts柱状图
    public function djCustomerNum($deparments, $timeArea,$consultation_type_id = 0,$shop_code){
        if(empty($shop_code)) $shop_code = session('shop_code');

        $timeArea = $timeArea ? $timeArea : 'last_week';
        $timeArea = getdateArea($timeArea);
        $timezone = getDateFromRange($timeArea[0], $timeArea[1]);
        $url = '5a0e6f272bb38';
        $ids = '';
        $where = '';
//        if($consultation_type_id){
//            $where['consultation_type_id'] = $consultation_type_id;
//        }
        foreach ($deparments as $key => $value) {
            $param['department_id'] = $value['id'];
            $param['get_leave'] = 2;
            $res = sx_call($url, $param);
            unset($param);
            foreach ($res['data'] as $k => $v) {
                $ids[$value['id']][$k] = $v['id'];
            }
            $id_s = implode($ids[$value['id']], ',');
            foreach ($timezone as $a => $b) {
                $zone[$a] = date('m-d', strtotime($b));
                $cData[$a] = db('crm_c_customerinfo')
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where($where)
                    ->where('add_shop_code', $shop_code)
                    ->where('dj_day', 'like', $b.'%')
                    ->where('dj_staff_id','in',$id_s)
                    ->count('id');
                // echo db()->getLastSql().'<br />';
            }
            // $arr[$key]['id'] = $value['id'];
            $arr[$key]['names'] = $value['department_name'];
            $arr[$key]['data'] = $cData;
            $temp[$key] = $value['department_name'];
        }
        // var_dump($temp);
        // exit;
        $data['timezone'] = $zone;
        $data['names'] = $temp;
        $data['data'] = $arr;
        return $data;
    }

    // 根据  员工id 时间区间  获取毛客资量     echarts柱状图
    public function getNewPicForStaff($staff_id,$timeArea,$consultation_type_id=0,$shop_code){
        if(empty($shop_code)) $shop_code = session('shop_code');
        $timeArea = $timeArea ? $timeArea : 'last_week';
        $timeArea = getdateArea($timeArea);
        $timezone = getDateFromRange($timeArea[0], $timeArea[1]);
        $where = '';
//        if($consultation_type_id){
//            $where['consultation_type_id'] = $consultation_type_id;
//        }
        foreach ($timezone as $key => $value) {
            $zone[$key] = date('m-d', strtotime($value));
            // $where = [
            //     'staff_id'=> $staff_id,
            //     'addtime' => $value,
            // ];
            // $res = db('c_day_number')->where($where)->column('dj_customer');
            $res = db('crm_c_customerinfo')
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where($where)
                ->where('add_shop_code', $shop_code)
                ->where('dj_day', 'like', $value.'%')
                ->where('dj_staff_id',$staff_id)
                ->count('id');
            // echo db()->getLastSql();
            // echo '<br />';
            $temp[$key] = $res;
        }
        // exit;
        $data['timezone']       = $zone;
        $data['data'][0]['data']= $temp;
        // var_dump($data);
        return $data;
    }

    // 根据  组id  时间区间  获取毛客资量    echarts柱状图
    public function getNewPicForGroup($group_id,$timeArea,$consultation_type_id=0,$shop_code){
        if(empty($shop_code)) $shop_code = session('shop_code');
        $timeArea = $timeArea ? $timeArea : 'last_week';
        $timeArea = getdateArea($timeArea);
        $timezone = getDateFromRange($timeArea[0], $timeArea[1]);
        $where = '';
//        if($consultation_type_id){
//            $where['consultation_type_id'] = $consultation_type_id;
//        }
        $staffs = $this->getStaffs($group_id);
        foreach ($staffs as $key => $value) {
            $staffnames[$key] = $value['staffname'];
            foreach ($timezone as $k => $v) {
                $zone[$k] = date('m-d', strtotime($v));
                $cData[$k] = db('crm_c_customerinfo')
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where($where)
                    ->where('add_shop_code', $shop_code)
                    ->where('dj_day', 'like', $v.'%')
                    ->where('dj_staff_id',$value['id'])
                    ->count('id');
            }
            $temp[$key]['data'] = $cData;
            $temp[$key]['names'] = $value['staffname'];
        }
        $return['data'] = $temp;
        $return['timezone'] = $zone;
        $return['names'] = $staffnames;

        return $return;
    }
    // 根据  部门id  时间区间  获取毛客资量    echarts柱状图
    public function getNewPicForDepartment($department_id,$timeArea,$consultation_type_id = 0,$shop_code){
        if(empty($shop_code)) $shop_code = session('shop_code');
        $timeArea = $timeArea ? $timeArea : 'last_week';
        $timeArea = getdateArea($timeArea);
        $timezone = getDateFromRange($timeArea[0], $timeArea[1]);
        $where = '';
//        if($consultation_type_id){
//            $where['consultation_type_id'] = $consultation_type_id;
//        }
        // 获取部门下的小组
        $groups = $this->getGroups($department_id);
        foreach ($groups as $key => $value) {
            $groupnames[$key] = $value['group_name'];
            // 根据组id获取组下的员工
            $staffs = $this->getStaffs($value['id']);
            foreach ($staffs as $a => $b) {
                $gids[$a] = $b['id'];
            }
            $ids = implode($gids, ',');
            foreach ($timezone as $k => $v) {
                $zone[$k] = date('m-d', strtotime($v));
                $cData[$k] = db('crm_c_customerinfo')
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where($where)
                    ->where('add_shop_code', $shop_code)
                    ->where('dj_day', 'like', $v.'%')
                    ->where('dj_staff_id','in', $ids)
                    ->count('id');
            }
            $temp[$key]['data'] = $cData;
            $temp[$key]['names'] = $value['group_name'];
        }

        $return['data']     = $temp;
        $return['timezone'] = $zone;
        $return['names']    = $groupnames;
        return $return;
    }

    // 根据渠道获取统计  默认上月  未完成
    public function getChannelCost($channel, $timeArea='last_month'){
        
        $return['names']   = ['总花费', '套餐金额', '回报率'];

        $timeArea = getdateArea($timeArea);
        foreach ($channel as $key => $value) {
            $names[$key] = $value['channel_name'];
            $where = [
                'customer_channel' => $value['channel_name'],
                'shop_code'        => $value['shop_code'],
            ];
            $res = db('crm_c_customer_order')
                ->where($where)
                ->whereTime('create_time', 'last month')
                // ->where('create_time', 'between', [$timeArea[0], $timeArea[1]])
                ->sum('order_amount');
            // echo db()->getLastSql();
            // echo '<br />';
            $temp[$key] = $res;
        }

        $return['channels']= $names;
        $return['data'][0]['names'] = '总花费';
        $return['data'][0]['data']  = $temp;
        $return['data'][0]['type']  = 'bar';
        
        // var_dump($return['data']);
        // exit;
    }

    // 大屏专用  判断  该员工是否有权限查看大屏数据
    public function checkBigScreenAuth(){
        // 获取配置文件中的信息，根据,分割成数组，如果staff_id不存在，则跳转到登录或首页
        $staff_id = session('staff_id');
        $str_id = config('bigScreen_id');
        $bigScreen_id = explode(',', $str_id);
        $is_in = in_array($staff_id, $bigScreen_id);
        if ($is_in === false) {
            // controller('crm/Index','controller')->index();
            // exit;
            return false;
        }else{
            return true;
        }
    }

    // 获取毛客资量
    public function getCustomerNum($data){
        // 毛客资定义：电商录入的新客资，不包括网销，渠道录入的客资
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        $where['customer_type'] = 1;
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('dj_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('dj_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }
        // echo db()->getLastSql();
        // exit;
        return $num;
    }

    // 获取毛客资量
    public function sta_getCustomerNum($data){
        // 毛客资定义：电商录入的新客资，不包括网销，渠道录入的客资
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
//        if($data['consultation_type_id']){
//            $where['consultation_type_id'] = $data['consultation_type_id'];
//        }
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('dj_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('dj_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }
        return $num;
    }

    // 获取有效客资 量
    public function getInvCustomerNum($data){
        // 有效客资定义：毛客资中，标记有效的，消费类型为婚纱
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['is_valid'] = 1;
        $where['consultation_type_id'] = HS_TYPE;
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }
        // echo db()->getLastSql();
        // exit;
        return $num;
    }
    // 获取有效客资 量
    public function sta_getInvCustomerNum($data){
        // 有效客资定义：毛客资中，标记有效的，消费类型为婚纱
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['is_valid'] = 1;
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }
        return $num;
    }

    // 获取手机 量
    public function getTelCustomerNum($data){
        // 获取手机定义：有效客资中 存在手机号的
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['is_valid'] = 1;
        $where['consultation_type_id'] = HS_TYPE;

        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('customer_tel', 'not null')
                ->where('customer_tel', '<>', '')
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('customer_tel', 'not null')
                ->where('customer_tel', '<>', '')
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }
        return $num;
    }
    // 获取手机 量
    public function sta_getTelCustomerNum($data){
        // 获取手机定义：有效客资中 存在手机号的
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['is_valid'] = 1;
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('customer_tel', 'not null')
                ->where('customer_tel', '<>', '')
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('customer_tel', 'not null')
                ->where('customer_tel', '<>', '')
                ->where('yx_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }

        return $num;
    }

    // 进店/邀约 量
    public function getIntoCustomerNum($data){
        // 进店/邀约定义：电商、网销录入的新客资  消费类型为婚纱，且实际进店，标记为进店进客 + 线上订单
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['consultation_type_id'] = HS_TYPE;

        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            // 实际进店 （进店进客）
            $inv = db('crm_c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
//                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('shop_code', 'in', $data['add_shop_code'])
                ->where('syjd_day', 'between time', [$data['start'], $data['end']])
                ->count();
            // 线上订单
            // $online = db('crm_c_customerinfo')
            //     ->where($where)
            //     ->where('order_type', 1)
            //     ->where('is_intostore', '<>',2)
            //     ->where('add_shop_code', 'in', $data['add_shop_code'])
            //     ->where('order_start_time', 'between time', [$data['start'], $data['end']])
            //     ->count();
            $num = $inv;
            // $num = $inv+$online;
        }else{
            // 实际进店 （进店进客）
            $inv = db('crm_c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
//                ->where('shop_code', 'in', $data['add_shop_code'])
                ->where('syjd_day', 'between time', [$data['start'], $data['end']])
                ->count();
            // echo db()->getLastSql().'<br />';
            // 线上订单
            // $online = db('crm_c_customerinfo')
            //     ->where($where)
            //     ->where('order_type', 1)
            //     ->where('is_intostore', '<>',2)
            //     ->where('add_shop_code', 'in', $data['add_shop_code'])
            //     ->where('order_start_time', 'between time', [$data['start'], $data['end']])
            //     ->count();
            // echo db()->getLastSql();
            $num = $inv;
            // $num = $inv+$online;
        }
        // exit;
        return $num;
    }
    // 进店/邀约 量
    public function sta_getIntoCustomerNum($data){
        // 进店/邀约定义：电商、网销录入的新客资  消费类型为婚纱，且实际进店，标记为进店进客 + 线上订单
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            // 实际进店 （进店进客）
            $inv = db('crm_c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('syjd_day', 'between time', [$data['start'], $data['end']])
                ->count();
            // 线上订单
//            $online = db('crm_c_customerinfo')
//                ->where($where)
//                ->where('order_type', 1)
//                ->where('is_intostore', '<>',2)
//                ->where('add_shop_code', 'in', $data['add_shop_code'])
//                ->where('order_start_time', 'between time', [$data['start'], $data['end']])
//                ->count();
            $num = $inv;
        }else{
            // 实际进店 （进店进客）
            $inv = db('crm_c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('syjd_day', 'between time', [$data['start'], $data['end']])
                ->count();
            // echo db()->getLastSql();
            // 线上订单
//            $online = db('crm_c_customerinfo')
//                ->where($where)
//                ->where('order_type', 1)
//                ->where('is_intostore', '<>',2)
//                ->where('add_shop_code', 'in', $data['add_shop_code'])
//                ->where('order_start_time', 'between time', [$data['start'], $data['end']])
//                ->count();
            // echo db()->getLastSql();
            $num = $inv;
        }
        // exit;
        return $num;
    }

    // 新单 量
    public function getOrderNumberNum($data){
        // 新单 定义：电商、网销录入的新客资  消费类型为婚纱，且已经有效的订单
        // $where['c.is_status'] = 1;
        // $where['c.c_from'] = 1;
        // $where['c.customer_type'] = 1;
        // $where['c.consultation_type_id'] = HS_TYPE;
        // // $where['c.is_success'] = 1;

        // $num = db('crm_c_customer_order')->alias('o')
        //     ->join('crm_c_customerinfo c ','c.id = o.customer_id')
        //     ->where($where)
        //     ->where('o.order_valid', 2)
        //     ->where('c.add_shop_code', 'in', $data['add_shop_code'])
        //     ->where('o.create_time', 'between time', [$data['start'], $data['end']])
        //     ->count('o.id');
        // echo db()->getLastSql();

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

        $where['is_success'] = 1;
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('order_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('order_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }
        // echo db()->getLastSql();
        // exit;
        return $num;
    }
    // 新单 量
    public function sta_getOrderNumberNum($data){
        // 新单 定义：电商、网销录入的新客资  消费类型为婚纱，且已经有效的订单
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        $where['is_success'] = 1;
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('order_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }else{
            $num = db('crm_c_customerinfo')
                ->where($where)
                ->where('add_shop_code', 'in', $data['add_shop_code'])
                ->where('order_day', 'between time', [$data['start'], $data['end']])
                ->count();
        }

        return $num;
    }

    //其它费用统计
    public function anotherCost($param){
        $start = $param['start'] ? $param['start'] : date('Y-m-d 00:00:00');
        $end   = $param['end'] ? $param['end'] : date('Y-m-d 23:59:59');
        $sql = ' 1=1 ';
        if($param['brandclass_id']){
            $sql .= " and brandclass_id=".intval($param['brandclass_id']);
        }
        // if($param['add_shop_code']){
        //     $add_shop_code = explode(',',$param['add_shop_code']);
        // }
        $info = db('crm_s_another_cost_detail')
            ->where($sql)
            // ->where('shop_code','in',$add_shop_code)
            ->where('cost_date','between time',[$start,$end])
            ->sum('cost_avg');
        return$info;
    }

    // 花费 
    public function costMoney($data){
        // 新单 定义：电商的花费（不包含返点） s_channel_cost 表
        $allCost = db('crm_s_channel_cost')
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('cost_date', 'between time', [$data['start'], $data['end']])
            ->field('id,channel_id,sum(cost) as cost')
            ->group('channel_id')
            ->select();
        $cost = 0;
        foreach ($allCost as $key => $value) {
            $returnCost = db('crm_s_shop_return_rule')->where('channel_id', $value['channel_id'])->field('return_rule,return_value')->find();
            if ($returnCost) {
                // 占比
                if ($returnCost['return_rule'] == 1) {
                    $cost += $value['cost'] * ((100-$returnCost['return_value'])/100);
                }
                // 定额
                else if ($returnCost['return_rule'] == 2) {
                    $cost += $value['cost'] - $returnCost['return_value'];
                }
            }else{
                $cost += $value['cost'];
            }
        }
        return $cost;
    }
    // 花费
    public function sta_costMoney($data){
        // 新单 定义：电商的花费（如果录入返点，则包含返点） c_customer_cost 表
        $cost = db('crm_c_customer_cost')
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('cost_time', 'between time', [$data['start'], $data['end']])
            ->sum('cost_avg');

        // $allCost = db('crm_s_channel_cost')
        //     ->where('shop_code', 'in', $data['add_shop_code'])
        //     ->where('cost_date', 'between time', [$data['start'], $data['end']])
        //     ->field('id,channel_id,sum(cost) as cost');
 
        // if($data['channel_id']){
        //     $allCost->where('channle_id',$data['channel_id']);
        // }
        // $info = $allCost->group('channel_id')
        //     ->select();
        // $cost = 0;
        // foreach ($info as $key => $value) {
        //     $returnCost = db('crm_s_shop_return_rule')->where('channel_id', $value['channel_id'])->field('return_rule,return_value')->find();
        //     if ($returnCost) {
        //         // 占比
        //         if ($returnCost['return_rule'] == 1) {
        //             $cost += $value['cost'] * ((100-$returnCost['return_value'])/100);
        //         }
        //         // 定额
        //         else if ($returnCost['return_rule'] == 2) {
        //             $cost += $value['cost'] - $returnCost['return_value'];
        //         }
        //     }else{
        //         $cost += $value['cost'];
        //     }
        // }
        return $cost;
    }
    // 成交金额
    public function dealMoney($data){
        // 新单 定义：电商、网销录入的新客资转化为订单，消费类型为婚纱，的有效订单 的 一销套系金额  只能查 customer_order表
        // 根据customerinfo 表查 电商、网销 录入的新客资，消费类型为婚纱，已经有效的订单，order_day 为条件时间，根据customer_id，join customer_order表，sum('order_amount')

        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.customer_type'] = 1;
        $where['c.consultation_type_id'] = HS_TYPE;
        // $where['c.is_success'] = 1;

        $deal = db('crm_c_customer_order')->alias('o')
            ->join('crm_c_customerinfo c ','c.id = o.customer_id')
            ->where($where)
            ->where('o.order_valid', 2)
            ->where('c.add_shop_code', 'in', $data['add_shop_code'])
            ->where('o.create_time', 'between time', [$data['start'], $data['end']])
            ->sum('o.order_amount');

        // echo db()->getLastSql();
        // exit;
        return $deal;
    }
    // 成交金额
    public function sta_dealMoney($data){
        // 新单 定义：电商、网销录入的新客资转化为订单，消费类型为婚纱，的有效订单 的 一销套系金额  只能查 customer_order表
        // 根据customerinfo 表查 电商、网销 录入的新客资，消费类型为婚纱，已经有效的订单，order_day 为条件时间，根据customer_id，join customer_order表，sum('order_amount')

        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.customer_type'] = 1;
        $where['c.is_success'] = 1;
        if($data['consultation_type_id']){
            $where['c.consultation_type_id'] = $data['consultation_type_id'];
        }
        $deal = db('crm_c_customer_order o')
            ->join('crm_c_customerinfo c ','c.id = o.customer_id')
            ->where($where)
            ->where('c.add_shop_code', 'in', $data['add_shop_code'])
            ->where('c.order_day', 'between time', [$data['start'], $data['end']])
            ->sum('o.order_amount');

        return $deal;
    }

    // 营收 / 实收
    public function incomeMoney($data){
        // // 新单 定义：电商、网销实际收入，不限消费类型、订单状态是否有效 
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        if ($data['brandclass_id']) {
            $income = db('crm_c_customerinfo')
            ->where($where)
            ->where('brandclass_id', $data['brandclass_id'])
            ->where('order_start_time', 'between time', [$data['start'], $data['end']])
            ->sum('fact_money');
        }else{
            $income = db('crm_c_customerinfo')
            ->where($where)
            ->where('order_start_time', 'between time', [$data['start'], $data['end']])
            ->sum('fact_money');
        }
        // echo db()->getLastSql();
        // exit;
        
        // 新单 定义：实际收入，不限 电商还是网销、消费类型、订单状态是否有效 
        // if ($data['brandclass_id']) {
        //     $income = db('crm_c_order_detail')->alias('d')
        //     ->join('crm_c_customer_order o', 'd.order_sn=o.order_sn')
        //     ->where('o.brandclass_id', $data['brandclass_id'])
        //     ->where('d.pay_time', 'between time', [$data['start'], $data['end']])
        //     ->sum('d.order_fact');
        // }else{
        //     $income = db('crm_c_order_detail')
        //     ->where('pay_time', 'between time', [$data['start'], $data['end']])
        //     ->sum('order_fact');
        // }

        return $income;
    }
    // 营收 / 实收
    public function sta_incomeMoney($data){
        // 新单 定义：电商、网销实际收入，不限消费类型、订单状态是否有效
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        $income = db('crm_c_customerinfo')
            ->where($where)
            ->where('add_shop_code', 'in', $data['add_shop_code'])
            ->where('order_start_time', 'between time', [$data['start'], $data['end']])
            ->sum('fact_money');
        return $income;
    }
    //流失客资
    public function sta_get_loss_cus($data){
        if($data['consultation_type_id']){
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }else{
            $where = ' 1=1 ';
        }
        $loss = db('crm_c_customerinfo')
            ->where($where)
            ->where('is_loss',1)
            ->where('add_shop_code', 'in', $data['add_shop_code'])
            ->where('loss_day', 'between time', [$data['start'], $data['end']])
            ->count('id');
        return $loss;
    }


}