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

use app\index\controller\Base;
use PHPExcel;
use Symfony\Component\Yaml\Yaml;
use think\Queue;
use think\Request;

class Statistics extends Base
{
    // 大屏跳转
    public function bigScreen()
    {
        $this->redirect('/crm/Bigscreen');
        exit;
    }

    // 根据部门id获取所有  小组  信息
    public function getGroups()
    {
        $department_id = (int)input('department_id');
        $groups = controller('crm/Statistics', 'lib')->getGroups($department_id);
        return json($groups);
    }

    // 根据 组id 获取所有 小组成员 信息
    public function getStaffs($group_id)
    {
        $staffs = controller('crm/Statistics', 'lib')->getStaffs($group_id);
        foreach ($staffs as $key => $value) {
            $return[$key]['id'] = $value['id'];
            $return[$key]['staffname'] = $value['staffname'];
        }
        return $return;
    }

    // 根据 部门id 获取所有 小组成员 信息
    public function getDepartmentStaffs()
    {
        $department_id = (int)input('department_id');
        $return = controller('crm/Statistics', 'lib')->getDepartmentStaffs($department_id);
        return $return;
    }

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

    // 根据事业部获取  店（电商，网销，渠道）
    public function getDepartments()
    {
        $data = input();
        $url = '5a0aef152b750';
        $param['shop_code'] = $data['shop_code'];
        $res = sx_call($url, $param);

        if ($res['code'] == 200) {
            $departmentList = $res['data'];
        } else {
            $departmentList = '';
        }
        cookie('fp_select_shop_code',$data['shop_code']);
        return json($departmentList);
    }

    // 电商渠道客资统计  （页面）
    public function dsCustomerStatistics()
    {
        // 权限
        $auth = check_right('menu1515985582');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }

        switch (session('is_belong')) {
            case '1'://集团
                $shops = controller('crm/Customer', 'lib')->get_shop();
                break;
            case '2'://事业部
                $shops = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
                break;
            case '3'://店
            case '4'://部门
            default:
                $shops = controller('crm/Customer', 'lib')->get_shop(['shop_code' => session('shop_code')]);
                break;
        }
        $this->assign('shops', $shops);
        // 获取  部门 list
        $url = '5a0aef152b750';
        $data['shop_code'] = session('shop_code');
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $departmentList = $res['data'];
        } else {
            $departmentList = '';
        }
        // 部门    列表
        $this->assign('departmentList', $departmentList);
        $region = controller('crm/Customer', 'lib')->region();

        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('title', '电商渠道客资统计');
        return $this->fetch();
    }

    // 电商渠道客资统计  （数据）
    public function dsCustomerStatisticsData()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1515985582');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();

        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d 00:00:00', strtotime($timeArea[0]));
        $end = date('Y-m-d 23:59:59', strtotime($timeArea[1]));
        $shop_code = $data['shop_code'];
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        if ($data['consultation_type_id']) {
            $whereT['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 地域id，拼接where条件
        if ($data['province']) {
            $where['province_id'] = (int)$data['province'];
        }
        if ($data['city']) {
            $where['city_id'] = (int)$data['city'];
        }

        // 来源渠道
        $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        $count = count($channels);

        $arr['channel'] = '总计';
        foreach ($channels as $key => $value) {
            $returnData[$key]['channel'] = $value['channel_name'];

            $where['customer_channel_id'] = $value['id'];

            // 录入客资量
            $returnData[$key]['lrCustomer'] = db('c_customerinfo')
                ->where($where)
                ->where('dj_day', 'between time', [$start, $end])
                ->count();
            // 毛客资量 (接入时间)
            $returnData[$key]['mCustomer'] = db('c_customerinfo')
                ->where($where)
                ->where('jr_day', 'between time', [$start, $end])
                ->count();
            // echo db()->getLastSql().'<br />';
            // var_dump($returnData[$key]['mCustomer']);
            // 有效客资量
            $returnData[$key]['invCustomer'] = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('is_valid', 1)
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            // echo db()->getLastSql();
            // 进店数量
            $returnData[$key]['intoNum'] = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('is_intostore', 'between', '2,3')
                ->where('syjd_day', 'between time', [$start, $end])
                ->count();
            // echo db()->getLastSql();
            // 订单数量
            $returnData[$key]['orderNum'] = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('order_day', 'between time', [$start, $end])
                ->count();
            $arr['lrCustomer'] += $returnData[$key]['lrCustomer'];// 录入总计
            $arr['mCustomer'] += $returnData[$key]['mCustomer'];// 毛客资总计
            $arr['invCustomer'] += $returnData[$key]['invCustomer'];// 有效总计
            $arr['intoNum'] += $returnData[$key]['intoNum'];// 进店总计
            $arr['orderNum'] += $returnData[$key]['orderNum'];// 订单总计
        }
        array_push($returnData, $arr);
        // print_r($returnData);
        // exit;

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = $count;
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = array('渠道名称', '录入客资量', '毛客资量', '有效客资量', '进店数量', '订单数量');

            $file = 'dsCustomerStatisticsData.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
    }

    // 电商 渠道花费统计（电商）页面  (日报)
    public function dsDaily()
    {
        // 权限
        $auth = check_right('menu1512971049');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }

        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // var_dump($lists);
        // var_dump($lists['brandclassList']);
        // var_dump($lists['shopList']);
        // exit;
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        // today
        $today = date('Y-m-d') . ' - ' . date('Y-m-d');
        $this->assign('today', $today);

        $timeArea = getdateArea('this_month');
        $this->assign('start', $timeArea[0]);
        $this->assign('end', $timeArea[1]);

        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('title', '电商 渠道花费 统计日报');
        return $this->fetch();
    }

    // 电商 渠道花费统计（电商）数据表格  (日报)
    public function dsDailyData()
    {
        // 权限
        $auth = check_right('menu1512971049');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop'];
        $whereC = [];
        $staffInfo = getStaffInfoById(session('staff_id'));
        // 判断所属
        switch ($staffInfo['is_belong']) {
            // 集团
            case '1':
                if ($brandclass_id) {
                    $whereC['brandclass_id'] = $brandclass_id;
                }
                if ($shop_code) {
                    $whereC['shop_code'] = $shop_code;
                }
                break;
            // 事业部
            case '2':
                $whereC['brandclass_id'] = $staffInfo['brandclass_id'];
                if ($shop_code) {
                    $whereC['shop_code'] = $shop_code;
                }
                break;
            // 店
            case '3':
                $whereC['brandclass_id'] = $staffInfo['brandclass_id'];
                $whereC['shop_code'] = $staffInfo['shop_code'];
                break;
            default:
                $whereC['brandclass_id'] = $staffInfo['brandclass_id'];
                $whereC['shop_code'] = $staffInfo['shop_code'];
                break;
        }

        $page = (int)$data['page'];
        $limit = (int)$data['limit'];

        if (!$data['timeArea']) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);

        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d 23:59:59', strtotime($timeArea[1]));
        unset($timeArea);
        // 导出
        if ($data['need'] == 1) {
            // 电商 各渠道花费
            $channelCost = db('s_channel_cost')
                ->where($whereC)
                ->where('cost_date', 'between time', [$start, $end])
                ->order('cost_date', 'asc')
                ->column('channel_id,channel_name,region_name,cost,cost_date', 'id');
            // echo db()->getLastSql();
        } // 显示
        else {
            // 电商 各渠道花费
            $channelCost = db('s_channel_cost')
                ->where($whereC)
                ->where('cost_date', 'between time', [$start, $end])
                ->order('cost_date', 'asc')
                ->limit($limit)
                ->page($page)
                ->column('channel_id,channel_name,region_name,cost,cost_date', 'id');
        }

        if (!$channelCost) {
            $sql = db()->getLastSql();
            $return = ['code' => 0, 'msg' => '', 'count' => 0];
            // $return = ['code'=>0,'msg'=>'','count'=>0,'data' =>$sql];
            return json($return);
        }
        $returnData = [];

        foreach ($channelCost as $key => $value) {
            // var_dump($value);
            $returnData[$key]['cost_date'] = $value['cost_date'];
            $returnData[$key]['channel_name'] = $value['channel_name'];
            $returnData[$key]['cost'] = number_format($value['cost'], 2);
            // 基础判断条件
            $where = [
                'brandclass_id' => $whereC['brandclass_id'],
                'add_shop_code' => $whereC['shop_code'],
                'is_status' => 1,
                'c_from' => 1,
                'customer_channel_id' => $value['channel_id']
            ];
            if ($data['consultation_type_id']) {
                $where['consultation_type_id'] = $data['consultation_type_id'];
            }

            // 毛客资
            $newCustomer = db('c_customerinfo')
                ->where($where)
                ->where('dj_day', 'between time', [$start, $end])->count();
            $returnData[$key]['newCustomer'] += $newCustomer;
            // echo db()->getLastSql().'<br />';die;
            // var_dump($newCustomer);
            // exit;
            // 有效客资
            $validCustomer = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 1)
                ->where('yx_day', 'between time', [$start, $end])->count();
            $returnData[$key]['validCustomer'] = $validCustomer;
            // echo db()->getLastSql().'<br />';
            // var_dump($validCustomer);
            // 获取率 有效/毛客资
            $acquisitionRate = (number_format(($validCustomer / $newCustomer) * 100, 2)) . '%';
            $returnData[$key]['acquisitionRate'] = $acquisitionRate;
            // var_dump($acquisitionRate);
            // 邀约
            $invitation = db('c_customerinfo')
                ->where($where)
                ->where('yjd_day', 'between time', [$start, $end])->count();
            $returnData[$key]['invitation'] = $invitation;
            // echo db()->getLastSql().'<br />';
            // var_dump($invitation);
            // 进店 （进店   进客/非进客）
            $into = db('c_customerinfo')
                ->where($where)
                ->where('syjd_day', 'between time', [$start, $end])->count();
            $returnData[$key]['into'] = $into;
            // echo db()->getLastSql().'<br />';
            // var_dump($invitation);
            // 进店转化率  进店/有效
            $inRate = (number_format(($into / $validCustomer) * 100, 2)) . '%';
            $returnData[$key]['inRate'] = $inRate;
            // var_dump($inRate);
            // 订单总数  （总订单）
            $orderNum = db('c_customerinfo')
                ->where($where)
                ->where('order_start_time', 'between time', [$start, $end])->count();
            $returnData[$key]['orderNum'] = $orderNum;
            // echo db()->getLastSql().'<br />';
            // var_dump($orderNum);
            // 成交率  订单总数/进店
            $dealRate = (number_format(($orderNum / $into) * 100, 2)) . '%';
            $returnData[$key]['dealRate'] = $dealRate;
            // var_dump($dealRate);
            // 转化率  订单总数/有效
            $changeRate = (number_format(($orderNum / $validCustomer) * 100, 2)) . '%';
            $returnData[$key]['changeRate'] = $changeRate;
            // 总营收
            $orerAmount = db('c_customerinfo')
                ->where($where)
                ->where('order_day', 'between time', [$start, $end])
                ->sum('totalpay_money');
            $returnData[$key]['orerAmount'] = $orerAmount;
            // echo db()->getLastSql().'<br />';
            // var_dump($orerAmount);
            // 总实收
            $earning = db('c_customerinfo')
                ->where($where)
                ->where('order_day', 'between time', [$start, $end])
                ->sum('fact_money');
            $returnData[$key]['earning'] = $earning;
            // echo db()->getLastSql().'<br />';
            // var_dump($earning);
            // 总均价           总营收/总订单
            $averagePrice = $orerAmount / $orderNum;
            $returnData[$key]['averagePrice'] = number_format($averagePrice, 2);
            // var_dump($averagePrice);
            // 获取成本        花费 / 毛客资
            $obtainCost = $value['cost'] / $newCustomer;
            $returnData[$key]['obtainCost'] = number_format($obtainCost, 2);
            // var_dump($obtainCost);
            // 有效获取成本    花费 / 有效客资
            $vaildCost = $value['cost'] / $validCustomer;
            $returnData[$key]['vaildCost'] = number_format($vaildCost, 2);
            // var_dump($vaildCost);
            // 成交成本        花费/总订单
            $dealCost = $value['cost'] / $orderNum;
            $returnData[$key]['dealCost'] = number_format($dealCost, 2);
            // var_dump($dealCost);
            // ROI             总实收/花费
            $roi = (number_format(($earning / $value['cost']) * 100, 2)) . '%';
            $returnData[$key]['roi'] = $roi;
            // var_dump($roi);
        }
        // var_dump($returnData);
        // exit;
        // 导出
        if ($data['need'] == 1) {
            $title = array('日期', '渠道名称', '总花费', '总获取', '总有效获取', '获取率', '总邀约', '总进店', '进店转化率', '总订单', '成交率', '总转化率', '总营收', '总实收', '总均价', '获取成本', '有效获取成本', '成交成本', 'ROI');
            $file = 'dsDaily.xlsx';

            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } // 显示
        else {
            $count = db('s_channel_cost')
                ->where($whereC)
                ->where('cost_date', 'between time', [$start, $end])
                ->count();
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = $count;
            $return['data'] = $returnData;
            return json($return);
        }
        // var_dump($channelCost);
        // exit;
    }

    // 电商 渠道花费统计（电商）页面  (月报)
    public function dsReport()
    {
        // 权限
        $auth = check_right('menu1514351403');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }

        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));

        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        // month
        $month = date('Y-m');
        $this->assign('month', $month);

        // 是否已生成月报
        $timeArea = getdateArea('this_month');
        $where['shop_code'] = session('shop_code');
        $where['brandclass_id'] = session('brandclass_id');

        $reportStatus = db('c_ds_report')
            ->where($where)
            ->where('date', 'between time', [$timeArea[0], $timeArea[1]])
            ->count();

        // echo db()->getLastSql();
        // var_dump($reportStatus);
        // exit;
        if ($reportStatus) {
            $reportStatus = 1;
        } else {
            $reportStatus = 0;
        }
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('reportStatus', $reportStatus);
        $this->assign('title', '电商 渠道花费 统计月报');
        return $this->fetch();
    }

    // 生成月报
    public function createDsReport()
    {
        $auth = check_right('menu1514351403');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();

        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）'];
            return json($return);
        }
        // 基础条件
        $where = [
            'shop_code' => $shop_code,
            'brandclass_id' => $brandclass_id,
        ];

        $month = $data['timeArea'];
        // 月份的每一天
        $days = getMonthDays($month);
        $now = date('Y-m-d H:i:s');
        // $staff_id = session('staff_id');
        // $staffInfo= getStaffInfoById($staff_id);
        // 循环这个月的每一天
        foreach ($days as $key => $value) {
            // 删除之前的月报表
            $del_res = db('c_ds_report')->where($where)->where('date', $value)->delete();

            // 花费 日均表
            $costInfo = db('c_customer_cost')
                ->where($where)
                ->where('cost_time', $value)
                ->where('channel_id', '<>', 0)
                ->field('channel_id,channel_name,region_id,region_name,cost_avg,return_avg')
                ->select();

            // 判断条件
            $whereC['add_shop_code'] = $where['shop_code'];
            $whereC['brandclass_id'] = $where['brandclass_id'];
            $whereC['is_status'] = 1;
            $whereC['c_from'] = 1;
            if ($data['consultation_type_id']) {
                $whereC['consultation_type_id'] = $data['consultation_type_id'];
            }
            // 循环这个月的每一个 花费
            foreach ($costInfo as $k => $v) {
                // 基础数据
                $createDate[$key . $k]['date'] = $value;
                $createDate[$key . $k]['create_time'] = $now;
                $createDate[$key . $k]['shop_code'] = $shop_code;
                $createDate[$key . $k]['brandclass_id'] = $brandclass_id;
                $createDate[$key . $k]['channel_id'] = $v['channel_id'];
                $createDate[$key . $k]['channel'] = $v['channel_name'];
                $createDate[$key . $k]['region_id'] = $v['region_id'];
                $createDate[$key . $k]['region'] = $v['region_name'];
                $createDate[$key . $k]['cost'] = $v['cost_avg'] - $v['return_avg'];
                $createDate[$key . $k]['return_cost'] = $v['return_avg'];

                $whereC['customer_channel_id'] = $v['channel_id'];
                if ($v['region_id'] != 0) {
                    $whereC['customer_region_id'] = $v['region_id'];
                }

                // 总获取
                $newCustomer = db('c_customerinfo')
                    ->where($whereC)
                    ->where('dj_day', 'like', $value . '%')->count();
                // echo db()->getLastSql().'<br />';
                // exit;
                $createDate[$key . $k]['new_customer'] = $newCustomer;
                // echo db()->getLastSql().'<br />';
                // 总有效获取
                $validCustomer = db('c_customerinfo')
                    ->where($whereC)
                    ->where('is_valid', 1)
                    ->where('yx_day', 'like', $value . '%')->count();
                $createDate[$key . $k]['valid_customer'] = $validCustomer;
                // 获取率      总有效获取/总获取
                $aRate = $validCustomer / $newCustomer;
                $acquisitionRate = round($aRate * 100, 4);
                $createDate[$key . $k]['acquisition_rate'] = $acquisitionRate;
                // 总邀约
                $invitation = db('c_customerinfo')
                    ->where($whereC)
                    ->where('yjd_day', 'like', $value . '%')->count();
                $createDate[$key . $k]['invitation'] = $invitation;
                // 总进店
                $into = db('c_customerinfo')
                    ->where($whereC)
                    ->where('syjd_day', 'like', $value . '%')->count();
                $createDate[$key . $k]['into'] = $into;
                // 进店转化率  总进店/总有效获取
                $iRate = $into / $validCustomer;
                $inRate = round($iRate * 100, 4);
                $channelCost[$key]['in_rate'] = $inRate;
                // 总订单
                $orderNum = db('c_customerinfo')
                    ->where($whereC)
                    ->where('order_start_time', 'like', $value . '%')->count();
                $createDate[$key . $k]['order_num'] = $orderNum;
                // 成交率      总订单/总进店
                $dRate = $orderNum / $into;
                $dealRate = round($dRate * 100, 4);
                $createDate[$key . $k]['deal_rate'] = $dealRate;
                // 总转化率    总订单/总有效获取
                $cRate = $orderNum / $validCustomer;
                $changeRate = round($cRate * 100, 4);
                $createDate[$key . $k]['change_rate'] = $changeRate;
                // 总营收 (有效订单)
                $orerAmount = db('c_customerinfo')
                    ->where($whereC)
                    ->where('order_day', 'like', $value . '%')
                    ->sum('totalpay_money');
                $createDate[$key . $k]['orer_amount'] = $orerAmount;
                // 总实收
                $earning = db('c_customerinfo')
                    ->where($whereC)
                    ->where('order_start_time', 'like', $value . '%')
                    ->sum('fact_money');
                $createDate[$key . $k]['earning'] = $earning;
                // 总均价  总营收 / 总订单
                $averagePrice = $orerAmount / $orderNum;
                $createDate[$key . $k]['average_price'] = round($averagePrice, 4);

                // 获取成本      总实际支出 / 总获取
                $obtainCost = ($v['cost_avg'] - $v['return_avg']) / $newCustomer;
                $createDate[$key . $k]['obtain_cost'] = round($obtainCost, 4);

                // 有效获取成本  总实际支出 / 总有效获取
                $vaildCost = ($v['cost_avg'] - $v['return_avg']) / $validCustomer;
                $createDate[$key . $k]['vaild_cost'] = round($vaildCost, 4);

                // 成交成本      总实际支出 / 总订单
                $dealCost = ($v['cost_avg'] - $v['return_avg']) / $orderNum;
                $createDate[$key . $k]['deal_cost'] = round($dealCost, 4);

                // roi           总实收/总实际支出
                $roi = round(($earning / ($v['cost_avg'] - $v['return_avg'])) * 100, 4);
                $createDate[$key . $k]['roi'] = $roi;
            }
        }
        // exit;

        // 开启事务
        db()->startTrans();
        try {
            // 重新生成 月报表
            $result = db('c_ds_report')->insertAll($createDate);
            db()->commit();
            $returnData = array('code' => 200, 'msg' => 0);
        } catch (Exception $e) {
            db()->rollBack();
            $returnData = array('code' => 100, 'msg' => '生成月报失败，请重试。');
        }

        return $returnData;
    }

    // 电商 渠道花费统计（电商）数据表格  (月报)
    public function dsReportData()
    {
        // 权限
        $auth = check_right('menu1514351403');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];
        $month = $data['timeArea'];

        // exit;
        $start = date('Y-m-01', strtotime($month));
        $end = date('Y-m-d', strtotime($start . ' +1 month -1 day'));

        $info = db('c_ds_report')
            ->where('shop_code', $shop_code)
            ->where('brandclass_id', $brandclass_id)
            ->where('date', 'between time', [$start, $end])
            ->select();
        // echo db()->getLastSql();
        // var_dump($info);
        // exit;
        $returnData = [];
        $return = [];
        if (!$info) {
            $return['code'] = 0;
            $return['msg'] = '尚未生成月报，请点击生成按钮';
            $return['count'] = count($returnData);
            $return['data'] = $returnData;
            return json($return);
        }
        // 取出所有值，并根据渠道统一
        foreach ($info as $key => $value) {
            // 渠道名称
            $temp[$value['channel_id']]['channel'] = $value['channel'];
            // 总实际支出
            $temp[$value['channel_id']]['cost'] += $value['cost'];
            // 返点花费
            $temp[$value['channel_id']]['return_cost'] += $value['return_cost'];
            // 总获取
            $temp[$value['channel_id']]['new_customer'] += $value['new_customer'];
            // 总有效获取
            $temp[$value['channel_id']]['valid_customer'] += $value['valid_customer'];
            // 总邀约
            $temp[$value['channel_id']]['invitation'] += $value['invitation'];
            // 总进店
            $temp[$value['channel_id']]['into'] += $value['into'];
            // 总订单
            $temp[$value['channel_id']]['order_num'] += $value['order_num'];
            // 总营收
            $temp[$value['channel_id']]['orer_amount'] += $value['orer_amount'];
            // 总实收
            $temp[$value['channel_id']]['earning'] += $value['earning'];
        }

        // 计算各种  率及成本
        foreach ($temp as $key => $value) {
            // 渠道名称
            $returnData[$key]['channel'] = $value['channel'];
            // 总实际支出
            $cost = $value['cost'] - $value['return_cost'];
            $returnData[$key]['cost'] = $cost;
            // 返点花费
            $returnData[$key]['return_cost'] = $value['return_cost'];
            // 总获取
            $returnData[$key]['new_customer'] = $value['new_customer'];
            // 总有效获取
            $returnData[$key]['valid_customer'] = $value['valid_customer'];
            // 获取率  总有效 / 总获取
            $returnData[$key]['acquisition_rate'] = (round(($value['valid_customer'] / $value['new_customer']) * 100, 2)) . '%';
            // 总邀约
            $returnData[$key]['invitation'] = $value['invitation'];
            // 总进店
            $returnData[$key]['into'] = $value['into'];
            // 进店率  总进店 / 总有效
            $returnData[$key]['in_rate'] = (round(($value['into'] / $value['valid_customer']) * 100, 2)) . '%';
            // 总订单
            $returnData[$key]['order_num'] = $value['order_num'];
            // 成交率  总订单 / 总进店
            $returnData[$key]['deal_rate'] = (round(($value['order_num'] / $value['into']) * 100, 2)) . '%';
            // 总转化率  总订单 / 总有效
            $returnData[$key]['change_rate'] = (round(($value['order_num'] / $value['valid_customer']) * 100, 2)) . '%';
            // 总营收
            $returnData[$key]['orer_amount'] = $value['orer_amount'];
            // 总实收
            $returnData[$key]['earning'] = $value['earning'];
            // 总均价  总营收 / 总订单
            $returnData[$key]['average_price'] = round($value['orer_amount'] / $value['order_num'], 2);
            // 获取成本  总实际支出 / 总获取
            $returnData[$key]['obtain_cost'] = round($cost / $value['new_customer'], 2);
            // 有效获取成本  总有效获取 / 总实际支出
            $returnData[$key]['vaild_cost'] = round($cost / $value['valid_customer'], 2);
            // 成交成本  总花费 / 总订单
            $returnData[$key]['deal_cost'] = round($cost / $value['order_num'], 2);
            // ROI  总实收 / 总实际支出
            $returnData[$key]['roi'] = round($value['earning'] / $cost, 2);
        }
        // 导出
        if ($data['need'] == 1) {
            $title = array('渠道名称', '总实际支出', '返点花费', '总获取', '总有效获取', '获取率', '总邀约', '总进店', '进店转化率', '总订单', '成交率', '总转化率', '总营收', '总实收', '总均价', '获取成本', '有效获取成本', '成交成本', 'ROI');
            $file = 'dsReport.xlsx';

            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } // 显示
        else {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = count($returnData);
            $return['data'] = $returnData;
            return json($return);
        }
    }

    // 深挖客资日报 (页面)
    public function swCustomerDaily()
    {
        // 权限
        $auth = check_right('menu1514424405');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        switch (session('is_belong')) {
            case '1'://集团
                $shops = controller('crm/Customer', 'lib')->get_shop();
                break;
            case '2'://事业部
                $shops = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
                break;
            case '3'://店
            case '4'://部门
            default:
                $shops = controller('crm/Customer', 'lib')->get_shop(['shop_code' => session('shop_code')]);
                break;
        }
        $this->assign('shops', $shops);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        $this->assign('title', '深挖 客资日报');
        return $this->fetch();
    }

    // 深挖客资日报 (数据表格)
    public function swCustomerDailyData()
    {
        // 权限
        $auth = check_right('menu1514424405');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }

        $data = input();
        $date = $data['day'] ? date('Y-m-d', strtotime($data['day'])) : date('Y-m-d');
        $next = date('Y-m-d', strtotime($date . ' +1 day'));

        $shop_code = $data['shop_code'];

        $where = ['is_status' => 1, 'c_from' => 1, 'shop_code' => $shop_code];
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 导出     `introducer_type` int(4) DEFAULT '0' COMMENT '提报类型（1：新客；2：现客；3：老客）',
        if ($data['need'] == 1) {
            // 标记为A客的客资
            $AcustomerInfo = db('c_customerinfo')
                ->where($where)
                ->where('sign_name', 'like', '%A%')
                ->where('sign_time', 'between time', [$date, $next])
                ->field('customer_name,customer_tel,dj_staff,dj_staff_id,dj_day,add_shop_name,access_model,introducer_type,introducer_name,introducer_tel,introducer_number,sign_name,customer_remark,syjd_day,sales_staff,yjd_day,order_day,order_start_time,order_number,totalpay_money,fact_money,reception_name')
                ->select();

            // 已经成为有效订单的
            $OcustomerInfo = db('c_customerinfo')
                ->where($where)
                // ->where('sign_name', 'like', '%A%')
                ->where('order_day', 'between time', [$date, $next])
                ->field('customer_name,customer_tel,dj_staff,dj_staff_id,dj_day,add_shop_name,access_model,introducer_type,introducer_name,introducer_tel,introducer_number,sign_name,customer_remark,syjd_day,sales_staff,yjd_day,order_day,order_start_time,order_number,totalpay_money,fact_money,reception_name')
                ->select();
            $customerInfo = array_merge($AcustomerInfo, $OcustomerInfo);
        } // 展示
        else {
            $page = (int)$data['page'];
            $limit = (int)$data['limit'];
            // $count = db('c_customerinfo')
            //     ->where($where)
            //     ->where('dj_day', 'between time', [$date, $next])
            //     ->count();
            // A客
            $AcustomerInfo = db('c_customerinfo')
                ->where($where)
                ->where('sign_name', 'like', '%A%')
                ->where('sign_time', 'between time', [$date, $next])
                ->limit($limit)->page($page)
                ->field('customer_name,customer_tel,dj_staff,dj_staff_id,dj_day,add_shop_name,access_model,introducer_type,introducer_name,introducer_tel,introducer_number,sign_name,customer_remark,syjd_day,sales_staff,yjd_day,order_start_time,order_number,totalpay_money,fact_money,reception_name')
                ->select();
            // 已经成为有效订单的
            $OcustomerInfo = db('c_customerinfo')
                ->where($where)
                ->where('order_day', 'between time', [$date, $next])
                ->limit($limit)->page($page)
                ->field('customer_name,customer_tel,dj_staff,dj_staff_id,dj_day,add_shop_name,access_model,introducer_type,introducer_name,introducer_tel,introducer_number,sign_name,customer_remark,syjd_day,sales_staff,yjd_day,order_day,order_start_time,order_number,totalpay_money,fact_money,reception_name')
                ->select();
            $customerInfo = array_merge($AcustomerInfo, $OcustomerInfo);
            $count = count($customerInfo);
        }

        $returnData = [];
        foreach ($customerInfo as $key => $value) {
            $staffInfo = getStaffInfoById($value['dj_staff_id']);
            // var_dump($staffInfo);
            $workType = explode(',', $staffInfo['work_type']);
            array_unshift($workType, $staffInfo['main_work_type']);
            $is_in = in_array(MS_WORK_TYPE, $workType);
            // 指名/非营业
            // if ($is_in) {
            if (MS_WORK_TYPE == $staffInfo['main_work_type']) {
                $returnData[$key]['dj_type'] = '指名';
            } else {
                $returnData[$key]['dj_type'] = '非营业';
            }
            // 提交时间
            $returnData[$key]['dj_day'] = $value['dj_day'];
            // 店别
            $returnData[$key]['add_shop_name'] = $value['add_shop_name'];
            // 提报人姓名
            $returnData[$key]['dj_staff'] = $value['dj_staff'];
            // 新顾客姓名
            $returnData[$key]['customer_name'] = $value['customer_name'];
            // 新顾客手机
            $returnData[$key]['customer_tel'] = $value['customer_tel'];
            // 来源渠道
            $returnData[$key]['access_model'] = $value['access_model'];
            // 老顾客姓名
            $returnData[$key]['introducer_name'] = $value['introducer_name'];
            // 老顾客手机
            $returnData[$key]['introducer_tel'] = $value['introducer_tel'];
            // 新/现/老
            switch ($value['introducer_type']) {
                case '1':
                    $returnData[$key]['introducer_type'] = '新客';
                    break;
                case '2':
                    $returnData[$key]['introducer_type'] = '现客';
                    break;
                case '3':
                    $returnData[$key]['introducer_type'] = '老客';
                    break;
            }
            // 老顾客编号
            $returnData[$key]['introducer_number'] = $value['introducer_number'];
            // 客资鉴别  ABCD
            $returnData[$key]['sign_name'] = $value['sign_name'];
            // 备注
            $returnData[$key]['customer_remark'] = $value['customer_remark'];
            // 邀约日期
            $returnData[$key]['syjd_day'] = $value['syjd_day'] ? date('Y-m-d', strtotime($value['syjd_day'])) : '';
            // 邀约人
            $returnData[$key]['sales_staff'] = $value['sales_staff'];
            // 预约进店时间
//            $returnData[$key]['yjd_day']           = !empty($value['syjd_day']) ? date('Y-m-d',strtotime($value['yjd_day'])) : '';
            $returnData[$key]['yjd_day'] = $value['syjd_day'] ? substr($value['syjd_day'], 0, 10) : '';
            // 定单日期
            $returnData[$key]['order_start_time'] = $value['order_start_time'] ? date('Y-m-d', strtotime($value['order_start_time'])) : '';
            // 订单编号
            $returnData[$key]['order_number'] = $value['order_number'];
            // 定单套系金额
            $returnData[$key]['totalpay_money'] = $value['totalpay_money'];
            // 实付金额
            $returnData[$key]['fact_money'] = $value['fact_money'];
            // 接单门市姓名
            $returnData[$key]['reception_name'] = $value['reception_name'];
        }
//         var_dump($returnData);
//         exit;
        if ($data['need'] == 1) {
            $title = array('指名/非营业', '提交时间', '店别/组别', '提报人姓名', '新顾客姓名', '新顾客手机', '渠道名称', '老顾客姓名', '老顾客手机', '新/现/老', '老顾客编号', '客资鉴别', '备注', '邀约日期', '邀约人', '预约进店时间', '定单日期', '订单编号', '定单套系金额', '实付金额', '接单门市姓名');
            $file = 'swCustomerDaily.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = $count;
            $return['data'] = $returnData;
            return json($return);
        }
    }

    // 深挖日报 （页面）
    public function swDaily()
    {
        // 权限控制
        $auth = check_right('menu1514425074');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }

        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));

        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        // month
        $today = date('Y-m-d');
        $this->assign('today', $today);

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('menu', 6);
        $this->assign('title', '深挖日报');
        return $this->fetch();
    }

    // 深挖日报 （数据表格）
    public function swDailyData()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1514425074');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }

        $data = input();
        $page = (int)$data['page'];
        $limit = (int)$data['limit'];

        $brandclass_id = $data['brandclass_id'];
        $shop_code = $data['shop_code'];
        $staff_id = session('staff_id');
        // $brandclass_id = (int)$data['brandclass'];
        // $shop_code = $data['shop'];

        // 时间
        if (!$data['day']) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0];
            return json($return);
        }
        $day = date('Y-m-d', strtotime($data['day']));
        if ($data['consultation_type_id']) {
            $whereC['consultation_type_id'] = $data['consultation_type_id'];
        }
        $whereC['is_status'] = 1;
        $whereC['c_from'] = 1;
        $whereC['shop_code'] = $shop_code;
        $whereC['brandclass_id'] = $brandclass_id;

        $returnData = [];
        $staffs = controller('crm/Statistics', 'lib')->getStaffInfoByShop($shop_code);
        foreach ($staffs as $key => $value) {
            $tomorrow = date("Y-m-d", strtotime('+1 day', strtotime($day)));
            $whereC['sales_staff_id'] = $value['id'];
            $returnData[$key]['staff'] = $value['staffname'];
            $returnData[$key]['date'] = $day;
            // 日获取客资
            $customerNum = db('c_customerinfo')
                ->where($whereC)
                ->where('jr_day', 'between time', [$day, $tomorrow])
                ->count();
            // echo db()->getLastSql();
            // echo '<br />';
            $returnData[$key]['customerNum'] = $customerNum;
            // 日获取A客
            $aCustomer = db('c_customerinfo')
                ->where($whereC)
                ->where('sign_name', 'like', 'A%')
                ->where('sign_time', 'between time', [$day, $tomorrow])
                ->count();
            $returnData[$key]['aCustomer'] = $aCustomer;
            // 日A客转化率
            $aRate = round($aCustomer / $customerNum, 2);
            if ($aRate === false) {
                $returnData[$key]['aRate'] = 0;
            } else {
                $returnData[$key]['aRate'] = $aRate;
            }
            // 日新单量
            $returnData[$key]['newOrder'] = db('c_customerinfo')
                ->where($whereC)
                ->where('order_start_time', 'between time', [$day, $tomorrow])
                ->count();
            // 当日添加微信
            $returnData[$key]['newWechat'] = db('c_customerinfo')
                ->where($whereC)
                ->where('wechat_time', 'like', $day . '%')
                ->count();
            // 明日邀约数
            $returnData[$key]['tomorrowInv'] = db('c_customerinfo')
                ->where($whereC)
                ->where('yjd_day', 'like', $tomorrow . '%')
                ->count();
        }
        // var_dump($returnData);
        // exit;
        if ($data['need'] == 1) {
            $title = array('日期', '日获取客资', '日获取A客', '日A客转化率', '日新单量', '当日添加微信', '明日邀约数');
            $file = 'swDailyData.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = count($returnData);
            $return['data'] = $returnData;
            return json($return);
        }
    }

    // 深挖月报  (页面)
    public function swReport()
    {
        // 权限
        $auth = check_right('menu1514425150');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));

        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('title', '深挖月报');
        return $this->fetch();
    }

    // 深挖月报 （数据表格）
    public function swReportData()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1514425150');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }

        $data = input();
        // $page = (int)$data['page'];
        // $limit= (int)$data['limit'];

        $day = date('Y-m', strtotime($data['timeArea']));
        $timeArea = explode('-', $day);
        $shop_code = $data['shop_code'];
        // 岗位目标
        $where = [
            'year' => $timeArea[0],
            'month' => $timeArea[1],
            'kpi_id' => 'orderNumber',
            'shop_code' => $shop_code
        ];

        $start = date('Y-m-01', strtotime($day));
        $end = date('Y-m-d', strtotime("$start +1 month -1 day"));

        // 成单量的设定
        $gw = db('s_kpi_staffgoal')->where($where)->select();
        foreach ($gw as $key => $value) {
            // var_dump($value['position_id']);
            // var_dump($value['shop_code']);
            $staffInfo = controller('crm/Statistics', 'lib')->getStaffInfoByPositon($value['position_id'], $value['shop_code']);
            foreach ($staffInfo as $k => $v) {
                // var_dump($v);
                $whereC = [
                    'is_status' => 1,
                    'shop_code' => $value['shop_code'],
                    'sales_staff_id' => $v['id']
                ];
                if ($data['consultation_type_id']) {
                    $whereC['consultation_type_id'] = $data['consultation_type_id'];
                }
                $returnData[$key . $k]['position_name'] = $value['position_name'];
                $returnData[$key . $k]['staffname'] = $v['staffname'];

                // 月获取客资
                $customerNum = db('c_customerinfo')
                    ->where($whereC)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
                $returnData[$key . $k]['customerNum'] = $customerNum;
                // 月获取A客
                $aCustomer = db('c_customerinfo')
                    ->where($whereC)
                    ->where('sign_name', 'like', 'A%')
                    ->where('sign_time', 'between time', [$start, $end])
                    ->count();
                $returnData[$key . $k]['aCustomer'] = $aCustomer;
                // 月A客转化率
                $aRate = round($aCustomer / $customerNum, 2);
                if ($aRate === false) {
                    $returnData[$key . $k]['aRate'] = 0;
                } else {
                    $returnData[$key . $k]['aRate'] = $aRate;
                }
                // 月新单量
                $newOrder = db('c_customerinfo')
                    ->where($whereC)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                $returnData[$key . $k]['newOrder'] = $newOrder;
                // 当月添加微信
                $returnData[$key . $k]['newWechat'] = db('c_customerinfo')
                    ->where($whereC)
                    ->where('wechat_time', 'between time', [$start, $end])
                    ->count();
                // 新单完成比
                $returnData[$key . $k]['newRate'] = round($newOrder / $value['kpi_value'], 2);
                // 目标差
                $returnData[$key . $k]['diff'] = $value['kpi_value'] - $newOrder;
            }
        }
        sort($returnData);
        // var_dump($returnData);
        // exit;
        if ($data['need'] == 1) {
            $title = array('岗位', '员工', '月获取客资', '月获取A客', '月A客转化率', '月新单量', '当月添加微信', '新单完成比', '目标差');
            $file = 'swReportData.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = '';
            $return['data'] = my_sort($returnData, 'id');
            return json($return);
        }
    }

    // 深挖统计  （页面）
    public function swStatistics()
    {
        // 权限控制
        $auth = check_right('menu1514425221');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }

        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));

        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('title', '深挖数据统计');
        return $this->fetch();
    }

    // 深挖统计  （数据表格）
    public function swStatisticsData()
    {
        set_time_limit(0);
        // 权限控制
        $auth = check_right('menu1514425221');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }

        $data = input();
        $shop_code = $data['shop_code'];
        // $page = (int)$data['page'];
        // $limit= (int)$data['limit'];

        $day = date('Y-m', strtotime($data['timeArea']));
        // 月 第一天与最后一天
        $start = date('Y-m-01', strtotime($day));
        $end = date('Y-m-d', strtotime("$start +1 month"));

        $staffInfo = controller('crm/Statistics', 'lib')->getStaffInfoByShop($shop_code);
        // $signs = db('s_tracksign')->where('shop_code', session('shop_code'))->select();

        foreach ($staffInfo as $key => $value) {
            $returnData[$key]['staffname'] = $value['staffname'];
            // var_dump($value);
            $whereC = [
                'c_from' => 1,
                'is_status' => 1,
                'shop_code' => $value['shop_code'],
                'sales_staff_id' => $value['id']
            ];
            if ($data['consultation_type_id']) {
                $whereC['consultation_type_id'] = $data['consultation_type_id'];
            }
            // 客资
            $customerNum = db('c_customerinfo')
                ->where($whereC)
                ->where('dj_day', 'between time', [$start, $end])
                ->count();
            // echo db()->getLastSql();
            // exit;
            $returnData[$key]['customerNum'] = $customerNum;
            // A客
            $aCustomer = db('c_customerinfo')
                ->where($whereC)
                ->where('sign_name', 'like', 'A%')
                ->where('sign_time', 'between time', [$start, $end])
                ->count();
            $returnData[$key]['aCustomer'] = $aCustomer;
            // A客转化率
            $returnData[$key]['aRate'] = round($aCustomer / $customerNum, 2);
//            if ($aRate === false) {
//                $returnData[$key]['aRate'] = 0;
//            }else{
//                $returnData[$key]['aRate'] = $aRate;
//            }
            // 邀约
            $invitation = db('c_customerinfo')
                ->where($whereC)
                ->where('yjd_day', 'between time', [$start, $end])
                ->count();
            $returnData[$key]['invitation'] = $invitation;
            // 邀约转化率
            $invRate = round($invitation / $aCustomer, 2);
            if ($invRate === false) {
                $returnData[$key]['invRate'] = 0;
            } else {
                $returnData[$key]['invRate'] = $invRate;
            }
            // 新单
            $newOrder = db('c_customerinfo')
                ->where($whereC)
                ->where('order_start_time', 'between time', [$start, $end])
                ->count();
            $returnData[$key]['newOrder'] = $newOrder;
            // 新单转化率
            $newOrderRate = round($newOrder / $customerNum, 2);
            if ($newOrderRate === false) {
                $returnData[$key]['newOrderRate'] = 0;
            } else {
                $returnData[$key]['newOrderRate'] = $newOrderRate;
            }
            // 成交率
            $orderRate = round($newOrder / $invitation, 2);
            if ($orderRate === false) {
                $returnData[$key]['orderRate'] = 0;
            } else {
                $returnData[$key]['orderRate'] = $orderRate;
            }
            // B客
            $bCustomer = db('c_customerinfo')
                ->where($whereC)
                ->where('sign_name', 'like', 'B%')
                ->where('sign_time', 'between time', [$start, $end])
                ->count();
            $returnData[$key]['bCustomer'] = $bCustomer;
            // B客转化率
            $bRate = round($bCustomer / $customerNum, 2);
            if ($bRate === false) {
                $returnData[$key]['bRate'] = 0;
            } else {
                $returnData[$key]['bRate'] = $bRate;
            }
            // C客
            $cCustomer = db('c_customerinfo')
                ->where($whereC)
                ->where('sign_name', 'like', 'C%')
                ->where('sign_time', 'between time', [$start, $end])
                ->count();
            $returnData[$key]['cCustomer'] = $cCustomer;
            // C客转化率
            $returnData[$key]['cRate'] = round($cCustomer / $customerNum, 2);
//            if ($cRate === false) {
//                $returnData[$key]['cRate'] = 0;
//            }else{
//                $returnData[$key]['cRate'] = $cRate;
//            }
            // 无效
            $noCustomer = db('c_customerinfo')
                ->where($whereC)
                ->where('sign_name', '无效')
                ->where('sign_time', 'between time', [$start, $end])
                ->count();
            $returnData[$key]['noCustomer'] = $noCustomer;
            // 无效转化率
            $noRate = round($noCustomer / $customerNum, 2);
            if ($noRate === false) {
                $returnData[$key]['noRate'] = 0;
            } else {
                $returnData[$key]['noRate'] = $noRate;
            }
            // 待定
            $ddCustomer = db('c_customerinfo')
                ->where($whereC)
                ->where('sign_name', '待定')
                ->where('sign_time', 'between time', [$start, $end])
                ->count();
            $returnData[$key]['ddCustomer'] = $ddCustomer;
            // 待定转化率
            $ddRate = round($ddCustomer / $customerNum, 2);
            if ($ddRate === false) {
                $returnData[$key]['ddRate'] = 0;
            } else {
                $returnData[$key]['ddRate'] = $ddRate;
            }
        }
        // var_dump($returnData);
        // exit;
        $returnData = my_sort($returnData, 'id');
        if ($data['need'] == 1) {
            $title = array('员工', '提报客资数', 'A客数', 'A客转化率', '邀约', '邀约转化率', '新单', '新单转化率', '成交率', 'B客数', 'B客转化率', 'C客数', 'C客转化率', '无效', '无效转化率', '待定', '待定转化率');
            $file = 'swStatisticsData.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = '';
            $return['data'] = $returnData;
            return json($return);
        }
    }

    // 深挖  各店转化率表  页面
    public function swCustomerChange()
    {
        // 权限控制
        $auth = check_right('menu1517727451');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        // 转介绍客资接入店 list
        $shop = controller('Customer', 'lib')->getShopInfo(array('brandclass' => session('brandclass'), 'is_dig' => 1));
        // ???

        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));

        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));

        // 所有店    列表
        $shopList = controller('crm/Statistics', 'lib')->getShops(session('brandclass_id'));
        $this->assign('shopList', $shopList);

        //客资标记 列表
        $signTemp1 = controller('crm/Setting', 'lib')->gettrackingKmarkerList();
        $signTemp2 = db('c_customerinfo')
            // ->where('add_shop_code', $data['shop'])
            ->where('shop_code', session('shop_code'))
            ->where('sign_id', 'not null')
            ->group('sign_id')
            ->field('sign_id AS id,sign_name AS tracksign')
            ->select();
        $signList = [];

        $temp = array_merge($signTemp1, $signTemp2);

        foreach ($temp as $key => $value) {
            if ($value['id']) {
                $signList[$value['id']]['signId'] = $value['id'];
                $signList[$value['id']]['signName'] = $value['tracksign'];
            }
        }
        $this->assign('signList', $signList);
        // var_dump($signList);
        // exit;

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('title', '渠道  各店转化率表');
        return $this->fetch();
    }

    // 深挖  各店转化率表  数据
    public function swCustomerChangeData()
    {
        set_time_limit(0);
        // 权限控制
        $auth = check_right('menu1517727451');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }

        $data = input();

        $page = (int)$data['page'];
        $limit = (int)$data['limit'];

        if (!$data['timeArea']) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        // 时间区域的  开始和结束  时间
        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d', strtotime($timeArea[1]));
        // if ($end == $start) {
        $end = date('Y-m-d', strtotime('+1 day', strtotime($timeArea[1])));
        // }
        // 根据来源渠道（深挖的渠道就是提报人的部门），shop_code，groupby员工
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        // $where['add_shop_code'] = $data['shop'];

        if ($data['shop_code']) {
            $where['add_shop_code'] = $data['shop_code'];
        }
        if ($data['department']) {
            $where['customer_channel_id'] = $data['department'];
        }
        //客资标记 列表
        $signTemp1 = db('STracksign')->where('shop_code', session('shop_code'))->where('is_delete', 1)->select();
        $signTemp2 = db('c_customerinfo')
            // ->where('add_shop_code', $data['shop'])
            ->where('brandclass_id', $data['brandclass'])
            ->where('sign_id', 'not null')
            ->where($where)
            ->where('sign_time', 'between time', [$start, $end])
            ->group('sign_id')
            ->field('sign_id AS id,sign_name AS tracksign')
            ->select();
        $signList = [];
        $temp = array_merge($signTemp1, $signTemp2);

        foreach ($temp as $key => $value) {
            $signList[$value['id']]['sign_id'] = $value['id'];
            $signList[$value['id']]['sign_name'] = $value['tracksign'];
        }
        // 总数
        $countAll = db('c_customerinfo')
            ->where($where)
            ->where('dj_day', 'between time', [$start, $end])
            ->group('customer_channel_id,dj_staff_id')
            ->count();
        // 客资数  导出
        if ($data['need'] == 1) {
            $staffsAllNum = db('c_customerinfo')
                ->where($where)
                ->where('dj_day', 'between time', [$start, $end])
                ->group('customer_channel_id,dj_staff_id')
                ->column('add_shop_name,customer_channel,dj_staff_id,dj_staff,COUNT(id) AS allNum', 'dj_staff_id');
        } // 查询
        else {
            $staffsAllNum = db('c_customerinfo')
                ->where($where)
                ->where('dj_day', 'between time', [$start, $end])
                ->group('customer_channel_id,dj_staff_id')
                ->limit($limit)->page($page)
                ->column('add_shop_name,customer_channel,dj_staff,COUNT(id) AS allNum', 'dj_staff_id');
        }

        // 标记客资数
        $staffSigns = db('c_customerinfo')
            ->where($where)
            ->where('sign_time', 'between time', [$start, $end])
            ->group('sign_id,dj_staff_id')
            ->column('dj_staff_id,dj_staff,sign_id,sign_name,COUNT(id) AS signNum', 'id');


        // var_dump($staffSignData);
        // exit;
        $staffSignData = [];
        foreach ($staffSigns as $key => $value) {
            if ($value['sign_id']) {
                $staffSignData[$value['dj_staff_id']][$value['sign_id']] = $value['signNum'];
            }
        }
        // print_r($staffSignData);die;
        // 从配置文件里取该店A客的配置id
        $signA = config('signA');
        $aid = $signA[session('shop_code')];

        foreach ($staffsAllNum as $key => $value) {
            // unset($staffsAllNum[$key]['dj_staff_id']);
            $where['dj_staff_id'] = $key;
            // 邀约    实际进店的客资
            $invitation = db('c_customerinfo')
                ->where($where)
                ->where('dj_day', 'between time', [$start, $end])
                ->where('syjd_day', 'not null')
                ->count();
            $staffsAllNum[$key]['invitation'] = $invitation;
            // 新单
            $newOrder = db('c_customerinfo')
                ->where($where)
                ->where('dj_day', 'between time', [$start, $end])
                ->where('order_day', 'not null')
                ->count();
            $staffsAllNum[$key]['newOrder'] = $newOrder;
            // 新单转化率  新单数/客资数
            $newOrderRate = round($newOrder / $value['allNum'] * 100, 2) . '%';
            if ($newOrderRate === false) {
                $staffsAllNum[$key]['newOrderRate'] = 0;
            } else {
                $staffsAllNum[$key]['newOrderRate'] = $newOrderRate;
            }
            // 成交率  新单数/邀约数
            $orderRate = round($newOrder / $invitation * 100, 2) . '%';
            if ($orderRate === false) {
                $staffsAllNum[$key]['orderRate'] = 0;
            } else {
                $staffsAllNum[$key]['orderRate'] = $orderRate;
            }
            // print_r($staffSignData);die;
            foreach ($signList as $k => $v) {
                // 邀约转化率   邀约/A客
                if ($aid == $v['sign_id']) {
                    // $staffsAllNum[$key]['invRate'] = round((int)$staffSignData[$value['dj_staff_id']][$v['sign_id']] / $invitation*100, 2).'%';
                    $staffsAllNum[$key]['invRate'] = round($invitation / (int)$staffSignData[$value['dj_staff_id']][$v['sign_id']] * 100, 2) . '%';
                }
                $staffsAllNum[$key]['sign_' . $v['sign_id']] = (int)$staffSignData[$value['dj_staff_id']][$v['sign_id']];
                $staffsAllNum[$key]['sign_' . $v['sign_id'] . 'Rate'] = round($staffsAllNum[$key]['sign_' . $v['sign_id']] / $value['allNum'] * 100, 2) . '%';
            }
        }

        if ($data['need'] == 1) {
            $title = array('ID', '提报店', '渠道名称', '提报人', '客资数', '邀约数量', '新单', '新单转化率', '成交率', '邀约转化率');
            foreach ($signList as $key => $value) {
                array_push($title, $value['sign_name'], $value['sign_name'] . '转化率');
            }
            $file = 'swCustomerChangeData.xlsx';
            sort($staffsAllNum);
            // var_dump($title);
            // var_dump($staffsAllNum);
            // exit;
            controller("crm/Customer", "lib")->export($title, $staffsAllNum, $file);
        } else {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = $countAll;
            $return['data'] = $staffsAllNum;
            return json($return);
        }
    }

    // 统计毛客资量  页面
    public function dj_customer()
    {
        // 权限控制
        $auth = check_right('menu1512897388');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        $shop_code = session('shop_code');
        // 获取该店面下的部门
        $deparments = controller('crm/Statistics', 'lib')->getdeparments($shop_code);

        $today = date('Y-m-d') . ' - ' . date('Y-m-d');
        $this->assign('today', $today);
        // $deparmentData = controller('crm/Statistics', 'lib')->djCustomerNum($deparments);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        switch (session('is_belong')) {
            case '1'://集团
                $shops = controller('crm/Customer', 'lib')->get_shop();
                break;
            case '2'://事业部
                $shops = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
                break;
            case '3'://店
            case '4'://部门
            default:
                $shops = controller('crm/Customer', 'lib')->get_shop(['shop_code' => session('shop_code')]);
                break;
        }
        $this->assign('shops', $shops);
        $this->assign('deparments', $deparments);
        $this->assign('title', '统计分析 毛客资量');
        return $this->fetch();
    }

    // 毛客资量    统计表格   该门店下所有的部门的毛客资统计表
    public function dj_customer_json()
    {
        set_time_limit(0);
        // 权限控制
        $auth = check_right('menu1512897388');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        // 时间段
        // if (!$data['timeArea']) {
        //     $return = ['code'=>0,'msg'=>'','count'=>0,'data'=>''];
        //     return json($return);
        // }

        $shop_code = $data['shop_code'];
        // 存在员工，查员工
        if ($data['staff']) {
            $djCustomer = controller('crm/Statistics', 'lib')->getDjCustomerByStaffid($shop_code, $data);
            // var_dump($djCustomer);
            if ($data['need'] == 1) {
                $title = array('事业部', '提报部门', '提报小组', '提报日期', '提报人', '新顾客姓名', '顾客联系电话', '提报类型', '标记类型', '介绍人编号', '介绍人姓名', '介绍人电话', '是否进店', '进店时间', '成交金额', '备注事项');
                $explodeData = $djCustomer['data'];
                $file = 'customer.xlsx';
                controller("crm/Customer", "lib")->export($title, $explodeData, $file);
            } else {
                return json($djCustomer);
            }

        }
        // 员工不存在，组存在，查组
        if (!$data['staff'] && $data['group']) {
            $djCustomer = controller('crm/Statistics', 'lib')->getDjCustomerByGroupid($shop_code, $data);
            if ($data['need'] == 1) {

                $title = array('事业部', '提报部门', '提报小组', '提报日期', '提报人', '新顾客姓名', '顾客联系电话', '提报类型', '标记类型', '介绍人编号', '介绍人姓名', '介绍人电话', '是否进店', '进店时间', '成交金额', '备注事项');
                $explodeData = $djCustomer['data'];
                $file = 'customer.xlsx';
                controller("crm/Customer", "lib")->export($title, $explodeData, $file);
            } else {
                return json($djCustomer);
            }
        }
        // 员工不存在，组不存在，部门存在，查部门
        if (!$data['staff'] && !$data['group'] && $data['department']) {
            $djCustomer = controller('crm/Statistics', 'lib')->getDjCustomerByDepartmentid($shop_code, $data);
            if ($data['need'] == 1) {
                $title = array('事业部', '提报部门', '提报小组', '提报日期', '提报人', '新顾客姓名', '顾客联系电话', '提报类型', '标记类型', '介绍人编号', '介绍人姓名', '介绍人电话', '是否进店', '进店时间', '成交金额', '备注事项');
                $explodeData = $djCustomer['data'];

                $file = 'customer.xlsx';
                controller("crm/Customer", "lib")->export($title, $explodeData, $file);
            } else {
                return json($djCustomer);
            }
        }
        // 如果部门，小组，员工，全部为空（默认）该门店下所有的部门的毛客资统计表
        if (!$data['department'] && !$data['group'] && !$data['staff']) {
            $djCustomer = controller('crm/Statistics', 'lib')->getDjCustomer($shop_code, $data);
            if ($data['need'] == 1) {
                $title = array('事业部', '提报部门', '提报小组', '提报日期', '提报人', '新顾客姓名', '顾客联系电话', '提报类型', '标记类型', '介绍人编号', '介绍人姓名', '介绍人电话', '是否进店', '进店时间', '成交金额', '备注事项');
                $explodeData = $djCustomer['data'];
                $file = 'customer.xlsx';
                controller("crm/Customer", "lib")->export($title, $explodeData, $file);
            } else {
                return json($djCustomer);
            }
        }
        // exit;
    }

    // 根据选择 获取 数据  生成柱状图
    public function getNewPicForDjcus()
    {
        $data = input('post.');
        $shop_code = $data['shop_code'];
        // 存在员工，查员工
        if ($data['staff']) {
            $res = controller('crm/Statistics', 'lib')->getNewPicForStaff($data['staff'], $data['timeArea'], $data['consultation_type_id'], $shop_code);
            $name = controller('crm/Statistics', 'lib')->getStaffInfo($data['staff']);
            $names = [$name];
            $res['names'] = $names;
            $res['data'][0]['names'] = $name;
            return json($res);
        }
        // exit;
        // 员工不存在，组存在，查组
        if (!$data['staff'] && $data['group']) {
            $res = controller('crm/Statistics', 'lib')->getNewPicForGroup($data['group'], $data['timeArea'], $data['consultation_type_id'], $shop_code);
            // var_dump($res);
            return json($res);
        }
        // exit;
        // 员工不存在，组不存在，部门存在，查部门
        if (!$data['staff'] && !$data['group'] && $data['department']) {
            $res = controller('crm/Statistics', 'lib')->getNewPicForDepartment($data['department'], $data['timeArea'], $data['consultation_type_id'], $shop_code);
            return json($res);
        }
        // exit;
        // 如果部门，小组，员工，全部为空，加载默认
        if (!$data['department'] && !$data['group'] && !$data['staff']) {
            // 获取该店面下的部门
            $deparments = controller('crm/Statistics', 'lib')->getdeparments($shop_code);
            // 获取该店面下的  每个部门  毛客资量
            $res = controller('crm/Statistics', 'lib')->djCustomerNum($deparments, $data['timeArea'], $data['consultation_type_id'], $shop_code);
            return json($res);
            // $this->redirect('dj_customer');
        }
        exit;
    }

    // 有效客资量  页面
    public function valid_customer()
    {
        // 权限控制
        // $auth = check_right('');
        // iif (!$auth) {
        //     controller('crm/Index','controller')->index();
        //     exit;
        // }

        $shop_code = session('shop_code');
        // 获取该店面下的部门
        $deparments = controller('crm/Statistics', 'lib')->getdeparments($shop_code);
        // $deparmentData = controller('crm/Statistics', 'lib')->djCustomerNum($deparments);
        // var_dump($deparmentData);
        // exit;
        $this->assign('deparments', $deparments);
        $this->assign('title', '统计 有效客资量');
        return $this->fetch();
    }

    // 电商报表==》渠道漏斗  页面
    public function ds_channelLd()
    {
        // 权限
        $auth = check_right('menu1519826594');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        switch (session('is_belong')) {
            case '1'://集团
                $shops = controller('crm/Customer', 'lib')->get_shop();
                break;
            case '2'://事业部
                $shops = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
                break;
            case '3'://店
            case '4'://部门
            default:
                $shops = controller('crm/Customer', 'lib')->get_shop(['shop_code' => session('shop_code')]);
                break;
        }
        $this->assign('shops', $shops);
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //来源渠道
        $channel = controller("Customer", "lib")->getChannel();
        $this->assign("channel", $channel);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        $this->assign('title', '渠道漏斗统计');
        return $this->fetch();
    }

    // 电商报表==》渠道漏斗  数据
    public function channelLdData()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1519826594');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();

        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d 00:00:00', strtotime($timeArea[0]));
        $end = date('Y-m-d 23:59:59', strtotime($timeArea[1]));
        $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $where['is_status'] = 1;
        $where['customer_type'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        // 地域id，拼接where条件
        if ($data['province']) {
            $where['province_id'] = (int)$data['province'];
            $whereC['province_id'] = (int)$data['province'];
        }
        if ($data['city']) {
            $where['city_id'] = (int)$data['city'];
            $whereC['city_id'] = (int)$data['city'];
        }
//        if ($data['consultation_type_id']) {
//            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
//        }
        $consultation_type_info = db('s_sta_setting')->where('shop_code', $shop_code)->find();
        $all = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['all_customer_consumptiontype']) {
                $all->where('c.consultation_type_id', 'in', $consultation_type_info['all_customer_consumptiontype']);
            }
        }
        $valid = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['valid_customer_consumptiontype']) {
                $valid->where('c.consultation_type_id', 'in', $consultation_type_info['valid_customer_consumptiontype']);
            }
        }
        $into = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['into_customer_consumptiontype']) {
                $into->where('c.consultation_type_id', 'in', $consultation_type_info['into_customer_consumptiontype']);
            }
        }
        $order = db('c_customerinfo')->alias('c');
        $order1 = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['ordder_customer_consumptiontype']) {
                $order->where('c.consultation_type_id', 'in', $consultation_type_info['order_customer_consumptiontype']);
                $order1->where('c.consultation_type_id', 'in', $consultation_type_info['order_customer_consumptiontype']);
            }
        }

        $group = 's.id';
        $channels = '';
        if ($data['channel'] == true) {
            if ($data['channel_id']) {
                $channels = db('s_channel')->where('id', $data['channel_id'])->select();
            } else {
                // 来源渠道
                $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
            }
            $group = 's.id';
            $cKey = 's.id';
        } else {
            $url = '59fd5e729e5a8';
            $res = sx_call($url, []);
            if ($res['code'] != 200) {
                $return = ['code' => 150, 'msg' => '来源渠道查询失败', 'count' => 0, 'data' => '',];
                return json($return);
            } else {
                $channels = $res['data'];
            }
            $group = ' s.channel_info_id ';
            $cKey = 's.channel_info_id';
        }
//        print_r($channels);die;
        // 花费
        if($data['channel']){
            $channelCost = db('s_channel_cost')->alias('c')
                ->where($whereC)
                ->where('c.cost_date', 'between time', [$start, $end])
                ->where('c.shop_code', $shop_code)
                ->group('c.channel_id')
                ->column('sum(c.cost) as cost,c.id,c.channel_class_name,c.channel_info_name,c.channel_info_id','c.channel_id');
        }else{
            $channelCost = db('s_channel_cost')->alias('c')
                ->where($whereC)
                ->where('c.cost_date', 'between time', [$start, $end])
                ->where('c.shop_code', $shop_code)
                ->group('c.channel_info_id')
                ->column('sum(c.cost) as cost,c.id,c.channel_class_name,c.channel_info_name,c.channel_info_id','c.channel_info_id');
        }


        // 录入客资量
        $allCustomer = $all->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.dj_day', 'between time', [$start, $end])
            ->group($group)
            ->column('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);

        // 有效客资量
        $validCustomer = $valid->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.customer_type', 1)
            ->where('c.is_valid', 1)
            ->where('c.yx_day', 'between time', [$start, $end])
            ->group($group)
            ->column('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);
        // 总手机  手机号不为空的客资总数（按录入时间计算）
        $allTel = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('is_valid',1)
            ->where('c.customer_tel', '<>', '')
            ->where('c.dj_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);
        // 进店数量
        $intoNum = $into->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.customer_type', 1)
            ->where('c.is_intostore', 'in', '2,3')
            ->where('c.syjd_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);
        // 有效订单 数

        $orderNum = $order->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.customer_type', 1)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);
        // 营收（实际收入  不区分有效无效）
        $factMoney = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('order_start_time', 'between time', [$start, $end])
//            ->field('sum(c.fact_money),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('sum(c.fact_money) as fact_money,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);
        // 套系均值（有效单套系应收款均值）
        $order_amount_avg = $order1->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.customer_type', 1)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
//            ->field('avg(c.totalpay_money),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('avg(c.totalpay_money) as totalpay_money,s.channel_name,s.channel_class_name,s.channel_info_name', $cKey);
        $returnData = [];
        $arr = [];
        $arr['id'] = '';
        $arr['channel_info_name'] = '';
        $arr['channel_name'] = '总计';
        foreach ($channels as $k => $v) {
            $returnData[$k]['id'] = $v['id'];
//            $returnData[$k]['channel_class_name'] = $v['channelclass'];
            if ($data['channel'] == true) {
                $returnData[$k]['channel_info_name'] = $v['channel_info_name'];
                $returnData[$k]['channel_name'] = $v['channel_name'];
            }else{
                $returnData[$k]['channel_info_name'] = $v['channel_name'];
                $returnData[$k]['channel_name'] = '';
            }

            $returnData[$k]['id'] = $v['id'];
            $returnData[$k]['channelCost'] = $channelCost[$v['id']]['cost'] ? sprintf('%.2f',$channelCost[$v['id']]['cost']) : 0;
            $returnData[$k]['lrCustomer'] = $allCustomer[$v['id']]['num'] ? $allCustomer[$v['id']]['num'] : 0;
            $returnData[$k]['invCustomer'] = $validCustomer[$v['id']]['num'] ? $validCustomer[$v['id']]['num'] : 0;
            $returnData[$k]['allTel'] = $allTel[$v['id']]['num'] ? $allTel[$v['id']]['num'] : 0;
            $returnData[$k]['intoNum'] = $intoNum[$v['id']]['num'] ? $intoNum[$v['id']]['num'] : 0;
            $returnData[$k]['orderNum'] = $orderNum[$v['id']]['num'] ? $orderNum[$v['id']]['num'] : 0;
            $returnData[$k]['factMoney'] = $factMoney[$v['id']]['fact_money'] ? $factMoney[$v['id']]['fact_money'] : 0;
            $returnData[$k]['orderAmountAvg'] = $order_amount_avg[$v['id']]['totalpay_money'] ?
                sprintf('%.2f',$order_amount_avg[$v['id']]['totalpay_money']) : 0;
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$k]['invRate'] = (sprintf('%.2f', $returnData[$k]['invCustomer'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            // 进店率（ 实际进店 / 有效获取 ）
            $returnData[$k]['intoRate'] = (sprintf('%.2f', $returnData[$k]['intoNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$k]['orderRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['intoNum'] * 100)) . '%';
            // 转化率（ 有效新单 / 有效获取 ）
            $returnData[$k]['changeRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 毛客资成本
            $returnData[$k]['customerCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['lrCustomer']);
            // 有效获取成本
            $returnData[$k]['invCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['invCustomer']);
            // 新单成本
            $returnData[$k]['orderCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['orderNum']);
            // ROI（实收：花费）(营收)
            $returnData[$k]['ROI'] = sprintf('%.2f',intval($returnData[$k]['factMoney'])/intval
                ($returnData[$k]['channelCost'])).':1';
//            foreach($channels as $key=>$val){

            $arr['channelCost'] += $channelCost[$v['id']]['cost'];   // 花费总计
            $arr['lrCustomer']  += $allCustomer[$v['id']]['num'];    // 录入总计
            $arr['invCustomer'] += $validCustomer[$v['id']]['num'];   // 有效总计
//                $arr['hsValid'] += $returnData[$k]['hsValid'];   // 婚纱有效总计
            $arr['allTel']      += $allTel[$v['id']]['num'];        // 总手机总计
            $arr['intoNum']     += $intoNum[$v['id']]['num'];       // 进店总计
            $arr['orderNum']    += $orderNum[$v['id']]['num'];      // 订单总计
            $arr['factMoney']   += $factMoney[$v['id']]['fact_money']; // 营收总计
//            }
        }
        $arr['channelCost'] = sprintf('%.2f',$arr['channelCost']);
        array_push($returnData,$arr);
//        print_r($returnData);die;
//        echo db()->getLastSql();die;


        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channels);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = array('序号', '渠道类型', '来源渠道', '渠道名称', '花费', '毛客资', '有效客获取', '婚纱有效', '总手机', '邀约进店', '有效订单', '营收', '套系均值', '有效率', '进店率', '成交率', '转化率', '毛客资成本', '有效获取成本', '新单成本', 'ROI');
            $file = '渠道漏斗统计.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
    }

    // 电商报表==》地域漏斗  页面
    public function ds_regionLd()
    {
        // 权限
        $auth = check_right('menu1519826642');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        switch (session('is_belong')) {
            case '1'://集团
                $shops = controller('crm/Customer', 'lib')->get_shop();
                break;
            case '2'://事业部
                $shops = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
                break;
            case '3'://店
            case '4'://部门
            default:
                $shops = controller('crm/Customer', 'lib')->get_shop(['shop_code' => session('shop_code')]);
                break;
        }
        $this->assign('shops', $shops);
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        // 消费类型
        $consumptionType = controller('crm/Customer', 'lib')->consumptionType();
        $this->assign('consumptionType', $consumptionType);

        $this->assign('title', '地域漏斗统计');
        return $this->fetch();
    }

    // 电商报表==》地域漏斗  数据
    public function regionLdData()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1519826642');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d 00:00:00', strtotime($timeArea[0]));
        $end = date('Y-m-d 23:59:59', strtotime($timeArea[1]));

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $data['shop_code'];
//        $whereT = [];
//        if ($data['consumptionType']) {
//            $whereT['consultation_type_id'] = (int)$data['consumptionType'];
//        }
        $consultation_type_info = db('s_sta_setting')->where('shop_code', $data['shop_code'])->find();
        $all = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['all_customer_consumptiontype']) {
                $all->where('consultation_type_id', 'in', $consultation_type_info['all_customer_consumptiontype']);
            }
        }
        $valid = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['valid_customer_consumptiontype']) {
                $valid->where('consultation_type_id', 'in', $consultation_type_info['valid_customer_consumptiontype']);
            }
        }
        $into = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['into_customer_consumptiontype']) {
                $into->where('consultation_type_id', 'in', $consultation_type_info['into_customer_consumptiontype']);
            }
        }
        $order = db('c_customerinfo');
        $order1 = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['ordder_customer_consumptiontype']) {
                $order->where('consultation_type_id', 'in', $consultation_type_info['order_customer_consumptiontype']);
                $order1->where('consultation_type_id', 'in', $consultation_type_info['order_customer_consumptiontype']);
            }
        }
        if ($data['channel']) {
            if ($data['province_id']) {
                $province_id = intval($data['province_id']);
                $where['province_id'] = $province_id;
                // 城市列表
                $city = db('s_shop_address')->where('shop_code', $data['shop_code'])->where('pid', $province_id)->where('type', 2)->select();
                if ($data['city_id']) {
                    $city_id = intval($data['city_id']);
                    $where['city_id'] = $city_id;
                    // 城市列表
                    $city = [
                        [
                            'id' => $city_id,
                            'name' => $data['city_name'] ? $data['city_name'] : '',
                        ]
                    ];
                }
            } else {
                // 城市列表
                $city = db('s_shop_address')->where('shop_code', $data['shop_code'])->where('type', 2)->select();
            }
            $group = 'city_id';
            $field = 'city';
        } else {
            $city = controller("Customer", "lib")->address(['type' => 1]);//省
            $group = 'province_id';
            $field = 'province';
        }
        if ($data['channel']) {
            // 花费
            $channelCost = db('s_channel_cost')->alias('c')
                ->where('c.cost_date', 'between time', [$start, $end])
                ->where('c.shop_code', $data['shop_code'])
                ->group('city_id')
                ->column('sum(c.cost) as cost,c.city_name', 'c.city_id');
        } else {
            // 花费
            $channelCost = db('s_channel_cost')->alias('c')
                ->where('c.cost_date', 'between time', [$start, $end])
                ->where('c.shop_code', $data['shop_code'])
                ->group('province_id')
                ->column('sum(c.cost) as cost,c.province_name', 'c.province_id');
        }

        // 录入客资量
        $allCustomer = $all
            ->where($where)
            ->where('dj_day', 'between time', [$start, $end])
            ->group($group)
            ->column('count(id) as num,'.$field, $group);

        // 有效客资量
        $validCustomer = $valid
            ->where($where)
            ->where('customer_type', 1)
            ->where('is_valid', 1)
            ->where('yx_day', 'between time', [$start, $end])
//            ->field('count(c.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 总手机  手机号不为空的客资总数（按录入时间计算）
        $allTel = db('c_customerinfo')
            ->where($where)
            ->where('is_valid', 1)
            ->where('customer_tel', '<>', '')
            ->where('dj_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 进店数量
        $intoNum = $into
            ->where($where)
            ->where('customer_type', 1)
            ->where('is_intostore', 'in', '2,3')
            ->where('syjd_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 有效订单 数

        $orderNum = $order
            ->where($where)
            ->where('customer_type', 1)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
//            ->field('count(c.id),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('count(id) as num,'.$field, $group);
        // 营收（实际收入  不区分有效无效）
        $factMoney = db('c_customerinfo')
            ->where($where)
            ->where('order_start_time', 'between time', [$start, $end])
//            ->field('sum(c.fact_money),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('sum(fact_money) as fact_money,'.$field, $group);
        // 套系均值（有效单套系应收款均值）
        $order_amount_avg = $order1
            ->where($where)
            ->where('customer_type', 1)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
//            ->field('avg(c.totalpay_money),s.channel_name,s.channel_class_name,s.channel_info_name')
            ->group($group)
            ->column('avg(totalpay_money) as totalpay_money,'.$field,$group);
        $returnData = [];
        $arr = [];
        $arr['id'] = '';
        $arr['name'] = '总计';
        foreach ($city as $k => $v) {
            $returnData[$k]['name'] = $v['name'];
            $returnData[$k]['channelCost'] = $channelCost[$v['id']]['cost'] ? sprintf('%.2f', $channelCost[$v['id']]['cost']) : 0;
            $returnData[$k]['lrCustomer'] = $allCustomer[$v['id']]['num'] ? $allCustomer[$v['id']]['num'] : 0;
            $returnData[$k]['invCustomer'] = $validCustomer[$v['id']]['num'] ? $validCustomer[$v['id']]['num'] : 0;
            $returnData[$k]['allTel'] = $allTel[$v['id']]['num'] ? $allTel[$v['id']]['num'] : 0;
            $returnData[$k]['intoNum'] = $intoNum[$v['id']]['num'] ? $intoNum[$v['id']]['num'] : 0;
            $returnData[$k]['orderNum'] = $orderNum[$v['id']]['num'] ? $orderNum[$v['id']]['num'] : 0;
            $returnData[$k]['factMoney'] = $factMoney[$v['id']]['fact_money'] ? $factMoney[$v['id']]['fact_money'] : 0;
            $returnData[$k]['orderAmountAvg'] = $order_amount_avg[$v['id']]['totalpay_money'] ?
                sprintf('%.2f',$order_amount_avg[$v['id']]['totalpay_money']) : 0;
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$k]['invRate'] = (sprintf('%.2f', $returnData[$k]['invCustomer'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            // 进店率（ 实际进店 / 有效获取 ）
            $returnData[$k]['intoRate'] = (sprintf('%.2f', $returnData[$k]['intoNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$k]['orderRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['intoNum'] * 100)) . '%';
            // 转化率（ 有效新单 / 有效获取 ）
            $returnData[$k]['changeRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 毛客资成本
            $returnData[$k]['customerCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['lrCustomer']);
            // 有效获取成本
            $returnData[$k]['invCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['invCustomer']);
            // 新单成本
            $returnData[$k]['orderCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['orderNum']);
            // ROI（实收：花费）(营收)
//                $HSfactMoney = db('c_customerinfo')
//                    ->where($where1)
//                    ->where('order_day', 'between time', [$start, $end])
//                    ->sum('fact_money');
            $returnData[$k]['ROI'] =  $returnData[$k]['ROI'] = sprintf('%.2f',intval($returnData[$k]['factMoney'])/intval
                    ($returnData[$k]['channelCost'])).':1';
//            foreach($channels as $key=>$val){

            $arr['channelCost'] += $channelCost[$v['id']]['cost'];   // 花费总计
            $arr['lrCustomer']  += $allCustomer[$v['id']]['num'];    // 录入总计
            $arr['invCustomer'] += $validCustomer[$v['id']]['num'];   // 有效总计
//                $arr['hsValid'] += $returnData[$k]['hsValid'];   // 婚纱有效总计
            $arr['allTel']      += $allTel[$v['id']]['num'];        // 总手机总计
            $arr['intoNum']     += $intoNum[$v['id']]['num'];       // 进店总计
            $arr['orderNum']    += $orderNum[$v['id']]['num'];      // 订单总计
//            $arr['factMoney']   += $factMoney[$v['id']]['fact_money']; // 营收总计
//            }
        }
        $arr['channelCost'] = sprintf('%.2f',$arr['channelCost']);
        array_push($returnData,$arr);






        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($city);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = array('地域', '花费', '毛客资', '有效获取', '总手机', '邀约进店', '有效订单', '营收', '套系均值', '有效率', '进店率', '成交率', '转化率', '毛客资成本', '有效获取成本', '新单成本', 'ROI');
            $file = '地域漏斗统计.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
    }

    //电商统计日报--常态报表1   页面
    public function ds_sta_day()
    {
        // 权限
        $auth = check_right('menu1521352296');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);

        $today = $end_time = date('Y-m-d');
        $start_time = getWeekStartTimeNotFrontMonth();
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        // print_r($lists);die;
        $this->assign('today', $today);
        $this->assign('next_day', $start_time . '-' . $today);
        return $this->fetch();
    }

    //电商统计日报
    public function ds_sta_day_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1521352296');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）'];
            return json($return);
        }
//        $end_time= date('Y-m-d 23:59:59');
//        $start_time = getWeekStartTimeNotFrontMonth();
        $beginLastweek = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y'));
        $endLastweek = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
        $start_time = date('Y-m-d H:i:s', $beginLastweek);
        $end_time = date('Y-m-d H:i:s', $endLastweek);
        //通过页面获取的shop_code获取归属店的shop_code
        $shopCodes = sx_call('5a005e0038270', ['belong_shop_code' => $shop_code]);
        if ($shopCodes['code'] == 200) {
            $shopCodes = array_unique(array_column($shopCodes['data'], 'shop_code'));
        } else {
            $shopCodes = $shop_code;
        }
        $dataToday = array(
            'start' => date('Y-m-d', strtotime('-1 day')),
            'end' => date('Y-m-d'),
            'add_shop_code' => $shopCodes,
            'brandclass_id' => $brandclass_id,
        );
        $dataWeek = array(
            'start' => $start_time,
            'end' => $end_time,
            'add_shop_code' => $shopCodes,
            'brandclass_id' => $brandclass_id,
        );
        if ($data['consultation_type_id']) {
            $dataToday['consultation_type_id'] = $data['consultation_type_id'];
            $dataWeek['consultation_type_id'] = $data['consultation_type_id'];
        }
        $total = array();
        $total[0][0] = '时间';
        $total[0][1] = date('Y-m-d', strtotime('-1 day'));
        $total[0][2] = date('Y-m-d', $beginLastweek) . ' — ' . date('Y-m-d', $endLastweek);
        //花费
        $total[1][0] = '花费';
        $total[1][1] = controller('crm/Statistics', 'lib')->sta_costMoney($dataToday);
        $total[1][2] = controller('crm/Statistics', 'lib')->sta_costMoney($dataWeek);

        //毛客资
        $total[2][0] = '毛客资';
        $total[2][1] = controller('crm/Statistics', 'lib')->sta_getCustomerNum($dataToday);
        $total[2][2] = controller('crm/Statistics', 'lib')->sta_getCustomerNum($dataWeek);

        //有效获取
        $total[3][0] = '有效获取';
        $total[3][1] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($dataToday);
        $total[3][2] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($dataWeek);
        //获取手机
        $total[4][0] = '获取手机';
        $total[4][1] = controller('crm/Statistics', 'lib')->sta_getTelCustomerNum($dataToday);
        $total[4][2] = controller('crm/Statistics', 'lib')->sta_getTelCustomerNum($dataWeek);

        //进店
        $total[5][0] = '进店';
        $total[5][1] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($dataToday);
        $total[5][2] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($dataWeek);
        //订单
        $total[6][0] = '订单';
        $total[6][1] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($dataToday);
        $total[6][2] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($dataWeek);

        //成交金额
        $total[7][0] = '成交金额';

        $total[7][1] = controller('crm/Statistics', 'lib')->sta_dealMoney($dataToday);
        $total[7][2] = controller('crm/Statistics', 'lib')->sta_dealMoney($dataWeek);
        //营收
        $total[8][0] = '营收';
        $total[8][1] = controller('crm/Statistics', 'lib')->sta_incomeMoney($dataToday);
        $total[8][2] = controller('crm/Statistics', 'lib')->sta_incomeMoney($dataWeek);

        //成交平均 订单总收入/有效订单数
        $total[9][0] = '成交平均';
        $total[9][1] = sprintf('%.2f', $total[7][1] / $total[6][1]);
        $total[9][2] = sprintf('%.2f', $total[7][2] / $total[6][2]);
        //获取成本 花费/有效客资
        $total[10][0] = '获取成本';
        $total[10][1] = sprintf('%.2f', $total[1][1] / $total[3][1]);
        $total[10][2] = sprintf('%.2f', $total[1][2] / $total[3][2]);
        //成交成本  花费/订单数(有效)
        $total[11][0] = '成交成本';
        $total[11][1] = sprintf('%.2f', $total[1][1] / $total[6][1]);
        $total[11][2] = sprintf('%.2f', $total[1][2] / $total[6][2]);
        //转化率 有效订单/有效客资
        $total[12][0] = '转化率(有效订单/有效客资)';
        $total[12][1] = sprintf('%.2f', ($total[6][1] / $total[3][1]) * 100) . '%';
        $total[12][2] = sprintf('%.2f', ($total[6][2] / $total[3][2]) * 100) . '%';
        //毛客资转化率 有效订单/毛客资
        $total[13][0] = '毛客资转化率';
        $total[13][1] = sprintf('%.2f', ($total[6][1] / $total[2][1]) * 100) . '%';
        $total[13][2] = sprintf('%.2f', ($total[6][2] / $total[2][2]) * 100) . '%';
        // 导出
        if ($data['need'] == 1) {
            $title = array('统计名目', '当天', '本周');

            $file = '电商数据日报-常态报表1.xlsx';
            controller("crm/Customer", "lib")->export($title, $total, $file);
        } else {
            $return = ['code' => 1, 'msg' => '', 'count' => 0, 'data' => $total];
            return json($return);
        }
    }

    //电商统计月报--常态报表2   页面
    public function ds_sta_month()
    {
        // 权限
        $auth = check_right('menu1521352325');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);

        $today = $end_time = date('Y-m-d');
        $start_time = getWeekStartTimeNotFrontMonth();
        // print_r($lists);die;
        $this->assign('today', $today);
        $this->assign('next_day', $start_time . '-' . $today);

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        return $this->fetch();
    }

    //电商统计月报
    public function ds_sta_month_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1521352325');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）'];
            return json($return);
        }
        $end_time = date('Y-m-d 23:59:59');
        $start_time = getWeekStartTimeNotFrontMonth();
        //通过页面获取的shop_code获取归属店的shop_code
        $shopCodes = sx_call('5a005e0038270', ['belong_shop_code' => $shop_code]);
        if ($shopCodes['code'] == 200) {
            $shopCodes = array_unique(array_column($shopCodes['data'], 'shop_code'));
        } else {
            $shopCodes = $shop_code;
        }
        $beginThismonth = date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));

        $endThismonth = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m'), date('t'), date('Y')));
        $dataWeek = array(
            'start' => $start_time,
            'end' => $end_time,
            'add_shop_code' => $shopCodes,
            'brandclass_id' => $brandclass_id,
        );
        $dataMonth = array(
            'start' => $beginThismonth,
            'end' => $endThismonth,
            'add_shop_code' => $shopCodes,
            'brandclass_id' => $brandclass_id,
        );
        if ($data['consultation_type_id']) {
            $dataWeek['consultation_type_id'] = $data['consultation_type_id'];
            $dataMonth['consultation_type_id'] = $data['consultation_type_id'];
        }
        $total = array();
        $total[0][0] = '时间';
        $total[0][1] = $start_time . ' — ' . date('Y-m-d');
        $total[0][2] = $beginThismonth . ' — ' . date('Y-m-d', strtotime($endThismonth));
        //花费
        $total[1][0] = '花费';
        $total[1][1] = controller('crm/Statistics', 'lib')->sta_costMoney($dataWeek);
        $total[1][2] = controller('crm/Statistics', 'lib')->sta_costMoney($dataMonth);


        //毛客资
        $total[2][0] = '毛客资';
        $total[2][1] = controller('crm/Statistics', 'lib')->sta_getCustomerNum($dataWeek);
        $total[2][2] = controller('crm/Statistics', 'lib')->sta_getCustomerNum($dataMonth);

        //有效获取
        $total[3][0] = '有效获取';
        $total[3][1] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($dataWeek);
        $total[3][2] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($dataMonth);
        //获取手机
        $total[4][0] = '获取手机';
        $total[4][1] = controller('crm/Statistics', 'lib')->sta_getTelCustomerNum($dataWeek);
        $total[4][2] = controller('crm/Statistics', 'lib')->sta_getTelCustomerNum($dataMonth);

        //进店
        $total[5][0] = '进店';
        $total[5][1] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($dataWeek);
        $total[5][2] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($dataMonth);

        //订单
        $total[6][0] = '订单';
        $total[6][1] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($dataWeek);
        $total[6][2] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($dataMonth);

        //成交金额
        $total[7][0] = '成交金额';

        $total[7][1] = controller('crm/Statistics', 'lib')->sta_dealMoney($dataWeek);
        $total[7][2] = controller('crm/Statistics', 'lib')->sta_dealMoney($dataMonth);
        //营收
        $total[8][0] = '营收';
        $total[8][1] = controller('crm/Statistics', 'lib')->sta_incomeMoney($dataWeek);
        $total[8][2] = controller('crm/Statistics', 'lib')->sta_incomeMoney($dataMonth);

        //成交平均 订单总收入/有效订单数
        $total[9][0] = '成交平均';
        $total[9][1] = sprintf('%.2f', $total[7][1] / $total[6][1]);
        $total[9][2] = sprintf('%.2f', $total[7][2] / $total[6][2]);
        //获取成本 花费/有效客资
        $total[10][0] = '获取成本';
        $total[10][1] = sprintf('%.2f', $total[1][1] / $total[3][1]);
        $total[10][2] = sprintf('%.2f', $total[1][2] / $total[3][2]);
        //成交成本  花费/订单数(有效)
        $total[11][0] = '成交成本';
        $total[11][1] = sprintf('%.2f', $total[1][1] / $total[6][1]);
        $total[11][2] = sprintf('%.2f', $total[1][2] / $total[6][2]);
        //转化率 有效订单/有效客资
        $total[12][0] = '转化率';
        $total[12][1] = sprintf('%.2f', ($total[6][1] / $total[3][1]) * 100) . '%';
        $total[12][2] = sprintf('%.2f', ($total[6][2] / $total[3][2]) * 100) . '%';
        //毛客资转化率 有效订单/毛客资
        $total[13][0] = '毛客资转化率';
        $total[13][1] = sprintf('%.2f', ($total[6][1] / $total[2][1]) * 100) . '%';
        $total[13][2] = sprintf('%.2f', ($total[6][2] / $total[2][2]) * 100) . '%';
        // 导出
        if ($data['need'] == 1) {
            $title = array('统计名目', '本周', '本月');

            $file = '电商数据月报-常态报表1.xlsx';
            controller("crm/Customer", "lib")->export($title, $total, $file);
        } else {
            $return = ['code' => 1, 'msg' => '', 'count' => 0, 'data' => $total];
            return json($return);
        }
    }

    //电商日报明细
    public function daily_detail()
    {
        // 权限
        $auth = check_right('menu1521352428');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        return $this->fetch();
    }

    //日报明细
    public function daily_detail_data()
    {
        set_time_limit(0);
        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）'];
            return json($return);
        }
        $name = array('星期', '日期', '当日总花费', '总毛客资', '总有效获取', '总获取手机', '总进店', '总订单', '总成交金额', '总营收', '总均价', '总毛客资成本', '有效获取成本', '成交成本', '获取到成交率');

        $today = date('Y-m-d');
        $month = getMonthDays();
        $shopCodes = sx_call('5a005e0038270', ['belong_shop_code' => $shop_code]);
        if ($shopCodes['code'] == 200) {
            $shop_code = array_unique(array_column($shopCodes['data'], 'shop_code'));
        } else {
            $shop_code = $shop_code;
        }
        $returnData[0][0] = $name[0];
        foreach ($month as $k => $v) {
            if ($today < $v) {
                break;
            }
            $returnData[0][$k + 1] = get_week($v);
        }
        $returnData[1][0] = $name[1];
        foreach ($month as $k => $v) {
            if ($today < $v) {
                break;
            }
            $returnData[1][$k + 1] = $v;
        }

        $returnData[2][0] = $name[2];
        $consultation_type_info = db('s_sta_setting')->where('shop_code', $shop_code)->find();
        $all = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['all_customer_consumptiontype']) {
                $all->where('consultation_type_id', 'in', $consultation_type_info['all_customer_consumptiontype']);
            }
        }
        $valid = db('c_customerinfo');
        $valid1 = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['valid_customer_consumptiontype']) {
                $valid->where('consultation_type_id', 'in', $consultation_type_info['valid_customer_consumptiontype']);
                $valid1->where('consultation_type_id', 'in', $consultation_type_info['valid_customer_consumptiontype']);
            }
        }
        $into = db('c_customerinfo');
        $noInto = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['into_customer_consumptiontype']) {
                $into->where('consultation_type_id', 'in', $consultation_type_info['into_customer_consumptiontype']);
                $noInto->where('consultation_type_id', 'not in', $consultation_type_info['into_customer_consumptiontype']);
            }
        }
        $order = db('c_customerinfo');
        $order1 = db('c_customerinfo');
        $order2 = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 1) {
            if ($consultation_type_info['order_customer_consumptiontype']) {
                $order->where('consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order1->where('consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order2->where('consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
            }
        }
        $cost = db('c_customer_cost')
            ->where('shop_code', 'in',$shop_code)
            ->where('brandclass_id', $brandclass_id)
            ->whereTime('cost_time','m')
            ->group('cost_time')
            ->column('sum(cost_avg) as num','cost_time');
        $param = array(
            'shop_code' => $shop_code,
            'brandclass_id' => $brandclass_id,
        );
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        //毛客资
        // 存在事业部
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
        }
        $start = date('Y-m-01');
        $end = date('Y-m-d');
        $all = db('c_customerinfo')
            ->where($where)
            ->where('add_shop_code', 'in',$shop_code)
            ->where('dj_day','between',[$start,$end])
            ->group('days')
            ->column('DATE_FORMAT(dj_day,"%Y-%m-%d") days,count(id) as num');


        // 有效客资量
        $validCustomer = $valid
            ->where($where)
            ->where('add_shop_code', 'in',$shop_code)
            ->where('is_valid', 1)
            ->where('yx_day','between',[$start,$end])
            ->group('days')
            ->column('DATE_FORMAT(yx_day,"%Y-%m-%d") days,count(id) as num');
        // 总手机  手机号不为空的客资总数（按录入时间计算）
        $allTel = $valid1
            ->where($where)
            ->where('add_shop_code', 'in',$shop_code)
            ->where('is_valid', 1)
            ->where('dj_day', 'between',[$start,$end])
            ->where('customer_tel', '<>', '')
            ->where('customer_tel', 'not null')
            ->group('days')
            ->column('DATE_FORMAT(dj_day,"%Y-%m-%d") days,count(id) as num');
        // 进店数量
        $intoNum = $into
            ->where($where)
            ->where('add_shop_code', 'in',$shop_code)
            ->where('is_intostore', 'in', '2,3')
            ->where('syjd_day', 'between',[$start,$end])
            ->group('days')
            ->column('DATE_FORMAT(syjd_day,"%Y-%m-%d") days,count(id) as num');

        // 有效订单 数
        $orderNum = $order
            ->where($where)
            ->where('add_shop_code', 'in',$shop_code)
            ->where('is_success', 1)
            ->where('order_day', 'between',[$start,$end])
            ->group('days')
            ->column('DATE_FORMAT(order_day,"%Y-%m-%d") days,count(id) as num');

        // 营收（实际收入  不区分有效无效）
        $factMoney = $order
            ->where($where)
            ->where('add_shop_code', 'in',$shop_code)
            ->where('order_start_time', 'between',[$start,$end])
            ->group('days')
            ->column('DATE_FORMAT(order_start_time,"%Y-%m-%d") days,sum(fact_money) as num');
        // 套系
        $totalMoney = $order1
            ->where($where)
            ->where('add_shop_code', 'in',$shop_code)
            ->where('is_success', 1)
            ->where('order_day', 'between',[$start,$end])
            ->group('days')
            ->column('DATE_FORMAT(order_day,"%Y-%m-%d") days,sum(totalpay_money) as totalpay_money');

        $returnData[2][0] = $name[2];
        $returnData[3][0] = $name[3];
        $returnData[4][0] = $name[4];
        $returnData[5][0] = $name[5];
        $returnData[6][0] = $name[6];
        $returnData[7][0] = $name[7];
        $returnData[8][0] = $name[8];
        $returnData[9][0] = $name[9];
        $returnData[10][0] = $name[10];
        $returnData[11][0] = $name[11];
        $returnData[12][0] = $name[12];
        $returnData[13][0] = $name[13];
        $returnData[14][0] = $name[14];
        foreach($month as $k=>$v){
            $returnData[2][$k+1] = $cost[$v] ? $cost[$v] : 0;//花费
            $returnData[3][$k+1] = $all[$v] ? $all[$v] : 0;//毛客资
            $returnData[4][$k+1] = $validCustomer[$v] ? $validCustomer[$v] : 0;//有效客资
            $returnData[5][$k+1] = $allTel[$v] ? $allTel[$v] : 0;//获取电话
            $returnData[6][$k+1] = $intoNum[$v] ? $intoNum[$v] : 0;//进店
            $returnData[7][$k+1] = $orderNum[$v] ? $orderNum[$v] : 0;//成单
            $returnData[8][$k+1] = $totalMoney[$v] ? $totalMoney[$v] : 0;//套系总额
            $returnData[9][$k+1] = $factMoney[$v] ? $factMoney[$v] : 0;//营收
            $returnData[10][$k+1] = $orderNum[$v] ? sprintf('%.2f',$totalMoney[$v]/$orderNum[$v]) : 0;//均价
            $returnData[11][$k+1] = $orderNum[$v] ? sprintf('%.2f',$cost[$v]/$all[$v]) : 0;//毛客资成本
            $returnData[12][$k+1] = $orderNum[$v] ? sprintf('%.2f',$cost[$v]/$validCustomer[$v]) : 0;//有效获取成本
            $returnData[13][$k+1] = $orderNum[$v] ? sprintf('%.2f',$cost[$v]/$orderNum[$v]) : 0;//成交成本
            $returnData[14][$k+1] = $orderNum[$v] ? sprintf('%.2f',$orderNum[$v]/$validCustomer[$v]*100).'%' : '0%';//获取到成交率
        }
//        print_r($returnData);die;


        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '电商日报明细.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            $return = ['code' => 1, 'msg' => '', 'today' => (int)date('d'), 'data' => $returnData];
            return json($return);
        }
    }

    public function daily_detail_data1()
    {
        $sttime = time();
        set_time_limit(0);
        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）'];
            return json($return);
        }
        $name = array('星期', '日期', '当日总花费', '总毛客资', '总有效获取', '总进店', '总订单', '总成交金额', '总营收', '总均价', '总毛客资成本', '有效获取成本', '成交成本', '获取到成交率');

        $today = date('Y-m-d');
        $month = getMonthDays();
        $shopCodes = sx_call('5a005e0038270', ['belong_shop_code' => $shop_code]);
        if ($shopCodes['code'] == 200) {
            $shop_code = array_unique(array_column($shopCodes['data'], 'shop_code'));
        } else {
            $shop_code = $shop_code;
        }
        $returnData[0][0] = $name[0];
        foreach ($month as $k => $v) {
            if ($today < $v) {
                break;
            }
            $returnData[0][$k + 1] = get_week($v);
        }
        $returnData[1][0] = $name[1];
        foreach ($month as $k => $v) {
            if ($today < $v) {
                break;
            }
            $returnData[1][$k + 1] = $v;
        }

        $returnData[2][0] = $name[2];
        $returnData[3][0] = $name[3];
        $returnData[3][0] = $name[3];
        $returnData[4][0] = $name[4];
        $returnData[5][0] = $name[5];
        $returnData[6][0] = $name[6];
        $returnData[7][0] = $name[7];
        $returnData[8][0] = $name[8];
        $returnData[9][0] = $name[9];
        $returnData[10][0] = $name[10];
        $returnData[11][0] = $name[11];
        $returnData[12][0] = $name[12];
        $returnData[13][0] = $name[13];
        foreach ($month as $k => $v) {
            $param = array(
                'start' => $v,
                'end' => date('Y-m-d', strtotime($v) + 86400),
                'add_shop_code' => $shop_code,
                'brandclass_id' => $brandclass_id,
            );
            if ($data['consultation_type_id']) {
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            $costParam = array(
                'start' => $v,
                'end' => date('Y-m-d', strtotime($v) + 86400),
                'add_shop_code' => $shop_code,
                'brandclass_id' => $brandclass_id,
            );
            if ($today < $v) {
                break;
            }
            //当日总花费
            $returnData[2][$k + 1] = controller('crm/Statistics', 'lib')->sta_costMoney($costParam);
            //总毛客资
            $returnData[3][$k + 1] = controller('crm/Statistics', 'lib')->sta_getCustomerNum($param);
            //总有效获取
            $returnData[3][$k + 1] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($param);
            //总获取手机
            $returnData[4][$k + 1] = controller('crm/Statistics', 'lib')->sta_getTelCustomerNum($param);
            //总进店
            $returnData[5][$k + 1] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($param);
            //总订单
            $returnData[6][$k + 1] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($param);
            //总成交金额
            $returnData[7][$k + 1] = controller('crm/Statistics', 'lib')->sta_dealMoney($param);
            //总营收
            $returnData[8][$k + 1] = controller('crm/Statistics', 'lib')->sta_incomeMoney($param);
            //总均价
            $money = controller('crm/Statistics', 'lib')->sta_dealMoney($param);
            $order = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($param);
            $returnData[9][$k + 1] = number_format($money / $order, 2);
            //总毛客资成本
            $cost = controller('crm/Statistics', 'lib')->sta_costMoney($param);
            $allCus = controller('crm/Statistics', 'lib')->sta_getCustomerNum($param);
            $returnData[10][$k + 1] = number_format($cost / $allCus, 2);
            //有效获取成本
            $cost = controller('crm/Statistics', 'lib')->sta_costMoney($param);
            $validCus = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($param);
            $returnData[11][$k + 1] = number_format($cost / $validCus, 2);
            //成交成本
            $cost = controller('crm/Statistics', 'lib')->sta_costMoney($param);
            $order = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($param);
            $returnData[12][$k + 1] = number_format($cost / $order, 2);
            //总有效获取成交率
            $order = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($param);
            $validCus = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($param);
            $returnData[13][$k + 1] = number_format($order / $validCus * 100, 2) . '%';
        }
        /*$returnData[3][0] = $name[3];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }

            if ($today < $v) {
                break;
            }
            //总毛客资
            $returnData[3][$k+1] = controller('crm/Statistics','lib')->sta_getCustomerNum($param);
        }
        $returnData[3][0] = $name[3];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总有效获取
            $returnData[3][$k+1] = controller('crm/Statistics','lib')->sta_getInvCustomerNum($param);
        }
        $returnData[4][0] = $name[4];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总获取手机
            $returnData[4][$k+1]= controller('crm/Statistics','lib')->sta_getTelCustomerNum($param);
        }
        $returnData[5][0] = $name[5];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总进店
            $returnData[5][$k+1] = controller('crm/Statistics','lib')->sta_getIntoCustomerNum($param);
        }
        $returnData[6][0] = $name[6];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总订单
            $returnData[6][$k+1] = controller('crm/Statistics','lib')->sta_getOrderNumberNum($param);
        }
        $returnData[7][0] = $name[7];

        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总成交金额
            $returnData[7][$k+1] = controller('crm/Statistics','lib')->sta_dealMoney($param);

        }
        $returnData[8][0] = $name[8];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总营收
            $returnData[8][$k+1] = controller('crm/Statistics','lib')->sta_incomeMoney($param);
        }
        $returnData[9][0] = $name[9];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总均价
            $money = controller('crm/Statistics','lib')->sta_dealMoney($param);
            $order = controller('crm/Statistics','lib')->sta_getOrderNumberNum($param);
            $returnData[9][$k+1] = number_format($money/$order,2);
        }

        $returnData[10][0] = $name[10];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总毛客资成本
            $cost = controller('crm/Statistics','lib')->sta_costMoney($param);
            $allCus = controller('crm/Statistics','lib')->sta_getCustomerNum($param);
            $returnData[10][$k+1] = number_format($cost/$allCus,2);
        }
        $returnData[11][0] = $name[11];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //有效获取成本
            $cost = controller('crm/Statistics','lib')->sta_costMoney($param);
            $validCus = controller('crm/Statistics','lib')->sta_getInvCustomerNum($param);
            $returnData[11][$k+1] = number_format($cost/$validCus,2);
        }
        $returnData[12][0] = $name[12];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if ($today < $v) {
                break;
            }
            //成交成本
            $cost = controller('crm/Statistics','lib')->sta_costMoney($param);
            $order = controller('crm/Statistics','lib')->sta_getOrderNumberNum($param);
            $returnData[12][$k+1] = number_format($cost/$order,2);
        }
        $returnData[13][0] = $name[13];
        foreach ($month as $k => $v) {
            $param = array(
                'start'=>$v,
                'end'=>date('Y-m-d',strtotime($v)+86400),
                'add_shop_code'    => $shop_code,
                'brandclass_id'=> $brandclass_id,
            );
            if($data['consultation_type_id']){
                $param['consultation_type_id'] = $data['consultation_type_id'];
            }
            if ($today < $v) {
                break;
            }
            //总有效获取成交率
            $order = controller('crm/Statistics','lib')->sta_getOrderNumberNum($param);
            $validCus = controller('crm/Statistics','lib')->sta_getInvCustomerNum($param);
            $returnData[13][$k+1] = number_format($order/$validCus*100,2).'%';
        }*/

        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '日报明细.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            $return = ['code' => 1, 'msg' => '' . time() - $sttime, 'today' => (int)date('d'), 'data' => $returnData];
            return json($return);
        }
    }

    //网销漏斗
    public function wx_ld()
    {
        // 权限
        $auth = check_right('menu1521352461');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //获取方式
        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' => session('shop_code')));
        $this->assign("accessModel", $accessModel);
        //来源渠道
        $channel = controller("Customer", "lib")->getChannel();
        $this->assign("channel", $channel);
        //客资地域
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function wx_ld_data()
    {
        set_time_limit(0);
        $data = input();
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d', strtotime('+1 day', strtotime($timeArea[1])));
        $shop_code = $data['shop_code'];
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $whereC['start'] = $start;
        $whereC['end'] = $end;
        if ($data['shop_code']) {
            $where['shop_code'] = $data['shop_code'];
            $whereC['shop_code'] = $data['shop_code'];
        }
        if ($data['consultation_type_id']) {
            $whereT['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
        }
        if ($data['city_id']) {
            $where['city_id'] = (int)$data['city_id'];
            $whereC['city_id'] = (int)$data['city_id'];
        }
        if ($data['channel_id']) {//渠道
            $where['customer_channel_id'] = (int)$data['channel_id'];
            $whereC['channel_id'] = (int)$data['channel_id'];
        }
        if ($data['accessModel_id']) {//获取方式
            $where['access_model_id'] = (int)$data['accessModel_id'];
        }
        //获取店内所有员工
        $staffs = controller('crm/Statistics', 'lib')->getStaffInfoByShop($shop_code);
        $returnData = [];
        $arr = [];
        foreach ($staffs as $key => $value) {
            $returnData[$key]['staff'] = $value['staffname'];
            // 花费
//            $channelCost = db('s_channel_cost')
//                ->where($whereC)
//                ->where('cost_date', 'between time', [$start, $end])
//                ->sum('cost');
            $channelCost = controller('crm/Statistics', 'lib')->sta_costMoney($whereC);
//            $channelCost = number_format($channelCost, 2);
            // 录入客资量（分配）
            $returnData[$key]['lrCustomer'] = db('c_customerinfo')
                ->where($where)
                ->where('sales_staff_id', $value['id'])
                ->where('jr_day', 'between time', [$start, $end])
                ->count();

            // 有效客资量
            $returnData[$key]['invCustomer'] = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('sales_staff_id', $value['id'])
                ->where('is_valid', 1)
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            // 总手机
            $returnData[$key]['allTel'] = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('is_valid',1)
                ->where('sales_staff_id', $value['id'])
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            // 进店数量
            $returnData[$key]['intoNum'] = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('sales_staff_id', $value['id'])
                ->where('is_intostore', 'between', '2,3')
                ->where('syjd_day', 'between time', [$start, $end])
                ->count();
            // 有效订单 数
            $returnData[$key]['orderNum'] = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('sales_staff_id', $value['id'])
                ->where('is_success', 1)
                ->where('order_day', 'between time', [$start, $end])
                ->count();
            // 营收（实际收入  不区分有效无效）
            $factMoney = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('sales_staff_id', $value['id'])
                ->where('order_start_time', 'between time', [$start, $end])
                ->sum('fact_money');
            $returnData[$key]['factMoney'] = number_format($factMoney, 2);
            // 套系均值（有效单套系应收款均值）
            $order_amount_avg = db('c_customerinfo')
                ->where($where)
                ->where($whereT)
                ->where('sales_staff_id', $value['id'])
                ->where('is_success', 1)
                ->where('order_day', 'between time', [$start, $end])
                ->avg('totalpay_money');
            $returnData[$key]['orderAmountAvg'] = number_format($order_amount_avg, 2);
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$key]['invRate'] = (number_format($returnData[$key]['invCustomer'] / $returnData[$key]['lrCustomer'], 2) * 100) . '%';
            // 进店率（ 实际进店 / 有效获取 ）
            $returnData[$key]['intoRate'] = (number_format($returnData[$key]['intoNum'] / $returnData[$key]['invCustomer'], 2) * 100) . '%';
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$key]['orderRate'] = (number_format($returnData[$key]['orderNum'] / $returnData[$key]['intoNum'], 2) * 100) . '%';
            // 转化率（ 有效获取 / 有效新单 ）
            $returnData[$key]['changeRate'] = (number_format($returnData[$key]['orderNum']/$returnData[$key]['invCustomer'], 2) * 100) . '%';
            // 毛客资成本
            $returnData[$key]['customerCost'] = number_format($channelCost / $returnData[$key]['lrCustomer'], 2);
            // 有效获取成本
            $returnData[$key]['invCost'] = number_format($channelCost / $returnData[$key]['invCustomer'], 2);
            // 新单成本
            $returnData[$key]['orderCost'] = number_format($channelCost / $returnData[$key]['orderNum'], 2);
            // ROI（花费：婚纱接总）(营收)
            $returnData[$key]['ROI'] = number_format($returnData[$key]['factMoney'] / $channelCost, 2) . '：1';

            $arr['staff'] = '总计';                       // 花费总计
//            $arr['channelCost'] += $channelCost;                       // 花费总计
            $arr['lrCustomer'] += $returnData[$key]['lrCustomer'];    // 录入总计
            $arr['invCustomer'] += $returnData[$key]['invCustomer'];   // 有效总计
            $arr['allTel'] += $returnData[$key]['allTel'];        // 总手机总计
            $arr['intoNum'] += $returnData[$key]['intoNum'];       // 进店总计
            $arr['orderNum'] += $returnData[$key]['orderNum'];      // 订单总计
            $arr['factMoney'] += $factMoney;                         // 营收总计
        }
        array_push($returnData, $arr);
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($staffs);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = array('员工', '毛客资', '有效客获取', '总手机', '邀约进店', '有效订单', '营收', '套系均值', '有效率', '进店率', '成交率', '转化率', '毛客资成本', '有效获取成本', '新单成本', 'ROI');
            $file = '网销漏斗统计.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
    }

    //渠道透视
    public function qd_ts()
    {
        // 权限
        $auth = check_right('menu1521352487');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //客资地域
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function qd_ts_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1521352487');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();

        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 城市
        if (!$data['city_id']) {
            $return = ['code' => 200, 'msg' => '请选择城市', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d', strtotime('+1 day', strtotime($timeArea[1])));

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $data['shop_code'];
        if ($data['consultation_type_id']) {
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
        }
        if ($data['city_id']) {
            $where['city_id'] = (int)$data['city_id'];
        }
        $date = getDates($start, $end);
//        print_r($date);die;
        // 来源渠道
        $channels = db('s_channel')->where('shop_code', $data['shop_code'])->select();
        $returnData[0][0] = $data['city'];
        foreach ($channels as $key => $value) {
            $returnData[0][$key + 1] = $value['channel_name'];
        }
        $returnData[0][count($channels) + 1] = '总计';
        foreach ($date as $k => $v) {
            $returnData[$k + 1][0] = $v;
            // 录入客资量
            $num = 0;
            foreach ($channels as $key => $val) {
                $returnData[$k + 1][$key + 1] = db('c_customerinfo')
                    ->where($where)
                    ->where('customer_channel_id', $val['id'])
                    ->where('dj_day', 'between time', [$v, date('Y-m-d', strtotime($v) + 86400)])
                    ->count();
                $num += $returnData[$k + 1][$key + 1];
//                $returnData[$k+1][$key+1] = db()->getLastSql();
            }
            $returnData[$k + 1][count($channels) + 1] = $num;
        }

        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '渠道毛客资透视.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json(array('code' => 1, 'data' => $returnData, 'count' => count($returnData[0])));
        }
    }

    //地域渠道有效客资透视
    public function dy_ts()
    {
        // 权限
        $auth = check_right('menu1521352560');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        //客资地域
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        return $this->fetch();
    }

    //地域渠道有效客资透视
    public function dy_ts_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1521352560');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();

        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 省份
        if (!$data['province_id']) {
            $return = ['code' => 200, 'msg' => '请选择省份', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d', strtotime('+1 day', strtotime($timeArea[1])));

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        $where['add_shop_code'] = $data['shop_code'];
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
        }
        //获取省份下的城市
        $param = array(
            'pid' => $data['province_id'],
            'type' => 2,
            'shop_code' => $data['shop_code'],
        );
        $citys = controller('crm/Customer', 'lib')->address($param);

        // 来源渠道
        $channels = db('s_channel')->where('shop_code', $data['shop_code'])->select();
        $returnData[0][0] = $data['province'];
        foreach ($citys as $k => $v) {
            $returnData[0][$k + 1] = $v['name'];
        }
        $returnData[0][count($citys) + 1] = '总计';

        foreach ($channels as $key => $value) {
            $returnData[$key + 1][0] = $value['channel_name'];
            $num = 0;
            foreach ($citys as $k => $v) {
                $returnData[$key + 1][$k + 1] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 1)
                    ->where('city_id', $v['id'])
                    ->where('customer_channel_id', $value['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                $num += $returnData[$key + 1][$k + 1];
            }
            $returnData[$key + 1][count($citys) + 1] = $num;
        }

        $returnData[count($channels) + 1][0] = '总计';
        $cNum = 0;
        foreach ($citys as $k => $v) {
            $returnData[count($channels) + 1][$k + 1] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 1)
                ->where('city_id', $v['id'])
                ->where('customer_channel_id', 'in', array_column($channels, 'id'))
                ->where('dj_day', 'between time', [$start, $end])
                ->count();
            $cNum += $returnData[count($channels) + 1][$k + 1];
        }
        $returnData[count($channels) + 1][count($citys) + 1] = $cNum;
        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '地域有效客资透视.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json(array('code' => 1, 'data' => $returnData, 'count' => count($returnData[0])));
        }
    }

    //网销无效分析
    public function wx_unvalid()
    {
        // 权限
        $auth = check_right('menu1521352579');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function wx_unvalid_data()
    {
        set_time_limit(0);
        $data = input();
        $shop_code = $data['shop_code'];
        if ($data['mode'] == 'region') {
            $obj = controller("crm/Customer", "lib")->address(['pid' => $data['province_id'], 'type' => 2, 'shop_code' => $shop_code]);
        } elseif ($data['mode'] == 'access') {
            $obj = controller("Customer", "lib")->accessModel(array('shop_code' => $shop_code));
        } elseif ($data['mode'] == 'staff') {
            $obj = controller('Customer', 'lib')->get_staff_list(['shop_code' => $shop_code]);
        } elseif ($data['mode'] == 'channel') {
            $obj = controller("Customer", "lib")->getChannel($shop_code);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d', strtotime('+1 day', strtotime($timeArea[1])));

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = $shop_code;
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }


        $valid = 0;
        $unvalid = 0;
        $dd = 0;
        $total = 0;
        $yxRate = 0;
        $wxRate = 0;
        $ddRate = 0;
        $jd = 0;
        $jdRate = 0;
        foreach ($obj as $k => $v) {
            if ($data['mode'] == 'region') {
                $returnData[$k][0] = $v['name'];
                $where['city_id'] = $v['id'];
            } elseif ($data['mode'] == 'access') {
                $returnData[$k][0] = $v['accessmodel'];
                $where['access_model_id'] = $v['id'];
            } elseif ($data['mode'] == 'staff') {
                $returnData[$k][0] = $v['staffname'];
                $where['sales_staff_id'] = $v['id'];
            } elseif ($data['mode'] == 'channel') {
                $returnData[$k][0] = $v['channel_name'];
                $where['customer_channel_id'] = $v['id'];
            }

            //有效
            $returnData[$k][1] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 1)
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
//            echo db()->getLastSql();die;
            //无效
            $returnData[$k][2] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 3)
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            //待定
            $returnData[$k][3] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 2)
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            //总计
            $returnData[$k][4] = $returnData[$k][1] + $returnData[$k][2] + $returnData[$k][3];

            //有效率
            $returnData[$k][5] = sprintf('%.2f', $returnData[$k][1] / $returnData[$k][4] * 100) . '%';
            //无效率
            $returnData[$k][6] = sprintf('%.2f', $returnData[$k][2] / $returnData[$k][4] * 100) . '%';
            //待定率
            $returnData[$k][7] = sprintf('%.2f', $returnData[$k][3] / $returnData[$k][4] * 100) . '%';

            //进店数
            $inv = db('c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
                ->where('syjd_day', 'between time', [$start, $end])
                ->count();
            $returnData[$k][8] = $inv;
            //进店率  进店/有效
            $returnData[$k][9] = round($returnData[$k][8] / $returnData[$k][1] * 100, 2) . '%';

            $valid += $returnData[$k][1];
            $unvalid += $returnData[$k][2];
            $dd += $returnData[$k][3];
            $total += $returnData[$k][4];
            $yxRate += (float)$returnData[$k][5];
            $wxRate += (float)$returnData[$k][6];
            $ddRate += (float)$returnData[$k][7];
            $jd += $returnData[$k][8];
            $jdRate += (float)$returnData[$k][9];
        }
        $returnData[count($obj)][0] = '总计';
        $returnData[count($obj)][1] = $valid;
        $returnData[count($obj)][2] = $unvalid;
        $returnData[count($obj)][3] = $dd;
        $returnData[count($obj)][4] = $total;
        $returnData[count($obj)][5] = sprintf('%.2f', $valid / $total * 100) . '%';
        $returnData[count($obj)][6] = sprintf('%.2f', $unvalid / $total * 100) . '%';
        $returnData[count($obj)][7] = sprintf('%.2f', $dd / $total * 100) . '%';
        $returnData[count($obj)][8] = $jd;
        $returnData[count($obj)][9] = sprintf('%.2f', $jd / $valid * 100) . '%';
        // 导出
        if ($data['need'] == 1) {
            $title = array('', '有效', '无效', '待定', '总计', '有效率', '无效率', '待定率', '进店数', '进店率');
            $file = '网销无效分析.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json(array('code' => 1, 'data' => $returnData, 'count' => count($returnData[0])));
        }
    }

    //渠道漏斗月走势统计
    public function channel_ld_month()
    {
        // 权限
        $auth = check_right('menu1521352601');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        $this->assign('year', date('Y'));
        return $this->fetch();
    }

    public function channel_ld_month_data()
    {
        set_time_limit(0);
        $data = input();
        if (!$data['timeArea']) {
            $year = date('Y');
        } else {
            $year = $data['timeArea'];
        }
        $shop_code = $data['shop_code'];

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['is_valid'] = 1;
        $where['add_shop_code'] = $shop_code;
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 来源渠道
        $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        $count = count($channels);
        $returnData = [];
        $month1 = $month2 = $month3 = $month4 = $month5 = $month6 = $month7 = $month8 = $month9 = $month10 = $month11 = $month12 = 0;
        foreach ($channels as $k => $v) {
            $returnData[$k]['channel_class_name'] = $v['channel_class_name'];
            $returnData[$k]['channel_info_name'] = $v['channel_info_name'];
            $returnData[$k]['channel_name'] = $v['channel_name'];
            switch ($data['mode']) {
                //花费
                case 1:
                default:
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == 12) {
                            $year1 = $year . '-12';
                            $year2 = (int)($year + 1) . '-01';
                        } else {
                            $year1 = $year . '-' . $i;
                            $year2 = $year . '-' . ($i + 1);
                        }
//                        $param['add_shop_code'] = $shop_code;
//                        $param['channel_id'] = $v['id'];
//                        $param['start'] = $year1;
//                        $param['end'] = $year2;
                        $returnData[$k]['month' . $i] = db('c_customer_cost')
                            ->where('shop_code', $shop_code)
                            ->where('channel_id', $v['id'])
                            ->where('cost_time', 'between time', [$year1, $year2])
                            ->sum('cost_avg');
//                        $returnData[$k]['month'.$i] = controller('crm/Statistics', 'lib')->sta_costMoney($param);
                    }
                    break;
                //有效获取量
                case 2:
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == 12) {
                            $year1 = $year . '-12';
                            $year2 = (int)($year + 1) . '-01';
                        } else {
                            $year1 = $year . '-' . $i;
                            $year2 = $year . '-' . ($i + 1);
                        }
                        $returnData[$k]['month' . $i] = db('c_customerinfo')
                            ->where($where)
                            ->where('customer_channel_id', $v['id'])
                            ->where('yx_day', 'between time', [$year1, $year2])
                            ->count();

                    }
                    break;
                //入客量(进店)
                case 3:
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == 12) {
                            $year1 = $year . '-12';
                            $year2 = (int)($year + 1) . '-01';
                        } else {
                            $year1 = $year . '-' . $i;
                            $year2 = $year . '-' . ($i + 1);
                        }
                        $returnData[$k]['month' . $i] = db('c_customerinfo')
                            ->where($where)
//                            ->where('order_type', 1)
                            ->where('is_intostore', 2)
                            ->where('customer_channel_id', $v['id'])
                            ->where('syjd_day', 'between time', [$year1, $year2])
                            ->count();
                    }
                    break;
                //新单量
                case 4:
//                    $where['order_type'] = 2;
                    $where['is_success'] = 1;
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == 12) {
                            $year1 = $year . '-12';
                            $year2 = (int)($year + 1) . '-01';
                        } else {
                            $year1 = $year . '-' . $i;
                            $year2 = $year . '-' . ($i + 1);
                        }
                        $returnData[$k]['month' . $i] = db('c_customerinfo')
                            ->where($where)
                            ->where('customer_channel_id', $v['id'])
                            ->where('order_day', 'between time', [$year1, $year2])
                            ->count();
                    }
                    break;
                //有效获取成本
                case 5:
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == 12) {
                            $year1 = $year . '-12';
                            $year2 = (int)($year + 1) . '-01';
                        } else {
                            $year1 = $year . '-' . $i;
                            $year2 = $year . '-' . ($i + 1);
                        }
                        //花费
                        $cost = db('c_customer_cost')
                            ->where('shop_code', session('shop_code'))
                            ->where('channel_id', $v['id'])
                            ->where('shop_code', $shop_code)
                            ->where('cost_time', 'between time', [$year1, $year2])
                            ->sum('cost_avg');
                        //有效
                        $valid = db('c_customerinfo')
                            ->where($where)
                            ->where('customer_channel_id', $v['id'])
                            ->where('yx_day', 'between time', [$year1, $year2])
                            ->count();
                        $returnData[$k]['month' . $i] = number_format($cost / $valid, 2);
                    }
                    break;
                //新单成本
                case 6:
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == 12) {
                            $year1 = $year . '-12';
                            $year2 = (int)($year + 1) . '-01';
                        } else {
                            $year1 = $year . '-' . $i;
                            $year2 = $year . '-' . ($i + 1);
                        }
                        //花费
                        $cost = db('c_customer_cost')
                            ->where('shop_code', $shop_code)
                            ->where('channel_id', $v['id'])
                            ->where('cost_time', 'between time', [$year1, $year2])
                            ->sum('cost_avg');
                        $order = db('c_customerinfo')
                            ->where($where)
                            ->where('is_success', 1)
                            ->where('customer_channel_id', $v['id'])
                            ->where('order_day', 'between time', [$year1, $year2])
                            ->count();
                        $returnData[$k]['month' . $i] = number_format($cost / $order, 2);
                    }
                    break;
                //转换率
                case 7:
                    for ($i = 1; $i <= 12; $i++) {
                        if ($i == 12) {
                            $year1 = $year . '-12';
                            $year2 = (int)($year + 1) . '-01';
                        } else {
                            $year1 = $year . '-' . $i;
                            $year2 = $year . '-' . ($i + 1);
                        }
                        $order = db('c_customerinfo')
                            ->where($where)
//                            ->where('order_type', 1)
                            ->where('is_success', 1)
                            ->where('customer_channel_id', $v['id'])
                            ->where('order_day', 'between time', [$year1, $year2])
                            ->count();
                        //有效
                        $valid = db('c_customerinfo')
                            ->where($where)
                            ->where('customer_channel_id', $v['id'])
                            ->where('yx_day', 'between time', [$year1, $year2])
                            ->count();

                        $returnData[$k]['month' . $i] = number_format($order / $valid * 100, 2) . '%';
                    }
                    break;
            }
            if ($data['mode'] == 7) {
                $month1 += floatval($returnData[$k]['month1']);
                $month2 += floatval($returnData[$k]['month2']);
                $month3 += floatval($returnData[$k]['month3']);
                $month4 += floatval($returnData[$k]['month4']);
                $month5 += floatval($returnData[$k]['month5']);
                $month6 += floatval($returnData[$k]['month6']);
                $month7 += floatval($returnData[$k]['month7']);
                $month8 += floatval($returnData[$k]['month8']);
                $month9 += floatval($returnData[$k]['month9']);
                $month10 += floatval($returnData[$k]['month10']);
                $month11 += floatval($returnData[$k]['month11']);
                $month12 += floatval($returnData[$k]['month12']);
            } else {
                $month1 += floatval($returnData[$k]['month1']);
                $month2 += floatval($returnData[$k]['month2']);
                $month3 += floatval($returnData[$k]['month3']);
                $month4 += floatval($returnData[$k]['month4']);
                $month5 += floatval($returnData[$k]['month5']);
                $month6 += floatval($returnData[$k]['month6']);
                $month7 += floatval($returnData[$k]['month7']);
                $month8 += floatval($returnData[$k]['month8']);
                $month9 += floatval($returnData[$k]['month9']);
                $month10 += floatval($returnData[$k]['month10']);
                $month11 += floatval($returnData[$k]['month11']);
                $month12 += floatval($returnData[$k]['month12']);
            }
        }
        //总计
        $total['channel_class_name'] = '';
        $total['channel_info_name'] = '';
        $total['channel_name'] = '总计';
        if ($data['mode'] == 7) {
            $total['month1'] = number_format($month1 / $count, 2) . '%';
            $total['month2'] = number_format($month2 / $count, 2) . '%';
            $total['month3'] = number_format($month3 / $count, 2) . '%';
            $total['month4'] = number_format($month4 / $count, 2) . '%';
            $total['month5'] = number_format($month5 / $count, 2) . '%';
            $total['month6'] = number_format($month6 / $count, 2) . '%';
            $total['month7'] = number_format($month7 / $count, 2) . '%';
            $total['month8'] = number_format($month8 / $count, 2) . '%';
            $total['month9'] = number_format($month9 / $count, 2) . '%';
            $total['month10'] = number_format($month10 / $count, 2) . '%';
            $total['month11'] = number_format($month11 / $count, 2) . '%';
            $total['month12'] = number_format($month12 / $count, 2) . '%';
        } else {
            $total['month1'] = $month1;
            $total['month2'] = $month2;
            $total['month3'] = $month3;
            $total['month4'] = $month4;
            $total['month5'] = $month5;
            $total['month6'] = $month6;
            $total['month7'] = $month7;
            $total['month8'] = $month8;
            $total['month9'] = $month9;
            $total['month10'] = $month10;
            $total['month11'] = $month11;
            $total['month12'] = $month12;
        }
        array_push($returnData, $total);
        // 导出
        if ($data['need'] == 1) {
            $title = array('序号', '渠道类型', '来源渠道', '渠道名称', '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月');
            $file = '渠道漏斗月走势统计.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            $return['code'] = 0;
            $return['msg'] = '';
            $return['count'] = $count;
            $return['data'] = $returnData;
            return json($return);
        }
    }

    //关键词分析
    public function keywords()
    {
        // 权限
        $auth = check_right('menu1521352632');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }
        //来源渠道
//        $channel=controller("Customer","lib")->getChannel();
//        $this->assign("channel",$channel);
        //客资地域
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
//         var_dump($lists);
//         var_dump($lists['brandclassList']);
//         var_dump($lists['shopList']);
//         exit;
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //来源渠道
        $channel = controller("Customer", "lib")->getChannel();
        $this->assign("channel", $channel);
        return $this->fetch();
    }

    public function keywords_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1521352632');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'];

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）' . $shop_code];
            return json($return);
        }

        //通过页面获取的shop_code获取归属店的shop_code
        $shopCodes = sx_call('5a005e0038270', ['belong_shop_code' => $shop_code]);
        if ($shopCodes['code'] == 200) {
            $shopCodes = array_unique(array_column($shopCodes['data'], 'shop_code'));
        } else {
            $shopCodes = $shop_code;
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        // 时间区域
        if ($data['timeArea']) {
            $start = date('Y-m-d', strtotime($timeArea[0]));
            $end = date('Y-m-d', strtotime('+1 day', strtotime($timeArea[1])));
        } else {
            $start = 0;
            $end = date('Y-m-d H:i:s', time());
        }
        // 省份
        if ($data['province_id']) {
            $where['province_id'] = $data['province_id'];
        }
        // 城市
        if ($data['city_id']) {
            $where['city_id'] = $data['city_id'];
        }
        // 渠道
        if ($data['channel_id']) {
            $where['customer_channel_id'] = $data['channel_id'];
        }
        $where['brandclass_id'] = $brandclass_id;
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
//        $where['consultation_type_id'] = HS_TYPE;
        //关键词
        $keywords = db('c_customerinfo')
            ->where($where)
            ->where('customer_key', '<>', 'null')
            ->where('customer_key', '<>', '')
            ->where('shop_code', 'in', $shopCodes)
            ->where('dj_day', 'between time', [$start, $end])
            ->field('count(*) AS num,customer_key')
            ->group('customer_key')
            ->order('num desc')
            ->limit($limit)
            ->page($page)
            ->select();
//        echo db()->getLastSql();die;
        foreach ($keywords as $k => $v) {
            unset($keywords[$k]['num']);
            if (!$data['li'] || $data['li'] == 1) {//获取排行
                $cont = '获取排行';
                $keywords[$k]['tel'] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_first_tel|is_first_wechat|is_first_qq', '1')
                    ->where('customer_key', $v['customer_key'])
                    ->where('shop_code', 'in', $shopCodes)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
//                echo db()->getLastSql();die;
            } elseif ($data['li'] == 2) {//邀约
                $cont = '邀约排行';
                $keywords[$k]['tel'] = db('c_customerinfo')
                    ->where($where)
                    ->where('syjd_day', '<>', 'null')
                    ->where('customer_key', $v['customer_key'])
                    ->where('shop_code', 'in', $shopCodes)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
            } elseif ($data['li'] == 3) {//订单
                $cont = '订单排行';
                $keywords[$k]['tel'] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 'in', [2, 3])
                    ->where('order_start_time', '<>', 'null')
                    ->where('customer_key', $v['customer_key'])
                    ->where('shop_code', 'in', $shopCodes)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
            } elseif ($data['li'] == 4) {//订单总价
                $cont = '订单总价排行';
                $keywords[$k]['tel'] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 'in', [2, 3])
                    ->where('order_start_time', '<>', 'null')
                    ->where('customer_key', $v['customer_key'])
                    ->where('shop_code', 'in', $shopCodes)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->sum('fact_money');
            } elseif ($data['li'] == 5) {//单价
                $cont = '单价排行';
                $keywords[$k]['tel'] = db('c_customerinfo')
                    ->where($where)
                    ->where('fact_money', '<>', 0)
                    ->where('customer_key', $v['customer_key'])
                    ->where('shop_code', 'in', $shopCodes)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->value('fact_money');
            } elseif ($data['li'] == 6) {//总体
                $cont = '总体排行';
                $keywords[$k]['tel'] = db('c_customerinfo')
                    ->where($where)
                    ->where('customer_key', $v['customer_key'])
                    ->where('shop_code', 'in', $shopCodes)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
            }
        }
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($keywords);
        $return['data'] = $keywords;
        // 导出
        if ($data['need'] == 1) {
            $title = array('关键字', '数量/金额');
            $file = $cont . '--关键词分析.xlsx';
            controller("crm/Customer", "lib")->export($title, $keywords, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 200, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }

    //小组列表
    public function groupList($shopCode)
    {
        return db('c_staff_group')->where('shop_code', $shopCode)->select();
    }

    //批量获取员工信息
    public function getStaffsInfo($staffIds)
    {
        $url = '5a18e3fa516a1';
        $res = sx_call($url, array('staff_id' => $staffIds));
        if ($res['code'] == 200) {
            return $res['data'];
        } else {
            return false;
        }
    }

    //网销小组数据统计
    public function wx_group()
    {
        // 权限
        $auth = check_right('menu1521352658');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        // 来源渠道
        $channels = controller('crm/Customer', 'lib')->getChannel();
        $this->assign('channel', $channels);
        // 客资标记
        $signs = controller('crm/Setting', 'lib')->gettrackingKmarkerList();
        $this->assign('signs', $signs);
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //获取方式
        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' => session('shop_code')));
        $this->assign("accessModel", $accessModel);
        return $this->fetch();
    }

    public function wx_group_data()
    {
        set_time_limit(0);
        $time1 = time();
        // 权限
        $auth = check_right('menu1521352658');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $title = ['序号','组名', '姓名', '轮位客资', '有效', '待定', '无效', '有效率', '无效率', '待定率', '首次获取微信/QQ量', '首次获取qq微信转电话量', '转手机率',
            '总手机数'];
        $data = input();

        $shopCode = $data['shop_code'];
        //获取店下的小组
        $groupList = $this->groupList($shopCode);
        if (empty($groupList)) {
            $return = ['code' => 100, 'msg' => '参数有误,请修改', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $returnData = [];
        for ($i = 0; $i < count($title); $i++) {
            $returnData[0][$i] = $title[$i];
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        // 时间区域
        if ($data['timeArea']) {
            $start = date('Y-m-d', strtotime($timeArea[0]));
            $end = date('Y-m-d 23:59:59', strtotime('+1 day', strtotime($timeArea[1])));
        } else {
            $start = 0;
            $end = date('Y-m-d H:i:s', time());
        }
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.customer_type'] = 1;
        $where['c.shop_code'] = $shopCode;
        $where['g.shop_code'] = $shopCode;
//        if($data['consultation_type_id']){
//            $whereC['consultation_type_id'] = $data['consultation_type_id'];
//        }
        $consultation_type_info = db('s_sta_setting')->where('shop_code', $shopCode)->find();
        $all = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 3) {
            if ($consultation_type_info['all_customer_consumptiontype']) {
                $all->where('consultation_type_id', 'in', $consultation_type_info['all_customer_consumptiontype']);
            }
        }
        $valid = db('c_customerinfo');
        if ($consultation_type_info['is_marketing'] == 3) {
            if ($consultation_type_info['valid_customer_consumptiontype']) {
                $valid->where('consultation_type_id', 'in', $consultation_type_info['valid_customer_consumptiontype']);
            }
        }
        if ($data['sign_id']) {
            $where['c.sign_id'] = $data['sign_id'];
        }
        if ($data['customer_channel_id']) {
            $where['c.customer_channel_id'] = $data['customer_channel_id'];
        }
//        if($data['accessModel_id']){
//            $where['access_model_id'] = $data['accessModel_id'];
//        }
        if ($data['province_id']) {
            $where['c.province_id'] = $data['province_id'];
        }
        if ($data['city_id']) {
            $where['c.city_id'] = $data['city_id'];
        }
        $total = [];
//        $noGroupStaffs = controller('crm/Setting','lib')->getNoGroupStaff(['shop_code'=>$shopCode]);
//        print_r($noGroupStaffs);die;
        //组内所有人
        $staff = db('c_staff_group')->alias('g')->join('c_staff_group_relation r','g.id=r.group_id')
            ->where('g.shop_code',$shopCode)
            ->field('g.id,g.group_name,r.staff_id,r.staff_name')
            ->select();
        if(!$staff[0]['staff_name']){
            $staffIds = implode(',',array_column($staff,'staff_id'));
            $url = "5a18e3fa516a1";
            $res = sx_call($url,array('staff_id'=>$staffIds));
            $staffNames = [];

            if($res['code'] == 200){
                $info = $res['data'];
                foreach($info as $key=>$val){
                    $staffNames[$val['id']] = $val['staffname'];
                }
            }else{
                $return = ['code' => 100, 'msg' => '批量查询小组人员信息失败', 'count' => 0, 'data' => ''];
                return json($return);
            }
        }

        //接入毛客资
        $allCustomer = $all->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('dj_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //有效
        $validCustomer = $valid->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid', 1)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //待定
        $ddCustoemr = $valid->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid', 2)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //无效
        $unValidCustomer = $valid->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid', 3)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');;
        //微信/QQ  存在微信或QQ 计算一项
        $noTel = $valid->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid',1)
            ->where('is_first_tel', null)
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //转化手机数 原来没有，后来添加
        $zhaunTel = $valid->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid',1)
            ->where('customer_tel', '<>', '')
            ->where('is_first_tel', null)
            ->where('tel_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //转化手机率 转化手机数/第一次没获取到手机的客资数量
//        $array[11] = number_format($array[10] / $array[9] * 100, 2) . '%';
        //总手机数
        $allTel = $valid->alias('c')->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('is_valid',1)
            ->where('customer_tel', '<>', '')
            ->where('yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        $returnData = [];
        $arr = [];
        $px = [];
        $arr['id'] = '';
        $arr['name'] = '';
        $arr['staff_name'] = '总计';
        $i = 1;
        //第一个小组
        $gid = $staff[0]['id'];
        //最后一个小组
        $last = end($staff);
        $lastSid = $last['staff_id'];
        $group = [];
        foreach($staff as $k=>$v){
            //小组总计
            $group[$v['id']]['id'] = '';
            $group[$v['id']]['name'] = '';
            $group[$v['id']]['staff_name'] = '总计';
            $group[$v['id']]['jrCus'] += $allCustomer[$v['staff_id']]['num'] ? $allCustomer[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['valid'] += $validCustomer[$v['staff_id']]['num'] ? $validCustomer[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['dd'] += $ddCustoemr[$v['staff_id']]['num'] ? $ddCustoemr[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['unValid'] += $unValidCustomer[$v['staff_id']]['num'] ? $unValidCustomer[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['validRate'] = sprintf('%.2f',$group[$v['id']]['valid']/$group[$v['id']]['jrCus'] * 100).'%';//有效率
            $group[$v['id']]['unValidRate'] = sprintf('%.2f',$group[$v['id']]['unValid']/$group[$v['id']]['jrCus'] * 100).'%';//无效率
            $group[$v['id']]['ddValidRate'] = sprintf('%.2f',$group[$v['id']]['dd']/$group[$v['id']]['jrCus'] * 100).'%';//无效率
            $group[$v['id']]['noTel'] += $noTel[$v['staff_id']]['num'] ? $noTel[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['zhaunTel'] += $zhaunTel[$v['staff_id']]['num'] ? $zhaunTel[$v['staff_id']]['num'] : 0;
            $group[$v['id']]['zhaunTelRate'] = sprintf('%.2f',$group[$v['id']]['zhaunTel']/$group[$v['id']]['noTel'] * 100).'%';
            $group[$v['id']]['allTel'] += $allTel[$v['staff_id']]['num'] ? $allTel[$v['staff_id']]['num'] : 0;

            $px['id'] = $i;
            $px['name'] = $v['group_name'];
            $px['staff_name'] = $v['staff_name'] ? $v['staff_name'] : $staffNames[$v['staff_id']];
            $px['jrCus'] = $allCustomer[$v['staff_id']]['num'] ? $allCustomer[$v['staff_id']]['num'] : 0;
            $px['valid'] = $validCustomer[$v['staff_id']]['num'] ? $validCustomer[$v['staff_id']]['num'] : 0;
            $px['dd'] = $ddCustoemr[$v['staff_id']]['num'] ? $ddCustoemr[$v['staff_id']]['num'] : 0;
            $px['unValid'] = $unValidCustomer[$v['staff_id']]['num'] ? $unValidCustomer[$v['staff_id']]['num'] : 0;
            $px['validRate'] = sprintf('%.2f',$px['valid']/$px['jrCus'] * 100).'%';//有效率
            $px['unValidRate'] = sprintf('%.2f',$px['unValid']/$px['jrCus'] * 100).'%';//无效率
            $px['ddValidRate'] = sprintf('%.2f',$px['dd']/$px['jrCus'] * 100).'%';//待定率
            $px['noTel'] = $noTel[$v['staff_id']]['num'] ? $noTel[$v['staff_id']]['num'] : 0;
            $px['zhaunTel'] = $zhaunTel[$v['staff_id']]['num'] ? $zhaunTel[$v['staff_id']]['num'] : 0;
            $px['zhaunTelRate'] = sprintf('%.2f',$px['zhaunTel']/$px['noTel'] * 100).'%';
            $px['allTel'] = $allTel[$v['staff_id']]['num'] ? $allTel[$v['staff_id']]['num'] : 0;

            if((!empty($gid) && ($gid != $v['id']))){
                $returnData[]= $group[$gid];
                $gid = $v['id'];
            }
            $returnData[] = $px;
            if($v['staff_id'] == $lastSid){
                $returnData[]= $group[$gid];
            }
//            array_push($returnData,$px);
            $arr['jrCus'] += $px['jrCus'];
            $arr['valid'] += $px['valid'];
            $arr['unValid'] += $px['unValid'];
            $arr['dd'] += $px['dd'];
            $arr['noTel'] += $px['noTel'];
            $arr['zhaunTel'] += $px['zhaunTel'];
            $arr['allTel'] += $px['allTel'];
            $i++;
        }
        $arr['validRate'] = sprintf('%.2f',$arr['valid']/$arr['jrCus'] * 100).'%';//有效率
        $arr['unValidRate'] = sprintf('%.2f',$arr['unValid']/$arr['jrCus'] * 100).'%';//无效率
        $arr['ddValidRate'] = sprintf('%.2f',$arr['dd']/$arr['jrCus'] * 100).'%';//待定率
        $arr['zhaunTelRate'] = sprintf('%.2f',$arr['zhaunTel']/$arr['noTel'] * 100).'%';
        $returnData[] = $arr;
//        array_push($returnData,$arr);

      /*  foreach ($groupList as $k => $v) {
            //获取小组下的人员
            $info = db('c_staff_group_relation')->where('group_id', $v['id'])->select();
            $staffIds = array_column($info, 'staff_id');//小组内人员数组
            $staffs = $this->getStaffsInfo($staffIds);
            $num = [];
            foreach ($staffs as $key => $val) {
                $array = [];
                $array[0] = $v['group_name'];
                $array[1] = $val['staffname'];
                //接入毛客资
                $array[2] = $all
                    ->where($where)
                    ->where('sales_staff_id', $val['id'])
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
                //有效
                $array[3] = $valid
                    ->where($where)
                    ->where('is_valid', 1)
                    ->where('sales_staff_id', $val['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //待定
                $array[4] = $valid
                    ->where($where)
                    ->where('is_valid', 2)
                    ->where('sales_staff_id', $val['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //无效
                $array[5] = $valid
                    ->where($where)
                    ->where('is_valid', 3)
                    ->where('sales_staff_id', $val['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //有效率
                $array[6] = sprintf('%.2f', $array[3] / $array[2] * 100) . '%';
                //无效率
                $array[7] = sprintf('%.2f', $array[5] / $array[2] * 100) . '%';
                //待定率
                $array[8] = sprintf('%.2f', $array[4] / $array[2] * 100) . '%';
                //微信/QQ  存在微信或QQ 计算一项
                $array[9] = $valid
                    ->where($where)
                    ->where('is_first_tel', null)
                    ->where('sales_staff_id', $val['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //转化手机数 原来没有，后来添加
                $array[10] = $valid
                    ->where($where)
                    ->where('customer_tel', '<>', '')
                    ->where('is_first_tel', null)
                    ->where('sales_staff_id', $val['id'])
                    ->where('tel_time', 'between time', [$start, $end])
                    ->count();
                //转化手机率 转化手机数/第一次没获取到手机的客资数量
                $array[11] = number_format($array[10] / $array[9] * 100, 2) . '%';
                //总手机数
                $array[12] = $valid
                    ->where($where)
                    ->where('customer_tel', '<>', '')
                    ->where('sales_staff_id', $val['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();

                array_push($returnData, $array);
                $num['jr'] += $array[2];//接入毛客资
                $num['yx'] += $array[3];//有效
                $num['dd'] += $array[4];//待定
                $num['wx'] += $array[5];//无效
                $num['wq'] += $array[9];//微信QQ
                $num['noTel'] += $array[10];//转手机数
                $num['allTel'] += $array[12];//总手机数
//                $num['noTelRate'] += $array[6];//转手机率

//                $num['yyRate'] += $array[9];//邀约转化率
//                $num['succRate'] += $array[10];//成交率
//                $num['orderRate'] += $array[11];//订单转化率
//                $num['validRate'] += $array[12];//有效率
            }
            $arr = [];
            $total[0] = $arr[0] = '';
            $total[1] = $arr[1] = '总计';
            $total[2] += $arr[2] += $num['jr'];
            $total[3] += $arr[3] += $num['yx'];
            $total[4] += $arr[4] += $num['dd'];
            $total[5] += $arr[5] += $num['wx'];
            $total[6] = $arr[6] = '';
            $total[7] = $arr[7] = '';
            $total[8] = $arr[8] = '';
            $total[9] += $arr[9] += $num['wq'];
            $total[10] += $arr[10] += $num['noTel'];
            $total[11] = $arr[11] = '';
            $total[12] += $arr[12] += $num['allTel'];
            array_push($returnData, $arr);
        }*/


//        array_push($returnData, $total);
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            unset($returnData[0]);
            $file = '网销综合数据分析1.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
    }

    //网销小组数据统计
    public function wx_group1()
    {
        // 权限
        $auth = check_right('menu1521352658');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        //消费类型
//        $consumptionType=controller("Customer","lib")->consumptionType();
//        $this->assign("consumptionType",$consumptionType);
        // 来源渠道
        $channels = controller('crm/Customer', 'lib')->getChannel();
        $this->assign('channel', $channels);
        // 客资标记
        $signs = controller('crm/Setting', 'lib')->gettrackingKmarkerList();
        $this->assign('signs', $signs);
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //获取方式
        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' => session('shop_code')));
        $this->assign("accessModel", $accessModel);
        return $this->fetch();
    }

    public function wx_group_data1()
    {
        set_time_limit(0);
        $time1 = time();
        // 权限
        $auth = check_right('menu1521352658');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $title = ['序号','组名', '姓名', '轮位客资', '有效客资', '进店数', '进店数(其它类型)', '进店率', '录入订单数', '网络订单数', '其它类型订单数', '成交率', '流失(进店未成交)', '流失率', '套系金额(其它类型)', '实收金额(其它类型)', '余款金额(其它类型)', '套系金额', '实收金额', '余款金额', '套系均价', '总客资成单率', '预付定金', '有效成单率'];
        $data = input();

        $shopCode = $data['shop_code'];
        //获取店下的小组
        $groupList = $this->groupList($shopCode);
        if (empty($groupList)) {
            $return = ['code' => 100, 'msg' => '暂无小组，请先去设置小组', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $returnData = [];
        for ($i = 0; $i < count($title); $i++) {
            $returnData[0][$i] = $title[$i];
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        // 时间区域
        if ($data['timeArea']) {
            $start = date('Y-m-d', strtotime($timeArea[0]));
            $end = date('Y-m-d 23:59:59', strtotime('+1 day', strtotime($timeArea[1])));
        } else {
            $start = 0;
            $end = date('Y-m-d 23:59:59', time());
        }
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.customer_type'] = 1;
        $where['c.shop_code'] = $shopCode;
//        if($data['consultation_type_id']){
//            $whereC['consultation_type_id'] = $data['consultation_type_id'];
//        }
        $consultation_type_info = db('s_sta_setting')->where('shop_code', $shopCode)->find();
        $all = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 3) {
            if ($consultation_type_info['all_customer_consumptiontype']) {
                $all->where('consultation_type_id', 'in', $consultation_type_info['all_customer_consumptiontype']);
            }
        }
        $valid = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 3) {
            if ($consultation_type_info['valid_customer_consumptiontype']) {
                $valid->where('consultation_type_id', 'in', $consultation_type_info['valid_customer_consumptiontype']);
            }
        }
        $into = db('c_customerinfo')->alias('c');
        $noInto = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 3) {
            if ($consultation_type_info['into_customer_consumptiontype']) {
                $into->where('consultation_type_id', 'in', $consultation_type_info['into_customer_consumptiontype']);
                $noInto->where('consultation_type_id', 'not in', $consultation_type_info['into_customer_consumptiontype']);
            }
        }
        $order = db('c_customerinfo')->alias('c');
        $order1 = db('c_customerinfo')->alias('c');
        $order2 = db('c_customerinfo')->alias('c');
        $order3 = db('c_customerinfo')->alias('c');
        $order4 = db('c_customerinfo')->alias('c');
        $order5 = db('c_customerinfo')->alias('c');
        $order6 = db('c_customerinfo')->alias('c');
        $noOrder = db('c_customerinfo')->alias('c');
        $noOrder1 = db('c_customerinfo')->alias('c');
        if ($consultation_type_info['is_marketing'] == 3) {
            if ($consultation_type_info['order_customer_consumptiontype']) {
                $order->where('c.consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order1->where('c.consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order2->where('c.consultation_type_id', 'not in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order3->where('c.consultation_type_id', 'not in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order4->where('c.consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order5->where('c.consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $order6->where('c.consultation_type_id', 'in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $noOrder->where('c.consultation_type_id', 'not in',
                    $consultation_type_info['order_customer_consumptiontype']);
                $noOrder1->where('c.consultation_type_id', 'not in',
                    $consultation_type_info['order_customer_consumptiontype']);
            }
        }

        if ($data['sign_id']) {
            $where['c.sign_id'] = $data['sign_id'];
        }
        if ($data['customer_channel_id']) {
            $where['c.customer_channel_id'] = $data['customer_channel_id'];
        }
//        if($data['accessModel_id']){
//            $where['access_model_id'] = $data['accessModel_id'];
//        }

        if ($data['province_id']) {
            $where['c.province_id'] = $data['province_id'];
        }
        if ($data['city_id']) {
            $where['c.city_id'] = $data['city_id'];
        }
        //组内所有人
        $staff = db('c_staff_group')->alias('g')->join('c_staff_group_relation r','g.id=r.group_id')
            ->where('g.shop_code',$shopCode)
            ->field('g.id,g.group_name,r.staff_id,r.staff_name')
            ->select();
        if(!$staff[0]['staff_name']){
            $staffIds = implode(',',array_column($staff,'staff_id'));
            $url = "5a18e3fa516a1";
            $res = sx_call($url,array('staff_id'=>$staffIds));
            $staffNames = [];

            if($res['code'] == 200){
                $info = $res['data'];
                foreach($info as $key=>$val){
                    $staffNames[$val['id']] = $val['staffname'];
                }
            }else{
                $return = ['code' => 100, 'msg' => '批量查询小组人员信息失败', 'count' => 0, 'data' => ''];
                return json($return);
            }
        }

        //接入毛客资
        $allCustomer = $all->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.dj_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //有效
        $validCustomer = $valid->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.is_valid', 1)
            ->where('c.yx_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //邀约 配置的消费类型
        $yy =$into->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.is_intostore', 2)
            ->where('c.syjd_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //邀约 其他消费类型
        $anotherYY =$noInto->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.is_intostore', 2)
            ->where('c.syjd_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //新单（实际婚纱有效定单数）
        $newOrder = $order->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //网络新单
        $onLineNewOrder = $order1->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.order_type', 1)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');

        //其他类型新单
        $anotherNewOrder = $order2->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');

        //流失
        $loss = $order3->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.is_intostore', 2)
            ->where('c.fact_money', 0)
            ->where('c.syjd_day', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('count(c.id) as num,c.sales_staff,g.group_name','r.staff_id');
        //套系金额 套系金额累计（按订单时间计算）其他类型
        $anotherTotal = $noOrder->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('sum(c.totalpay_money) as sum,c.sales_staff,g.group_name','r.staff_id');
        //实收金额累计(按订单时间计算)其他类型
        $anotherFactMoney = $noOrder1->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('sum(c.fact_money) as sum,c.sales_staff,g.group_name','r.staff_id');

        //套系金额 套系金额累计（按订单时间计算）设定类型
        $totalMoney = $order4->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('sum(c.totalpay_money) as sum,c.sales_staff,g.group_name','r.staff_id');
        //实收金额累计(按订单时间计算)
        $factMoney = $order5->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('order_start_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('sum(c.fact_money) as sum,c.sales_staff,g.group_name','r.staff_id');
        //预付定金 实收金额大于0，低于有效订单标准，的实收累计（订单时间计算）
        $dj = $order6->join('c_staff_group_relation r','c.sales_staff_id=r.staff_id')->join
        ('c_staff_group g','g.id=r.group_id')
            ->where($where)
            ->where('c.is_success', 3)
            ->where('c.fact_money', '>', 0)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->group('r.staff_id')
            ->order('g.id desc')
            ->column('sum(c.fact_money) as sum,c.sales_staff,g.group_name','r.staff_id');
        $returnData = [];
        $arr = [];
        $px = [];
        $arr['id'] = count($staff)+1;
        $arr['name'] = '';
        $arr['staff_name'] = '总计';
        $i = 1;
        //第一个小组
        $gid = $staff[0]['id'];
        //最后一个小组
        $last = end($staff);
        $lastSid = $last['staff_id'];
        $group = [];
        foreach($staff as $k=>$v){
            //小组总计
            $group[$v['id']]['id'] = '';
            $group[$v['id']]['name'] = '';
            $group[$v['id']]['staff_name'] = '总计';
            $group[$v['id']]['jrCus'] += $allCustomer[$v['staff_id']]['num'] ? $allCustomer[$v['staff_id']]['num'] : 0;//轮位客资
            $group[$v['id']]['valid'] += $validCustomer[$v['staff_id']]['num'] ? $validCustomer[$v['staff_id']]['num'] : 0;//有效客资
            $group[$v['id']]['yy'] += $yy[$v['staff_id']]['num'] ? $yy[$v['staff_id']]['num'] : 0;//进店数
            $group[$v['id']]['anotherYY'] += $anotherYY[$v['staff_id']]['num'] ? $anotherYY[$v['staff_id']]['num'] : 0;//进店数(其它类型)
            $group[$v['id']]['intoRate'] = sprintf('%.2f',$group[$v['id']]['yy']/$group[$v['id']]['jrCus'] * 100).'%';//进店率  进店/接入客资
            $group[$v['id']]['newOrder'] += $newOrder[$v['staff_id']]['num'] ? $newOrder[$v['staff_id']]['num'] : 0;//录入订单数
            $group[$v['id']]['onLineNewOrder'] += $onLineNewOrder[$v['staff_id']]['num'] ? $onLineNewOrder[$v['staff_id']]['num'] : 0;//网络订单数
            $group[$v['id']]['anotherNewOrder'] += $anotherNewOrder[$v['staff_id']]['num'] ? $anotherNewOrder[$v['staff_id']]['num'] : 0;//其它类型订单数
            $group[$v['id']]['cjRate'] = sprintf('%.2f',$group[$v['id']]['newOrder']/$group[$v['id']]['yy'] * 100).'%';//成交率 订单数/进店数
            $group[$v['id']]['loss'] += $loss[$v['staff_id']]['num'] ? $loss[$v['staff_id']]['num'] : 0;//流失(进店未成交)进店并且实收金额=0的（按进店时间计算）
            $group[$v['id']]['lossRate'] = sprintf('%.2f',$group[$v['id']]['loss']/$group[$v['id']]['yy'] * 100).'%';//流失率 流失/进店
            $group[$v['id']]['anotherTotal'] += $anotherTotal[$v['staff_id']]['sum'] ? $anotherTotal[$v['staff_id']]['sum'] : 0;//套系金额
            $group[$v['id']]['anotherFactMoney'] += $anotherFactMoney[$v['staff_id']]['sum'] ? $anotherFactMoney[$v['staff_id']]['sum'] : 0;//实收金额(其它类型)
            $group[$v['id']]['anotherYK'] += $group[$v['id']]['anotherTotal']-$group[$v['id']]['anotherFactMoney'] > 0 ? $group[$v['id']]['anotherTotal']-$group[$v['id']]['anotherFactMoney'] : 0;//余款金额(其它类型)
            $group[$v['id']]['totalMoney'] += $totalMoney[$v['staff_id']]['sum'] ? $totalMoney[$v['staff_id']]['sum'] : 0;//套系金额
            $group[$v['id']]['factMoney'] += $factMoney[$v['staff_id']]['sum'] ? $factMoney[$v['staff_id']]['sum'] : 0;//实收金额
            $group[$v['id']]['YK'] += $group[$v['id']]['totalMoney']-$group[$v['id']]['factMoney'] > 0 ? $group[$v['id']]['totalMoney']-$group[$v['id']]['factMoney'] : 0;//余款金额
            $group[$v['id']]['totalAVG'] += $group[$v['id']]['totalMoney']/$group[$v['id']]['newOrder'] > 0 ? sprintf('%.2f',$group[$v['id']]['totalMoney']/$group[$v['id']]['newOrder']) : 0;//套系均价
            $group[$v['id']]['allCusOrderRate'] = sprintf('%.2f',$group[$v['id']]['newOrder']/$group[$v['id']]['jrCus'] * 100).'%';//总客资成单率
            $group[$v['id']]['dj'] += $dj[$v['staff_id']]['sum'] ? $dj[$v['staff_id']]['sum'] : 0;//预付定金
            $group[$v['id']]['validOrderRate'] = sprintf('%.2f',$group[$v['id']]['newOrder']/$group[$v['id']]['valid'] * 100).'%';//有效成单率

            $px['id'] = $i;
            $px['name'] = $v['group_name'];
            $px['staff_name'] = $v['staff_name'] ? $v['staff_name'] : $staffNames[$v['staff_id']];
            $px['jrCus'] = $allCustomer[$v['staff_id']]['num'] ? $allCustomer[$v['staff_id']]['num'] : 0;//轮位客资
            $px['valid'] = $validCustomer[$v['staff_id']]['num'] ? $validCustomer[$v['staff_id']]['num'] : 0;//有效客资
            $px['yy'] = $yy[$v['staff_id']]['num'] ? $yy[$v['staff_id']]['num'] : 0;//进店数
            $px['anotherYY'] = $anotherYY[$v['staff_id']]['num'] ? $anotherYY[$v['staff_id']]['num'] : 0;//进店数(其它类型)
            $px['intoRate'] = sprintf('%.2f',$px['yy']/$px['jrCus'] * 100).'%';//进店率  进店/接入客资
            $px['newOrder'] = $newOrder[$v['staff_id']]['num'] ? $newOrder[$v['staff_id']]['num'] : 0;//录入订单数
            $px['onLineNewOrder'] = $onLineNewOrder[$v['staff_id']]['num'] ? $onLineNewOrder[$v['staff_id']]['num'] : 0;//网络订单数
            $px['anotherNewOrder'] = $anotherNewOrder[$v['staff_id']]['num'] ? $anotherNewOrder[$v['staff_id']]['num'] : 0;//其它类型订单数
            $px['cjRate'] = sprintf('%.2f',$px['newOrder']/$px['yy'] * 100).'%';//成交率 订单数/进店数
            $px['loss'] = $loss[$v['staff_id']]['num'] ? $loss[$v['staff_id']]['num'] : 0;//流失(进店未成交)进店并且实收金额=0的（按进店时间计算）
            $px['lossRate'] = sprintf('%.2f',$px['loss']/$px['yy'] * 100).'%';//流失率 流失/进店
            $px['anotherTotal'] = $anotherTotal[$v['staff_id']]['sum'] ? $anotherTotal[$v['staff_id']]['sum'] : 0;//套系金额
            $px['anotherFactMoney'] = $anotherFactMoney[$v['staff_id']]['sum'] ? $anotherFactMoney[$v['staff_id']]['sum'] : 0;//实收金额(其它类型)
            $px['anotherYK'] = $px['anotherTotal']-$px['anotherFactMoney'] > 0 ? $px['anotherTotal']-$px['anotherFactMoney'] : 0;//余款金额(其它类型)
            $px['totalMoney'] = $totalMoney[$v['staff_id']]['sum'] ? $totalMoney[$v['staff_id']]['sum'] : 0;//套系金额
            $px['factMoney'] = $factMoney[$v['staff_id']]['sum'] ? $factMoney[$v['staff_id']]['sum'] : 0;//实收金额
            $px['YK'] = $px['totalMoney']-$px['factMoney'] > 0 ? $px['totalMoney']-$px['factMoney'] : 0;//余款金额
            $px['totalAVG'] = $px['totalMoney']/$px['newOrder'] > 0 ? sprintf('%.2f',$px['totalMoney']/$px['newOrder']) : 0;//套系均价
            $px['allCusOrderRate'] = sprintf('%.2f',$px['newOrder']/$px['jrCus'] * 100).'%';//总客资成单率
            $px['dj'] = $dj[$v['staff_id']]['sum'] ? $dj[$v['staff_id']]['sum'] : 0;//预付定金
            $px['validOrderRate'] = sprintf('%.2f',$px['newOrder']/$px['valid'] * 100).'%';//有效成单率
            if((!empty($gid) && ($gid != $v['id']))){
                $returnData[]= $group[$gid];
                $gid = $v['id'];
            }
            $returnData[] = $px;
            if($v['staff_id'] == $lastSid){
                $returnData[]= $group[$gid];
            }
            $arr['jrCus'] += $px['jrCus'];
            $arr['valid'] += $px['valid'];
            $arr['yy'] += $px['yy'];
            $arr['anotherYY'] += $px['anotherYY'];
            $arr['newOrder'] += $px['newOrder'];
            $arr['onLineNewOrder'] += $px['onLineNewOrder'];
            $arr['anotherNewOrder'] += $px['anotherNewOrder'];
            $arr['loss'] += $px['loss'];
            $arr['anotherTotal'] += floatval($px['anotherTotal']);
            $arr['anotherFactMoney'] += floatval($px['anotherFactMoney']);
            $arr['anotherYK'] += floatval($px['anotherYK']);
            $arr['totalMoney'] += floatval($px['totalMoney']);
            $arr['factMoney'] += floatval($px['factMoney']);
            $arr['YK'] += floatval($px['YK']);
            $arr['dj'] += $px['dj'];
            $i++;
        }
        $arr['intoRate'] = sprintf('%.2f',$arr['yy']/$arr['jrCus'] * 100).'%';//进店率  进店/接入客资
        $arr['cjRate'] = sprintf('%.2f',$arr['newOrder']/$arr['yy'] * 100).'%';//成交率 订单数/进店数
        $arr['lossRate'] = sprintf('%.2f',$arr['loss']/$arr['yy'] * 100).'%';//流失率 流失/进店
        $arr['totalAVG'] = $arr['totalMoney']/$arr['newOrder'] > 0 ? sprintf('%.2f',$arr['totalMoney']/$arr['newOrder']) : 0;//套系均价
        $arr['allCusOrderRate'] = sprintf('%.2f',$arr['newOrder']/$arr['jrCus'] * 100).'%';//总客资成单率
        $arr['validOrderRate'] = sprintf('%.2f',$arr['newOrder']/$arr['valid'] * 100).'%';//有效成单率
        array_push($returnData,$arr);
        /*$total = [];
        foreach ($groupList as $k => $v) {
            //获取小组下的人员
            $info = db('c_staff_group_relation')->where('group_id', $v['id'])->select();
            $staffIds = array_column($info, 'staff_id');//小组内人员数组
            $staffs = $this->getStaffsInfo($staffIds);
            $num = [];
            foreach ($staffs as $key => $val) {
                $array = [];
                $array[0] = $v['group_name'];
                $array[1] = $val['staffname'];
                //接入毛客资
                $array[2] = $all
                    ->where($where)
                    ->where('sales_staff_id', $val['id'])
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
                //有效
                $array[3] = $valid
                    ->where($where)
                    ->where('is_valid', 1)
                    ->where('sales_staff_id', $val['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //邀约(实际进店数量)
                $array[4] = $into
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('sales_staff_id', $val['id'])
                    ->where('syjd_day', 'between time', [$start, $end])
                    ->count();
                $array[5] = $noInto
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('sales_staff_id', $val['id'])
                    ->where('syjd_day', 'between time', [$start, $end])
                    ->count();
                //进店率 进店/有效
                $array[6] = sprintf('%.2f', $array[4] / $array[2] * 100) . '%';
                //新单（实际婚纱有效定单数）
                $array[7] = $order
                    ->where($where)
                    ->where('order_type', 2)
                    ->where('is_success', 1)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                $array[8] = $order
                    ->where($where)
                    ->where('order_type', 1)
                    ->where('is_success', 1)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                $array[9] = $noOrder
                    ->where($where)
                    ->where('order_type', 2)
                    ->where('is_success', 1)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //成交率 订单数/进店数
                $array[10] = number_format($array[7] / $array[4] * 100, 2) . '%';
                //流失(进店未成交)  进店并且实收金额=0的（按进店时间计算）
                $array[11] = $order
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('fact_money', 0)
                    ->where('sales_staff_id', $val['id'])
                    ->where('syjd_day', 'between time', [$start, $end])
                    ->count();
                //流失率 流失/进店数
                $array[12] = number_format($array[11] / $array[4] * 100, 2) . '%';
                //套系金额 套系金额累计（按订单时间计算）
                $array[13] = $noOrder
                    ->where($where)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_start_time', 'between time', [$start, $end])
                    ->sum('totalpay_money');
                //实收金额累计(按订单时间计算)
                $array[14] = $noOrder
                    ->where($where)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_start_time', 'between time', [$start, $end])
                    ->sum('fact_money');
                //余款金额累计（按订单时间计算）
                $array[15] = $array[13] - $array[14];
                //套系金额 套系金额累计（按订单时间计算）
                $array[16] = $order
                    ->where($where)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_start_time', 'between time', [$start, $end])
                    ->sum('totalpay_money');
                //实收金额累计(按订单时间计算)
                $array[17] = $order
                    ->where($where)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_start_time', 'between time', [$start, $end])
                    ->sum('fact_money');
                //余款金额累计（按订单时间计算）
                $array[18] = $array[16] - $array[17];
                //套系均价 套系金额/订单数
                $array[19] = sprintf('%.2f', $array[16] / $array[7]);
                //总客资成单率 订单数/总客资
                $array[20] = sprintf('%.2f', $array[7] / $array[2]) . '%';
                //预付定金 实收金额大于0，低于有效订单标准，的实收累计（订单时间计算）
                $array[21] = $order
                    ->where($where)
                    ->where('is_success', 3)
                    ->where('fact_money', '>', 0)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_start_time', 'between time', [$start, $end])
                    ->sum('fact_money');
                //有效成单率 订单数/有效客
                $array[22] = sprintf('%.2f', $array[7] / $array[3]) . '%';

                array_push($returnData, $array);
                $num['jr'] += $array[2];//接入毛客资
                $num['yx'] += $array[3];//有效
                $num['yy'] += $array[4];//邀约(进店)
                $num['ayy'] += $array[5];//邀约(进店)
                $num['newOrder'] += $array[7];//录入新单
                $num['newOrder1'] += $array[8];//线上新单
                $num['anewOrder'] += $array[8];//其它新单
                $num['ls'] += $array[11];//流失
                $num['another_total_money'] += floatval($array[13]);//套系金额-其它消费类型
                $num['another_fact_money'] += floatval($array[14]);//实收金额-其它消费类型
                $num['another_yu_money'] += floatval($array[15]);//余款金额-其它消费类型
                $num['total_money'] += floatval($array[16]);//套系金额
                $num['fact_money'] += floatval($array[17]);//实收金额
                $num['yu_money'] += floatval($array[18]);//余款金额
                $num['yufu_money'] += floatval($array[20]);//余款金额
            }
            $arr = [];
            $total[0] = $arr[0] = '';
            $total[1] = $arr[1] = '总计';
            $total[2] += $arr[2] += $num['jr'];
            $total[3] += $arr[3] += $num['yx'];
            $total[4] += $arr[4] += $num['yy'];//邀约(进店)
            $total[5] += $arr[5] += $num['nyy'];//邀约(进店)
            $total[6] = $arr[6] = '';
            $total[7] += $arr[7] += $num['newOrder'];
            $total[8] += $arr[8] += $num['newOrder1'];
            $total[9] += $arr[9] += $num['anewOrder'];
            $total[10] = $arr[10] = '';
            $total[11] += $arr[11] += $num['ls'];
            $total[12] = $arr[12] = '';
            $total[13] += $arr[13] += floatval($num['another_total_money']);
            $total[14] += $arr[14] += floatval($num['another_fact_money']);
            $total[15] += $arr[15] += floatval($num['another_yu_money']);
            $total[16] += $arr[16] += floatval($num['total_money']);
            $total[17] += $arr[17] += floatval($num['fact_money']);
            $total[18] += $arr[18] += floatval($num['yu_money']);
            $total[19] += $arr[19] += $arr[16] / $arr[7];
            $total[20] = $arr[20] = '';
            $total[21] = $arr[21] = '';
            $total[22] = $arr[22] = '';
            array_push($returnData, $arr);
        }*/

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            unset($returnData[0]);
            $file = '网销综合数据分析2.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {

            return json($return);
        }
    }

    //网销小组邀约(进店)统计
    public function wx_group_jd()
    {
        // 权限
        $auth = check_right('menu1521352682');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        $this->assign('month', date('Y-m'));
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function wx_group_jd_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1521352682');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $title = ['组名', '姓名', '实际达成', '目标', '差额', '达成比'];

        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');

        if (!$shop_code) {
            $return = ['code' => 100, 'msg' => '请选择部门（店）' . $shop_code];
            return json($return);
        }

        //获取店下的小组
        $groupList = $this->groupList($shop_code);
        $returnData = [];
        $data = input();
        $timeArea = explode('-', $data['timeArea']);
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        $time = getdateArea($data['timeArea']);
        // 时间区域
        if ($data['timeArea']) {
            $year = $timeArea[0];
            $month = $timeArea[1];
            $start = $time[0];
            $end = $time[1];
        } else {
            $year = date('Y');
            $month = date('m');
            $start = date('Y-m', time());
            $end = date('Y-m-d H:i:s', time());
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['shop_code'] = $shop_code;
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        foreach ($groupList as $k => $v) {
            //获取小组下的人员
            $info = db('c_staff_group_relation')->where('group_id', $v['id'])->select();
            $staffIds = array_column($info, 'staff_id');//小组内人员数组
            $staffs = $this->getStaffsInfo($staffIds);
            foreach ($staffs as $key => $val) {
                $arr = [];
                $arr['group_name'] = $v['group_name'];
                $arr['staff_name'] = $val['staffname'];
                //邀约（进店）
                $arr['sj_num'] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('sales_staff_id', $val['id'])
                    ->where('syjd_day', 'between time', [$start, $end])
                    ->count();
                //目标
                //通过人查目标
                $goal = db('s_kpi_staffgoal')
                    ->where('staff_id', $val['id'])
                    ->where('flag', 'staff')
                    ->where('year', $year)
                    ->where('kpi_id', 'inviteIntoCustomerNumber')
                    ->where('month', $month)
                    ->where('shop_code', $shop_code)
                    ->value('kpi_value');
                //通过岗位查
                if (empty($goal)) {
                    $goal = db('s_kpi_staffgoal')
                        ->where('position_id', $val['main_position_id'])
                        ->where('flag', 'position')
                        ->where('year', $year)
                        ->where('month', $month)
                        ->where('shop_code', $shop_code)
                        ->where('kpi_id', 'inviteIntoCustomerNumber')
                        ->value('kpi_value');
                }
                $arr['goal'] = $goal ? $goal : 0;
                $arr['diff'] = $arr['goal'] - $arr['sj_num'];
                $arr['rate'] = number_format($arr['sj_num'] / $arr['goal'] * 100, 2) . '%';
                array_push($returnData, $arr);
            }
        }
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $file = '网销小组员工邀约(进店)排名.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 200, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }

    //网销小组新单统计
    public function wx_group_new_order()
    {
        // 权限
        $auth = check_right('menu1521352703');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        $this->assign('month', date('Y-m'));
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function wx_group_new_order_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1521352703');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $title = ['组名', '姓名', '实际达成', '目标', '差额', '达成比'];

        $data = input();
        $brandclass_id = (int)$data['brandclass_id'];
        $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');

//        if (!$shop_code) {
//            $return = ['code'=>100,'msg'=>'请选择部门（店）'.$shop_code];
//            return json($return);
//        }

        //获取店下的小组
        $groupList = $this->groupList($shop_code);
        $returnData = [];
        $data = input();
        $timeArea = explode('-', $data['timeArea']);
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        $time = getdateArea($data['timeArea']);
        // 时间区域
        if ($data['timeArea']) {
            $year = $timeArea[0];
            $month = $timeArea[1];
            $start = $time[0];
            $end = $time[1];
        } else {
            $year = date('Y');
            $month = date('m');
            $start = date('Y-m', time());
            $end = date('Y-m-d H:i:s', time());
        }
        $where['shop_code'] = $shop_code;
        $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'];
        }

        foreach ($groupList as $k => $v) {
            //获取小组下的人员
            $info = db('c_staff_group_relation')->where('group_id', $v['id'])->select();
            $staffIds = array_column($info, 'staff_id');//小组内人员数组
            $staffs = $this->getStaffsInfo($staffIds);
            foreach ($staffs as $key => $val) {
                $arr = [];
                $arr['group_name'] = $v['group_name'];
                $arr['staff_name'] = $val['staffname'];
                //新单
                $arr['sj_num'] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 1)
                    ->where('sales_staff_id', $val['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //目标
                //通过人查目标
                $goal = db('s_kpi_staffgoal')
                    ->where('staff_id', $val['id'])
                    ->where('flag', 'staff')
                    ->where('year', $year)
                    ->where('kpi_id', 'orderNumber')
                    ->where('month', $month)
                    ->where('shop_code', $shop_code)
                    ->value('kpi_value');
                //通过岗位查
                if (empty($goal)) {
                    $goal = db('s_kpi_staffgoal')
                        ->where('position_id', $val['main_position_id'])
                        ->where('flag', 'position')
                        ->where('year', $year)
                        ->where('month', $month)
                        ->where('shop_code', $shop_code)
                        ->where('kpi_id', 'orderNumber')
                        ->value('kpi_value');
                }
                $arr['goal'] = $goal ? $goal : 0;
                $arr['diff'] = $arr['goal'] - $arr['sj_num'];
                $arr['rate'] = number_format($arr['sj_num'] / $arr['goal'] * 100, 2) . '%';
                array_push($returnData, $arr);
            }
        }
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $file = '网销小组员新单排名.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 200, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }

    //网销地域统计
    public function wx_region()
    {
        // 权限
        $auth = check_right('menu1521352729');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function wx_region_data()
    {
        set_time_limit(0);
        $data = input();
        // 店面
        if (!$data['shop_code']) {
            $return = ['code' => 400, 'msg' => '请选择店面', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 省份
        if (!$data['province_id']) {
            $return = ['code' => 300, 'msg' => '请选择省份', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d', strtotime('+1 day', strtotime($timeArea[1])));

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = $data['shop_code'];
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
        }
        //获取城市
        $citys = controller('crm/Customer', 'lib')->address(['type' => 2, 'pid' => $data['province_id'], 'shop_code' => $data
        ['shop_code']]);
        $returnData = [];
//        array_push($returnData,$title);
        foreach ($citys as $k => $v) {
            $arr = [];
            $arr['name'] = $v['name'];
            //轮位客资
            $arr['jr_num'] = db('c_customerinfo')
                ->where($where)
                ->where('is_fp', 1)
                ->where('city_id', $v['id'])
                ->where('jr_day', 'between time', [$start, $end])
                ->count();
            //有效客资
            $arr['valid'] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 1)
                ->where('city_id', $v['id'])
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            //邀约客资
            $arr['jd'] = db('c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
                ->where('city_id', $v['id'])
                ->where('syjd_day', 'between time', [$start, $end])
                ->count();
            //新单
            $arr['order'] = db('c_customerinfo')
                ->where($where)
                ->where('is_success', 1)
                ->where('city_id', $v['id'])
                ->where('order_day', 'between time', [$start, $end])
                ->count();
            //营收
            $arr['factMoney'] = db('c_customerinfo')
                ->where($where)
                ->where('is_success', 1)
                ->where('city_id', $v['id'])
                ->where('order_start_time', 'between time', [$start, $end])
                ->sum('fact_money');
            //邀约转化率
            $arr['intoRate'] = number_format($arr['jd'] / $arr['valid'] * 100, 2) . '%';
            //成交率
            $arr['succRate'] = number_format($arr['order'] / $arr['jd'] * 100, 2) . '%';
            //新单/有效
            $arr['orderRate'] = number_format($arr['order'] / $arr['valid'] * 100, 2) . '%';
            //有效率
            $arr['validRate'] = number_format($arr['valid'] / $arr['jr_num'] * 100, 2) . '%';
            array_push($returnData, $arr);
        }
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = ['地域', '轮位客资', '有效', '邀约', '新单', '营收', '邀约转化率', '成交率', '新单/有效', '有效率'];
            $file = '网销地域统计.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 200, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }

    //电商目标达成统计
    public function ds_goal()
    {
        // 权限
        $auth = check_right('menu1521352748');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function ds_goal_data()
    {
        set_time_limit(0);
        $data = input();
        // 省份
        if (!$data['province_id']) {
            $return = ['code' => 300, 'msg' => '请选择省份', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode('-', $data['timeArea']);
        $year = $timeArea[0];
        $month = $timeArea[1];

        $time = getdateArea($data['timeArea']);
        $start = $time[0];
        $end = $time[1];

        $position_name = session('main_position_name');
        $staff_id = session('staff_id');
        $shop_code = session('shop_code');

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = session('shop_code');
//        if($data['consultation_type_id']){
//            $cusWhere['consultation_type_id'] = $data['consultation_type_id'];
//        }
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
        }
        //获取城市
        $citys = controller('crm/Customer', 'lib')->address(['type' => 2, 'pid' => $data['province_id']]);
        $returnData = [];
        $ids = array_column($citys, 'id');
        $channels = db('s_channel')->where('shop_code', $shop_code)->select();

        $returnData = [];
        $title[0] = $year . '年' . $month . '月目标';
        foreach ($channels as $ke => $v) {
            $title[$ke + 1] = $v['channel_name'];
        }
        $title[count($channels) + 1] = '总目标';
        array_push($returnData, $title);

        $kpiWhere['shop_code'] = $shop_code;
        $kpiWhere['year'] = $year;
        $kpiWhere['month'] = $month;
        $kpiWhere['kpi_id'] = 'newCustomerNum';
        foreach ($citys as $k => $v) {
            $arr = [];
            $arr[0] = $v['name'];
            $kpiNum = 0;
            foreach ($channels as $key => $val) {
                $kpi = db('s_kpi_staffgoal')
                    ->where('flag', 'staff')
                    ->where('city_id', $v['id'])
                    ->where('channel_id', $val['id'])
                    ->where('staff_id', $staff_id)
                    ->where($kpiWhere)
                    ->find();
                if (empty($kpi)) {
                    $kpi = db('s_kpi_staffgoal')
                        ->where('city_id', $v['id'])
                        ->where('flag', 'position')
                        ->where('channel_id', $val['id'])
                        ->where('position_name', $position_name)
                        ->where($kpiWhere)
                        ->find();
                    if (empty($kpi)) {
                        $kpi['kpi_value'] = 0;
                    }
                }

                $arr[$key + 1] = $kpi['kpi_value'];
                $kpiNum += $arr[$key + 1];
            }
            $arr[count($channels) + 1] = $kpiNum;
            array_push($returnData, $arr);
        }
        //总计
        $channel_total = ['总计'];
        foreach ($channels as $c => $n) {
            $chNum = 0;
            foreach ($returnData as $k => $v) {
                $chNum += $returnData[$k + 1][$c + 1];
            }
            array_push($channel_total, $chNum);
        }
        $allNum = 0;
        foreach ($returnData as $k => $v) {
            $allNum += $returnData[$k + 1][count($channels) + 1];
        }
        array_push($channel_total, $allNum);
        array_push($returnData, $channel_total);
        $goal = $returnData;
        array_push($returnData, []);
        //实际完成
        $returnData_sj = [];
        $sj[0] = '实际完成';
        foreach ($channels as $ke => $v) {
            $sj[$ke + 1] = $v['channel_name'];
        }
        $sj[count($channels) + 1] = '合计';
        array_push($returnData_sj, $sj);


        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $cusWhere['is_status'] = 1;
                $cusWhere['c_from'] = 1;
                $cusWhere['customer_type'] = 1;
                $cusWhere['city_id'] = $v['id'];
                $cusWhere['customer_channel_id'] = $val['id'];
                // 存在事业部
                if (session('brandclass_id')) {
                    $cusWhere['brandclass_id'] = session('brandclass_id');
                    $allCus = db('c_customerinfo')
                        ->where($cusWhere)
                        ->where('add_shop_code', 'in', $shop_code)
                        ->where('dj_day', 'between time', [$start, $end])
                        ->count();
                } else {
                    $allCus = db('c_customerinfo')
                        ->where($cusWhere)
                        ->where('add_shop_code', 'in', $shop_code)
                        ->where('dj_day', 'between time', [$start, $end])
                        ->count();
                }

                $cusArr[$key + 1] = $allCus;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = $cusNum;
            array_push($returnData_sj, $cusArr);
        }
        //总计
        $cus_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_sj as $k => $v) {
                $cuschNum += $returnData_sj[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allcusNum = 0;
        foreach ($returnData_sj as $k => $v) {
            $allcusNum += $returnData_sj[$k + 1][count($channels) + 1];
        }
        array_push($cus_total, $allcusNum);
        array_push($returnData_sj, $cus_total);
        $returnData = array_merge($returnData, $returnData_sj);

        array_push($returnData, []);

        //进度应完成
        $days = date('t', $data['timeArea']);
        $today = date('d');
        $returnData_jd = [];
        $sj[0] = '进度应完成';
        foreach ($channels as $ke => $v) {
            $sj[$ke + 1] = $v['channel_name'];
        }
        $sj[count($channels) + 1] = '合计';
        array_push($returnData_jd, $sj);


        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $avg = number_format($returnData[$k + 1][$key + 1] / $days, 4) * $today;
                $cusArr[$key + 1] = $avg;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = $cusNum;
            array_push($returnData_jd, $cusArr);
        }
        //总计
        $cus_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_jd as $k => $v) {
                $cuschNum += $returnData_jd[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allcusNum = 0;
        foreach ($returnData_jd as $k => $v) {
            $allcusNum += $returnData_jd[$k + 1][count($channels) + 1];
        }
        array_push($cus_total, $allcusNum);
        array_push($returnData_jd, $cus_total);
        $returnData = array_merge($returnData, $returnData_jd);

        array_push($returnData, []);


        //进度差额
        $returnData_diff = [];
        $sj[0] = '进度差额';
        foreach ($channels as $ke => $v) {
            $sj[$ke + 1] = $v['channel_name'];
        }
        $sj[count($channels) + 1] = '合计';
        array_push($returnData_diff, $sj);

//print_r($returnData_jd);die;
        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $avg = $returnData_jd[$k + 1][$key + 1] - $returnData_sj[$k + 1][$key + 1];
                $cusArr[$key + 1] = $avg;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = $cusNum;
            array_push($returnData_diff, $cusArr);
        }
        //总计
        $cus_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_jd as $k => $v) {
                $cuschNum += $returnData_diff[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allcusNum = 0;
        foreach ($returnData_jd as $k => $v) {
            $allcusNum += $returnData_diff[$k + 1][count($channels) + 1];
        }
        array_push($cus_total, $allcusNum);
        array_push($returnData_diff, $cus_total);
        $returnData = array_merge($returnData, $returnData_diff);

        array_push($returnData, []);


        //剩余目标
        $returnData_sy = [];
        $sy[0] = '剩余目标';
        foreach ($channels as $ke => $v) {
            $sy[$ke + 1] = $v['channel_name'];
        }
        $sy[count($channels) + 1] = '合计';
        array_push($returnData_sy, $sy);


        foreach ($citys as $k => $v) {
            $syArr = [];
            $syArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $cusNum = $returnData[$k + 1][$key + 1] - $returnData_sj[$k + 1][$key + 1];
                $syArr[$key + 1] = $cusNum;
                $cusNum += $syArr[$key + 1];
            }
            $syArr[count($channels) + 1] = $returnData[$k + 1][count($channels) + 1] - $returnData_sj[$k + 1][count($channels) + 1];
            array_push($returnData_sy, $syArr);
        }
        //总计
        $cus_total = ['合计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_sy as $k => $v) {
                $cuschNum += $returnData_sy[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allSy = $returnData[count($citys) + 1][count($channels) + 1] - $returnData_sj[count($citys) + 1][count($channels) + 1];
        array_push($cus_total, $allSy);

        array_push($returnData_sy, $cus_total);
        $returnData = array_merge($returnData, $returnData_sy);

        array_push($returnData, []);

        //剩余日均
        $return_syAvg = [];
        $syAvg[0] = '剩余日均';
        foreach ($channels as $ke => $v) {
            $syAvg[$ke + 1] = $v['channel_name'];
        }
        $syAvg[count($channels) + 1] = '合计';
        array_push($return_syAvg, $syAvg);


        foreach ($citys as $k => $v) {
            $syArr = [];
            $syArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $cusNum = number_format($returnData_sy[$k + 1][$key + 1] / ($days - $today), 4);
                $syArr[$key + 1] = $cusNum;
                $cusNum += $syArr[$key + 1];
            }
            $syArr[count($channels) + 1] = number_format($returnData_sy[$k + 1][count($channels) + 1] / ($days - $today), 4);
            array_push($return_syAvg, $syArr);
        }
        //总计
        $cus_total = ['合计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_sy as $k => $v) {
                $cuschNum += $return_syAvg[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allSy = number_format($returnData_sy[count($citys) + 1][count($channels) + 1] / ($days - $today), 4);
        array_push($cus_total, $allSy);

        array_push($return_syAvg, $cus_total);
        $returnData = array_merge($returnData, $return_syAvg);

        $return['code'] = 200;
        $return['msg'] = '';
        $return['count'] = count($returnData[0]);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '电商目标达成统计.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 100, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }
    //计算店面目标
    /*
     * param:$shop_code,$goal,$year,$month,$channel_id=0,$province_id=0,$city_id=0
     * */
    public function getShopGoal($param)
    {
        if ($param['shop_code']) $where['shop_code'] = $param['shop_code'];
        if ($param['kpi_id']) $where['kpi_id'] = $param['kpi_id'];
        if ($param['channel_id']) $where['channel_id'] = $param['channel_id'];
        if ($param['province_id']) $where['province_id'] = $param['province_id'];
        if ($param['city_id']) $where['city_id'] = $param['city_id'];
        $where['year'] = $param['year'] ? $param['year'] : date('Y');
        $where['month'] = $param['month'] ? $param['month'] : date('m');
        //本店下的所有人员
        $staffs = controller('crm/Statistics', 'lib')->getStaffInfoByShop($where['shop_code']);
        $num = 0;
        foreach ($staffs as $k => $v) {
            $staffGoalInfo = db('s_kpi_staffgoal')
                ->where($where)
                ->where('flag', 'staff')
                ->where('staff_id', $v['id'])
                ->sum('kpi_value');
            if (empty($staffGoalInfo)) {
                $positionGoal = db('s_kpi_staffgoal')
                    ->where($where)
                    ->where('position_id', $v['main_position_id'])
                    ->sum('kpi_value');
                if ($positionGoal) {
                    $num += $positionGoal;
                }
            } else {
                $num += $staffGoalInfo;
            }
        }
        return $num;
    }

    //电商对网销汇报报表
    public function ds_to_wx_report()
    {
        // 权限
        $auth = check_right('menu1521352381');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    //电商对网销汇报报表
    public function ds_to_wx_report_data()
    {
        set_time_limit(0);
        $inp = input();
        $returnData = [];
        $returnData[0][0] = '【常态报表3：电商--网销数据汇报】';
        $returnData[0][1] = '';
        $returnData[0][2] = '';
        $returnData[0][3] = '';

        $returnData[1][0] = '汇报单位';
        $returnData[1][1] = session('shop_name');
        $returnData[1][2] = '汇报给：';
        $returnData[1][3] = session('belong_shop_name');

        $returnData[2][0] = '汇报时间';
        $returnData[2][1] = date('Y-m-d');
        $returnData[2][2] = '';
        $returnData[2][3] = '';

        $returnData[3][0] = '目标名';
        $returnData[3][1] = '目标值';
        $returnData[3][2] = '已完成';
        $returnData[3][3] = '完成进度';

        $start = date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));

        $end = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m'), date('d'), date('Y')));

        $data = array(
            'brandclass_id' => session('brandclass_id'),
            'add_shop_code' => session('shop_code'),
            'start' => $start,
            'end' => $end,
        );
        if ($inp['consultation_type_id']) {
            $data['consultation_type_id'] = $inp['consultation_type_id'];
        }
        //有效获取
        $param['shop_code'] = session('shop_code');
        $param['kpi_id'] = 'validCustomerNumber';
        $param['start'] = date('Y-m');
        $param['end'] = date('Y-m');
        $valid = getShopGoal($param);
        $returnData[4][0] = '有效获取';
        $returnData[4][1] = $valid;
        $returnData[4][2] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($data);
        $returnData[4][3] = number_format($returnData[4][2] / $valid, 2) . '%';

        //进店量
        $param['shop_code'] = session('shop_code');
        $param['kpi_id'] = 'actualIntoCustomerNumber';
        $param['start'] = date('Y-m');
        $param['end'] = date('Y-m');
        $jd = getShopGoal($param);
        $returnData[5][0] = '进店量';
        $returnData[5][1] = $jd;
        $returnData[5][2] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($data);
        $returnData[5][3] = number_format($returnData[5][2] / $jd, 2) . '%';


        //新单量
        $param['shop_code'] = session('shop_code');
        $param['kpi_id'] = 'orderNumber';
        $param['start'] = date('Y-m');
        $param['end'] = date('Y-m');
        $order = getShopGoal($param);
        $returnData[6][0] = '新单量';
        $returnData[6][1] = $order;
        $returnData[6][2] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($data);
        $returnData[6][3] = number_format($returnData[6][2] / $order, 2) . '%';

        //转化率
        $returnData[7][0] = '转化率';
        $returnData[7][1] = '100%';
        $returnData[7][2] = number_format(($returnData[6][2] / $returnData[5][2]) * 100, 2) . '%';
        $returnData[7][3] = '';
        //======================================================
        $returnData[8][0] = '实际完成';
        $returnData[8][1] = '昨日数据';
        $returnData[8][2] = '当月累计数据';
        $returnData[8][3] = '';

        $beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $endYesterday = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;

        $dData = array(
            'brandclass_id' => session('brandclass_id'),
            'add_shop_code' => session('shop_code'),
            'start' => $beginYesterday,
            'end' => $endYesterday,
        );
        $mData = array(
            'brandclass_id' => session('brandclass_id'),
            'add_shop_code' => session('shop_code'),
            'start' => $start,
            'end' => $end,
        );
        if ($inp['consultation_type_id']) {
            $dData['consultation_type_id'] = $inp['consultation_type_id'];
            $mData['consultation_type_id'] = $inp['consultation_type_id'];
        }
        $returnData[9][0] = '毛客资数量';
        $returnData[9][1] = controller('crm/Statistics', 'lib')->sta_getCustomerNum($dData);
        $returnData[9][2] = controller('crm/Statistics', 'lib')->sta_getCustomerNum($mData);
        $returnData[9][3] = '';

        $returnData[10][0] = '有效资数量';
        $returnData[10][1] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($dData);
        $returnData[10][2] = controller('crm/Statistics', 'lib')->sta_getInvCustomerNum($mData);
        $returnData[10][3] = '';

        $returnData[11][0] = '手机获取';
        $returnData[11][1] = controller('crm/Statistics', 'lib')->sta_getTelCustomerNum($dData);
        $returnData[11][2] = controller('crm/Statistics', 'lib')->sta_getTelCustomerNum($mData);
        $returnData[11][3] = '';

        $returnData[12][0] = '总邀约';
        $returnData[12][1] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($dData);
        $returnData[12][2] = controller('crm/Statistics', 'lib')->sta_getIntoCustomerNum($mData);
        $returnData[12][3] = '';

        $returnData[13][0] = '新单';
        $returnData[13][1] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($dData);
        $returnData[13][2] = controller('crm/Statistics', 'lib')->sta_getOrderNumberNum($mData);
        $returnData[13][3] = '';

        $returnData[14][0] = '新单营收';
        $returnData[14][1] = controller('crm/Statistics', 'lib')->sta_incomeMoney($dData);
        $returnData[14][2] = controller('crm/Statistics', 'lib')->sta_incomeMoney($mData);
        $returnData[14][3] = '';

        $returnData[15][0] = '营收均价';
        $returnData[15][1] = number_format($returnData[14][1] / $returnData[13][1], 2);
        $returnData[15][2] = number_format($returnData[14][2] / $returnData[13][2], 2);
        $returnData[15][3] = '';

        $returnData[16][0] = '流失客资';
        $returnData[16][1] = controller('crm/Statistics', 'lib')->sta_get_loss_cus($dData);
        $returnData[16][2] = controller('crm/Statistics', 'lib')->sta_get_loss_cus($mData);
        $returnData[16][3] = '';

        $returnData[17][0] = '成交金额';
        $returnData[17][1] = controller('crm/Statistics', 'lib')->sta_dealMoney($dData);
        $returnData[17][2] = controller('crm/Statistics', 'lib')->sta_dealMoney($mData);
        $returnData[17][3] = '';

        $returnData[18][0] = '花费';
        $returnData[18][1] = controller('crm/Statistics', 'lib')->sta_costMoney($dData);
        $returnData[18][2] = controller('crm/Statistics', 'lib')->sta_costMoney($mData);
        $returnData[18][3] = '';

        $returnData[19][0] = '新单成本';
        $returnData[19][1] = number_format($returnData[18][1] / $returnData[13][1], 2);
        $returnData[19][2] = number_format($returnData[18][2] / $returnData[13][2], 2);
        $returnData[19][3] = '';

        $return['code'] = 200;
        $return['msg'] = '';
        $return['count'] = 4;
        $return['data'] = $returnData;
        // 导出
        if ($inp['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '电商->网销数据汇报.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 100, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }

    //电商店目标达成统计
    public function ds_shop_goal()
    {
        // 权限
        $auth = check_right('menu1521352772');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function ds_shop_goal_data()
    {
        set_time_limit(0);
        $data = input();
        // 省份
        if (!$data['province_id']) {
            $return = ['code' => 300, 'msg' => '请选择省份', 'count' => 0, 'data' => '',];
            return json($return);
        }
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = $data['timeArea'];


        $time = getdateArea($data['timeArea']);
        $start = $time[0];
        $end = $time[1];

        $position_name = session('main_position_name');
        $staff_id = session('staff_id');
        $shop_code = session('shop_code');

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['shop_code'] = session('shop_code');
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
        }
        //获取城市
        $citys = controller('crm/Customer', 'lib')->address(['type' => 2, 'pid' => $data['province_id']]);
        $returnData = [];
        $ids = array_column($citys, 'id');
        $channels = db('s_channel')->where('shop_code', $shop_code)->select();

        $returnData = [];
        $title[0] = $timeArea. '目标';
        foreach ($channels as $ke => $v) {
            $title[$ke + 1] = $v['channel_name'];
        }
        $title[count($channels) + 1] = '总目标';
        array_push($returnData, $title);


        foreach ($citys as $k => $v) {
            $arr = [];
            $arr[0] = $v['name'];
            $kpiNum = 0;
            foreach ($channels as $key => $val) {
                $kpiWhere['shop_code'] = $shop_code;
                $kpiWhere['start'] = $timeArea;
                $kpiWhere['end'] = $timeArea;
                $kpiWhere['city_id'] = $v['id'];
                $kpiWhere['channel_id'] = $val['id'];
                $kpiWhere['kpi_id'] = 'newCustomerNum';
                $kpi['kpi_value'] = getShopGoal($kpiWhere);

                $arr[$key + 1] = $kpi['kpi_value'];
                $kpiNum += $arr[$key + 1];
            }
            $arr[count($channels) + 1] = $kpiNum;
            array_push($returnData, $arr);
        }
        //总计
        $channel_total = ['总计'];
        foreach ($channels as $c => $n) {
            $chNum = 0;
            foreach ($returnData as $k => $v) {
                $chNum += $returnData[$k + 1][$c + 1];
            }
            array_push($channel_total, $chNum);
        }
        $allNum = 0;
        foreach ($returnData as $k => $v) {
            $allNum += $returnData[$k + 1][count($channels) + 1];
        }
        array_push($channel_total, $allNum);
        array_push($returnData, $channel_total);

        $goal = $returnData;

        array_push($returnData, []);
        //实际完成
        $returnData_sj = [];
        $sj[0] = '实际完成';
        foreach ($channels as $ke => $v) {
            $sj[$ke + 1] = $v['channel_name'];
        }
        $sj[count($channels) + 1] = '合计';
        array_push($returnData_sj, $sj);


        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $cusWhere['is_status'] = 1;
                $cusWhere['c_from'] = 1;
                $cusWhere['customer_type'] = 1;
                $cusWhere['city_id'] = $v['id'];
                $cusWhere['customer_channel_id'] = $val['id'];
                // 存在事业部
                if (session('brandclass_id')) {
                    $cusWhere['brandclass_id'] = session('brandclass_id');
                    $allCus = db('c_customerinfo')
                        ->where($cusWhere)
                        ->where('add_shop_code', 'in', $shop_code)
                        ->where('dj_day', 'between time', [$start, $end])
                        ->count();
                } else {
                    $allCus = db('c_customerinfo')
                        ->where($cusWhere)
                        ->where('add_shop_code', 'in', $shop_code)
                        ->where('dj_day', 'between time', [$start, $end])
                        ->count();
                }
                $cusArr[$key + 1] = $allCus;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = $cusNum;
            array_push($returnData_sj, $cusArr);
        }
        //总计
        $cus_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_sj as $k => $v) {
                $cuschNum += $returnData_sj[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allcusNum = 0;
        foreach ($returnData_sj as $k => $v) {
            $allcusNum += $returnData_sj[$k + 1][count($channels) + 1];
        }
        array_push($cus_total, $allcusNum);
        array_push($returnData_sj, $cus_total);
        $returnData = array_merge($returnData, $returnData_sj);
        $sjwc = $returnData_sj;
//        print_r($sjwc);die;
        array_push($returnData, []);
        //进度应完成
        $days = date('t', $data['timeArea']);
        $today = date('d');
        $returnData_jd = [];
        $sj[0] = '进度应完成';
        foreach ($channels as $ke => $v) {
            $sj[$ke + 1] = $v['channel_name'];
        }
        $sj[count($channels) + 1] = '合计';
        array_push($returnData_jd, $sj);


        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $avg = sprintf('%.4f', $returnData[$k + 1][$key + 1] / $days, 4) * $today;
                $cusArr[$key + 1] = $avg;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = $cusNum;
            array_push($returnData_jd, $cusArr);
        }
        //总计
        $cus_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_jd as $k => $v) {
                $cuschNum += $returnData_jd[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allcusNum = 0;
        foreach ($returnData_jd as $k => $v) {
            $allcusNum += $returnData_jd[$k + 1][count($channels) + 1];
        }
        array_push($cus_total, $allcusNum);
        array_push($returnData_jd, $cus_total);
        $returnData = array_merge($returnData, $returnData_jd);

        array_push($returnData, []);


        //进度差额
        $returnData_diff = [];
        $sj[0] = '进度差额';
        foreach ($channels as $ke => $v) {
            $sj[$ke + 1] = $v['channel_name'];
        }
        $sj[count($channels) + 1] = '合计';
        array_push($returnData_diff, $sj);

//print_r($returnData_jd);die;
        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $avg = $returnData_jd[$k + 1][$key + 1] - $returnData_sj[$k + 1][$key + 1];
                $cusArr[$key + 1] = $avg;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = $cusNum;
            array_push($returnData_diff, $cusArr);
        }
        //总计
        $cus_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_jd as $k => $v) {
                $cuschNum += $returnData_diff[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allcusNum = 0;
        foreach ($returnData_jd as $k => $v) {
            $allcusNum += $returnData_diff[$k + 1][count($channels) + 1];
        }
        array_push($cus_total, $allcusNum);
        array_push($returnData_diff, $cus_total);
        $returnData = array_merge($returnData, $returnData_diff);

        array_push($returnData, []);


        //预估到月底
        $returnData_yg = [];
        $yg[0] = '预估到月底';
        foreach ($channels as $ke => $v) {
            $yg[$ke + 1] = $v['channel_name'];
        }
        $yg[count($channels) + 1] = '合计';
        array_push($returnData_yg, $yg);
        $days = date('t');
        $today = date('d');

        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $avg = sprintf('%.4f', $sjwc[$k + 1][$key + 1] / $today * $days);
                $cusArr[$key + 1] = $avg;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = sprintf('%.4f', $sjwc[$k + 1][count($channels) + 1] / $today * $days);
            array_push($returnData_yg, $cusArr);
        }

        //总计
        $yg_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_yg as $k => $v) {
                $cuschNum += $returnData_yg[$k + 1][$c + 1];
            }
            array_push($yg_total, $cuschNum);
        }
        $ygcusNum = 0;
        foreach ($returnData_yg as $k => $v) {
            $ygcusNum += $returnData_yg[$k + 1][count($channels) + 1];
        }
        array_push($yg_total, $ygcusNum);
        array_push($returnData_yg, $yg_total);
        $returnData = array_merge($returnData, $returnData_yg);
        array_push($returnData, []);

        //预估全月差值
        $returnData_qy = [];
        $qy[0] = '预估全月差值';
        foreach ($channels as $ke => $v) {
            $qy[$ke + 1] = $v['channel_name'];
        }
        $qy[count($channels) + 1] = '合计';
        array_push($returnData_qy, $qy);

        foreach ($citys as $k => $v) {
            $cusArr = [];
            $cusArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $avg = sprintf('%.4f', $returnData_yg[$k + 1][$key + 1] - $goal[$k + 1][$key + 1], 4);
                $cusArr[$key + 1] = $avg;
                $cusNum += $cusArr[$key + 1];
            }
            $cusArr[count($channels) + 1] = $cusNum;
            array_push($returnData_qy, $cusArr);
        }
//        print_r($returnData_qy);die;
        //总计
        $qy_total = ['总计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_yg as $k => $v) {
                $cuschNum += $returnData_qy[$k + 1][$c + 1];
            }
            array_push($qy_total, $cuschNum);
        }
        $qycusNum = 0;
        foreach ($returnData_qy as $k => $v) {
            $qycusNum += $returnData_qy[$k + 1][count($channels) + 1];
        }
        array_push($qy_total, $qycusNum);
        array_push($returnData_qy, $qy_total);
        $returnData = array_merge($returnData, $returnData_qy);

        array_push($returnData, []);


        //剩余目标
        $returnData_sy = [];
        $sy[0] = '剩余目标';
        foreach ($channels as $ke => $v) {
            $sy[$ke + 1] = $v['channel_name'];
        }
        $sy[count($channels) + 1] = '合计';
        array_push($returnData_sy, $sy);


        foreach ($citys as $k => $v) {
            $syArr = [];
            $syArr[0] = $v['name'];
            $cusNum = 0;
            foreach ($channels as $key => $val) {
                $cusNum = $returnData[$k + 1][$key + 1] - $returnData_sj[$k + 1][$key + 1];
                $syArr[$key + 1] = $cusNum;
                $cusNum += $syArr[$key + 1];
            }
            $syArr[count($channels) + 1] = $returnData[$k + 1][count($channels) + 1] - $returnData_sj[$k + 1][count($channels) + 1];
            array_push($returnData_sy, $syArr);
        }
        //总计
        $cus_total = ['合计'];
        foreach ($channels as $c => $n) {
            $cuschNum = 0;
            foreach ($returnData_sy as $k => $v) {
                $cuschNum += $returnData_sy[$k + 1][$c + 1];
            }
            array_push($cus_total, $cuschNum);
        }
        $allSy = $returnData[count($citys) + 1][count($channels) + 1] - $returnData_sj[count($citys) + 1][count($channels) + 1];
        array_push($cus_total, $allSy);

        array_push($returnData_sy, $cus_total);
        $returnData = array_merge($returnData, $returnData_sy);

        array_push($returnData, []);


        $return['code'] = 200;
        $return['msg'] = '';
        $return['count'] = count($returnData[0]);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '电商渠道达成进店跟踪.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 100, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }
    //安徽
    //日统计表
    public function dayStatistics()
    {
        // 权限
        $auth = check_right('menu1522752932');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '你无权操作', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 来源渠道
        $channels = controller('crm/Customer', 'lib')->getChannel();
        $this->assign('channel', $channels);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function dayStatistics_data()
    {
        set_time_limit(0);
        // 权限
        $auth = check_right('menu1522752932');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '你无权操作', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        if (!$data['channel_id']) {
            $return = ['code' => 300, 'msg' => '请选择渠道名称', 'count' => 0, 'data' => '',];
            return json($return);
        }
//        $timeArea = explode(' - ', $data['timeArea']);
        $days = getMonthDays($data['timeArea']);
        $time1 = ' 00:00:00';
        $time2 = ' 24:00:00';

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = session('shop_code');
        $where['customer_channel_id'] = $data['channel_id'];
        if ($data['consultation_type_id']) {
            $whereT['consultation_type_id'] = $data['consultation_type_id'];
        }
        $brandclass_id = session('brandclass_id');

        $returnData = [];
        $title = array('【' . $data['channel_name'] . '】', '花费', '毛客资', '有效', '待定', '无效', '进店', '订单', '订单业绩', '实收', '毛客资成本', '有效客资成本', '订单成本', '进店率');

        array_push($returnData, $title);

        $num1 = 0;
        $num2 = 0;
        $num3 = 0;
        $num4 = 0;
        $num5 = 0;
        $num6 = 0;
        $num7 = 0;
        $num8 = 0;
        $num9 = 0;
        $num10 = 0;
        $num11 = 0;
        $num12 = 0;
        $num13 = 0;
        foreach ($days as $k => $v) {
            $arr = [];
            $arr[0] = $v;
            //花费
            $arr[1] = $cost = db('c_customer_cost')
                ->where('shop_code', session('shop_code'))
                ->where('channel_id', $data['channel_id'])
                ->where('cost_time', 'between time', [$v, $v])
                ->sum('cost_avg');
            $num1 += $arr[1];
            //毛客资
            if ($brandclass_id) {// 存在事业部
                $where['brandclass_id'] = $brandclass_id;
                $arr[2] = db('c_customerinfo')
                    ->where($where)
                    ->where('dj_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            } else {
                $arr[2] = db('c_customerinfo')
                    ->where($where)
                    ->where('dj_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            }
            $num2 += $arr[2];
            //有效客资
            if ($brandclass_id) {// 存在事业部
                $where['brandclass_id'] = $brandclass_id;
                $arr[3] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_valid', 1)
                    ->where('yx_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            } else {
                $arr[3] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_valid', 1)
                    ->where('yx_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            }
            $num3 += $arr[3];
            //待定
            if ($brandclass_id) {// 存在事业部
                $where['brandclass_id'] = $brandclass_id;
                $arr[4] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_valid', 2)
                    ->where('yx_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            } else {
                $arr[4] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_valid', 2)
                    ->where('yx_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            }
            $num4 += $arr[4];
            //无效
            if ($brandclass_id) {// 存在事业部
                $where['brandclass_id'] = $brandclass_id;
                $arr[5] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_valid', 3)
                    ->where('yx_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            } else {
                $arr[5] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_valid', 3)
                    ->where('yx_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            }
            $num5 += $arr[5];
            //进店
            if ($brandclass_id) {// 存在事业部
                $where['brandclass_id'] = $brandclass_id;
                $arr[6] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_intostore', 2)
                    ->where('syjd_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            } else {
                $arr[6] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_intostore', 2)
                    ->where('syjd_day', 'between time', [$v . $time1, $v . $time2])
                    ->count();
            }
            $num6 += $arr[6];
            //订单
            if ($brandclass_id) {// 存在事业部
                $where['brandclass_id'] = $brandclass_id;
                $info = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_success', 1)
                    ->where('order_day', 'between time', [$v . $time1, $v . $time2])
                    ->field('count(id) as num,sum(totalpay_money) as total,sum(fact_money) as fact')
                    ->find();
            } else {
                $info = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('is_success', 1)
                    ->where('order_day', 'between time', [$v . $time1, $v . $time2])
                    ->field('count(id) as num,sum(totalpay_money) as total,sum(fact_money) as fact')
                    ->find();
            }
            $arr[7] = $info['num'];
            $num7 += $arr[7];
            $arr[8] = $info['total'] ? $info['total'] : 0;
            $num8 += $arr[8];
            $arr[9] = $info['fact'] ? $info['fact'] : 0;
            $num9 += $arr[9];
            //毛客资成本
            $arr[10] = sprintf('%.2f', $arr[1] / $arr[2]);
            $num10 += floatval($arr[10]);
            //有效客资成本
            $arr[11] = sprintf('%.2f', $arr[1] / $arr[3]);
            $num11 += floatval($arr[11]);
            //订单成本
            $arr[12] = sprintf('%.2f', $arr[1] / $arr[7]);
            $num12 += floatval($arr[12]);
            //进店率
            $arr[13] = sprintf('%.2f', $arr[6] / $arr[3] * 100) . '%';
            array_push($returnData, $arr);
        }
        $tot = sprintf('%.2f', $num6 / $num3 * 100) . '%';
        $array = array('总计', $num1, $num2, $num3, $num4, $num5, $num6, $num7, $num8, $num9, $num10, $num11, $num12, $tot);
        array_push($returnData, $array);

        // 导出
        if ($data['need'] == 1) {
            // $title = $returnData[0];
            unset($returnData[0]);
            $file = '日渠道数据明细.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json(array('code' => 1, 'data' => $returnData, 'count' => count($returnData[0])));
        }
    }

    //安徽周/月报表
    public function week_and_month_statistics()
    {
        // 权限
        $auth = check_right('menu1522752970');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '你无权操作', 'count' => 0, 'data' => ''];
            return json($return);
        }

        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        return $this->fetch();
    }

    public function week_and_month_statistics_data()
    {
        set_time_limit(0);
        // $objPHPExcel = new PHPExcel();
        // $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');      //合并
        // $objPHPExcel->getActiveSheet()->unmergeCells('A1:F1');    // 拆分
        //  权限
        $auth = check_right('menu1522752970');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '你无权操作', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $timeArea = explode(' - ', $data['timeArea']);
        $start = date('Y-m-d', strtotime($timeArea[0]));
        $end = date('Y-m-d 23:59:59', strtotime($timeArea[1]));

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }

        $returnData = [];
        //品牌列表
        $brandclassList = controller('crm/Setting', 'lib')->brandclass_list();
        $title = [$data['timeArea'], '花费', '毛客资', '有效客资', '待定客资', '无效客资', '进店', '订单', '老客订单', '网转订单', '总订单', '走单', '订单业绩', '实收业绩', '均价', '进店率', '进店成交率'];

        array_push($returnData, $title);

        $num1 = $num2 = $num3 = $num4 = $num5 = $num6 = $num7 = $num8 = $num9 = $num10 = $num11 = $num12 = $num13 = $num14 = $num15 = $num16 = 0;
        foreach ($brandclassList as $k => $v) {
            $arr = [];
            $arr1 = [];
            $city_id = db_config('sx_city_id_' . $v['id']);
            if ($city_id) {
                $arr[0] = $v['brandclass'] . '--本地';
                //花费
                $arr[1] = db('c_customer_cost')
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('cost_time', 'between time', [$start, $end])
                    ->sum('cost_avg');
                //毛客资
                $arr[2] = db('c_customerinfo')
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
                //有效客资
                $arr[3] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 1)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //待定客资
                $arr[4] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 2)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //无效客资
                $arr[5] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 3)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //总进店
                $arr[6] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('syjd_day', 'between time', [$start, $end])
                    ->count();
                //进店订单
                $arr[7] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //老客订单
                $arr[8] = db('c_customerinfo')
                    ->where($where)
                    ->where('introducer_type', 3)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //网转订单
                $arr[9] = db('c_customerinfo')
                    ->where($where)
                    ->where('order_type', 2)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //总订单
                $arr[10] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //走单
                $arr[11] = $arr[6] - $arr[7];
                //订单业绩
                $arr[12] = db('c_customerinfo')
                    ->where($where)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->sum('totalpay_money');
                //实收业绩
                $arr[13] = db('c_customerinfo')
                    ->where($where)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->sum('fact_money');
                //均价
                $arr[14] = sprintf('%.2f', $arr[12] / $arr[10]);
                //进店率
                $arr[15] = sprintf('%.2f', $arr[6] / $arr[3] * 100) . '%';
                //进店成交率
                $arr[16] = sprintf('%.2f', $arr[7] / $arr[6] * 100) . '%';

                array_push($returnData, $arr);

                $arr1[0] = $v['brandclass'] . '--外地';
                //花费
                $arr1[1] = db('c_customer_cost')
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('cost_time', 'between time', [$start, $end])
                    ->sum('cost_avg');

                //毛客资
                $arr1[2] = db('c_customerinfo')
                    ->where('c_from', 1)
                    ->where('is_status', 1)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
                //有效客资
                $arr1[3] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 1)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //待定客资
                $arr1[4] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 2)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //无效客资
                $arr1[5] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 3)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //总进店
                $arr1[6] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('syjd_day', 'between time', [$start, $end])
                    ->count();
                //进店订单
                $arr1[7] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //老客订单
                $arr1[8] = db('c_customerinfo')
                    ->where($where)
                    ->where('customer_type', 2)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //网转订单
                $arr1[9] = db('c_customerinfo')
                    ->where($where)
                    ->where('order_type', 2)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //总订单
                $arr1[10] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //走单
                $arr1[11] = $arr1[6] - $arr1[7];
                //订单业绩
                $arr1[12] = db('c_customerinfo')
                    ->where($where)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->sum('totalpay_money');
                //实收业绩
                $arr1[13] = db('c_customerinfo')
                    ->where($where)
                    ->where('brandclass_id', $v['id'])
                    ->where('city_id', '<>', $city_id)
                    ->where('order_day', 'between time', [$start, $end])
                    ->sum('fact_money');
                //均价
                $arr1[14] = sprintf('%.2f', $arr1[12] / $arr1[10]);
                //进店率
                $arr1[15] = sprintf('%.2f', $arr1[6] / $arr1[3] * 100) . '%';
                //进店成交率
                $arr1[16] = sprintf('%.2f', $arr1[7] / $arr1[6] * 100) . '%';


                array_push($returnData, $arr1);
            } else {
                $arr[0] = $v['brandclass'];
                //花费
                $arr[1] = db('c_customer_cost')
                    ->where('brandclass_id', $v['id'])
                    ->where('cost_time', 'between time', [$start, $end])
                    ->sum('cost_avg');
                //毛客资
                $arr[2] = db('c_customerinfo')
                    ->where('c_from', 1)
                    ->where('is_status', 1)
                    ->where('brandclass_id', $v['id'])
                    ->where('dj_day', 'between time', [$start, $end])
                    ->count();
                //有效客资
                $arr[3] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 1)
                    ->where('brandclass_id', $v['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //待定客资
                $arr[4] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 2)
                    ->where('brandclass_id', $v['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //无效客资
                $arr[5] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_valid', 3)
                    ->where('brandclass_id', $v['id'])
                    ->where('yx_day', 'between time', [$start, $end])
                    ->count();
                //总进店
                $arr[6] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('brandclass_id', $v['id'])
                    ->where('syjd_day', 'between time', [$start, $end])
                    ->count();
                //进店订单
                $arr[7] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_intostore', 2)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //老客订单
                $arr[8] = db('c_customerinfo')
                    ->where($where)
                    ->where('introducer_type', 3)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //网转订单
                $arr[9] = db('c_customerinfo')
                    ->where($where)
                    ->where('order_type', 2)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //总订单
                $arr[10] = db('c_customerinfo')
                    ->where($where)
                    ->where('is_success', 'in', [1, 3])
                    ->where('brandclass_id', $v['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->count();
                //走单
                $arr[11] = $arr[6] - $arr[7];
                //订单业绩
                $arr[12] = db('c_customerinfo')
                    ->where($where)
                    ->where('brandclass_id', $v['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->sum('totalpay_money');
                //实收业绩
                $arr[13] = db('c_customerinfo')
                    ->where($where)
                    ->where('brandclass_id', $v['id'])
                    ->where('order_day', 'between time', [$start, $end])
                    ->sum('fact_money');
                //均价
                $arr[14] = sprintf('%.2f', $arr[12] / $arr[10]);
                //进店率
                $arr[15] = sprintf('%.2f', $arr[6] / $arr[3] * 100) . '%';
                //进店成交率
                $arr[16] = sprintf('%.2f', $arr[7] / $arr[6] * 100) . '%';
                array_push($returnData, $arr);
            }
            $num1 += $arr[1] + $arr1[1];
            $num2 += $arr[2] + $arr1[2];
            $num3 += $arr[3] + $arr1[3];
            $num4 += $arr[4] + $arr1[4];
            $num5 += $arr[5] + $arr1[5];
            $num6 += $arr[6] + $arr1[6];
            $num7 += $arr[7] + $arr1[7];
            $num8 += $arr[8] + $arr1[8];
            $num9 += $arr[9] + $arr1[9];
            $num10 += $arr[10] + $arr1[10];
            $num11 += $arr[11] + $arr1[11];
            $num12 += $arr[12] + $arr1[12];
            $num13 += $arr[13] + $arr1[13];
        }
        $total = [];
        $total[0] = '总计';
        $total[1] = $num1;
        $total[2] = $num2;
        $total[3] = $num3;
        $total[4] = $num4;
        $total[5] = $num5;
        $total[6] = $num6;
        $total[7] = $num7;
        $total[8] = $num8;
        $total[9] = $num9;
        $total[10] = $num10;
        $total[11] = $num11;
        $total[12] = $num12;
        $total[13] = $num13;
        $total[14] = sprintf('%.2f', $num12 / $num10);
        $total[15] = sprintf('%.2f', $num6 / $num3 * 100) . '%';
        $total[16] = sprintf('%.2f', $num7 / $num6 * 100) . '%';

        array_push($returnData, $total);

        array_push($returnData, ['不区分本地外地统计', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']);

        $num1 = $num2 = $num3 = $num4 = $num5 = $num6 = $num7 = $num8 = $num9 = $num10 = $num11 = $num12 = $num13 = $num14 = $num15 = $num16 = 0;
        foreach ($brandclassList as $k => $v) {
            $arr = [];
            $arr[0] = $v['brandclass'];
            //花费
            $arr[1] = db('c_customer_cost')
                ->where('brandclass_id', $v['id'])
                ->where('cost_time', 'between time', [$start, $end])
                ->sum('cost_avg');
            //毛客资
            $arr[2] = db('c_customerinfo')
                ->where('c_from', 1)
                ->where('is_status', 1)
                ->where('brandclass_id', $v['id'])
                ->where('dj_day', 'between time', [$start, $end])
                ->count();
            //有效客资
            $arr[3] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 1)
                ->where('brandclass_id', $v['id'])
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            //待定客资
            $arr[4] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 2)
                ->where('brandclass_id', $v['id'])
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            //无效客资
            $arr[5] = db('c_customerinfo')
                ->where($where)
                ->where('is_valid', 3)
                ->where('brandclass_id', $v['id'])
                ->where('yx_day', 'between time', [$start, $end])
                ->count();
            //总进店
            $arr[6] = db('c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
                ->where('brandclass_id', $v['id'])
                ->where('syjd_day', 'between time', [$start, $end])
                ->count();
            //进店订单
            $arr[7] = db('c_customerinfo')
                ->where($where)
                ->where('is_intostore', 2)
                ->where('is_success', 'in', [1, 3])
                ->where('brandclass_id', $v['id'])
                ->where('order_day', 'between time', [$start, $end])
                ->count();
            //老客订单
            $arr[8] = db('c_customerinfo')
                ->where($where)
                ->where('order_day', 3)
                ->where('is_success', 'in', [1, 3])
                ->where('brandclass_id', $v['id'])
                ->where('order_day', 'between time', [$start, $end])
                ->count();
            //网转订单
            $arr[9] = db('c_customerinfo')
                ->where($where)
                ->where('order_type', 2)
                ->where('is_success', 'in', [1, 3])
                ->where('brandclass_id', $v['id'])
                ->where('order_day', 'between time', [$start, $end])
                ->count();
            //总订单
            $arr[10] = db('c_customerinfo')
                ->where($where)
                ->where('is_success', 'in', [1, 3])
                ->where('brandclass_id', $v['id'])
                ->where('order_day', 'between time', [$start, $end])
                ->count();
            //走单
            $arr[11] = $arr[6] - $arr[7];
            //订单业绩
            $arr[12] = db('c_customerinfo')
                ->where($where)
                ->where('brandclass_id', $v['id'])
                ->where('order_day', 'between time', [$start, $end])
                ->sum('totalpay_money');
            //实收业绩
            $arr[13] = db('c_customerinfo')
                ->where($where)
                ->where('brandclass_id', $v['id'])
                ->where('order_day', 'between time', [$start, $end])
                ->sum('fact_money');
            //均价
            $arr[14] = sprintf('%.2f', $arr[12] / $arr[10]);
            //进店率
            $arr[15] = sprintf('%.2f', $arr[6] / $arr[3] * 100) . '%';
            //进店成交率
            $arr[16] = sprintf('%.2f', $arr[7] / $arr[6] * 100) . '%';

            array_push($returnData, $arr);
            $num1 += $arr[1];
            $num2 += $arr[2];
            $num3 += $arr[3];
            $num4 += $arr[4];
            $num5 += $arr[5];
            $num6 += $arr[6];
            $num7 += $arr[7];
            $num8 += $arr[8];
            $num9 += $arr[9];
            $num10 += $arr[10];
            $num11 += $arr[11];
            $num12 += $arr[12];
            $num13 += $arr[13];
        }
        $total = [];
        $total[0] = '总计';
        $total[1] = $num1;
        $total[2] = $num2;
        $total[3] = $num3;
        $total[4] = $num4;
        $total[5] = $num5;
        $total[6] = $num6;
        $total[7] = $num7;
        $total[8] = $num8;
        $total[9] = $num9;
        $total[10] = $num10;
        $total[11] = $num11;
        $total[12] = $num12;
        $total[13] = $num13;
        $total[14] = sprintf('%.2f', $num12 / $num10);
        $total[15] = sprintf('%.2f', $num6 / $num3 * 100) . '%';
        $total[16] = sprintf('%.2f', $num7 / $num6 * 100) . '%';

        array_push($returnData, $total);

        $return['code'] = 200;
        $return['msg'] = '';
        $return['count'] = count($title);
        $return['data'] = $returnData;

        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '各事业部数据报表.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 100, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }

    //24小时PK表
    public function ds_pk()
    {
        // 权限
        $auth = check_right('menu1522752932');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '你无权操作', 'count' => 0, 'data' => ''];
            return json($return);
        }
        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);

        $today = $end_time = date('Y-m-d');
        $start_time = getWeekStartTimeNotFrontMonth();
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        // print_r($lists);die;
        $this->assign('today', $today);
        $this->assign('next_day', $start_time . '-' . $today);
        return $this->fetch();
    }

    public function ds_pk_data()
    {
        set_time_limit(0);
        $data = input();
        //判断是电商还是网销
        $shop_code = $data['shop_code'];
        $shop = controller('crm/Customer', 'lib')->get_shop(array('shop_code' => $shop_code));

        $add_shop_code = $shop[0]['belong_shop_code'];


        if ($shop_code != $add_shop_code) {
            $flag = 'ds';//毛客资（电商）
            $where['add_shop_code'] = $shop_code;
            $title = ['组名', '员工', '毛客资'];
        } else {
            $flag = 'wx';//有效客资，进店量（网销），订单量（门店）
            $where['shop_code'] = $shop_code;
            $title = ['组名', '员工', '有效客资', '进店量', '订单量'];
        }

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 1;
        if ($data['consultation_type_id']) {
            $whereT['consultation_type_id'] = $data['consultation_type_id'];
        }
        // 时间区域
        if (!$data['timeArea']) {
            $return = ['code' => 100, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $time = $data['time'];
        $timeArea = explode(' - ', $data['timeArea']);
        if ($time) {
            $start = $time . ' ' . $timeArea[0];
            $end = $time . ' ' . $timeArea[1];
        } else {
            $start = date('Y-m-d') . $timeArea[0];
            $end = date('Y-m-d') . $timeArea[1];
        }


        $returnData = [];
        array_push($returnData, $title);

        //店下的所有小组
        $groups = db('c_staff_group')->where('shop_code', $shop_code)->select();
        $group_ids = array_column($groups, 'id');//小组id
        $inGroupStaff = db('c_staff_group_relation')->where('group_id', 'in', $group_ids)->field('staff_id')->select();
        $inGroupStaffIds = array_column($inGroupStaff, 'staff_id');//所有在小组的人员
        $url = '5a01766b4a3dd';
        $res = sx_call($url, array('shop_code' => $shop_code));
        if ($res['code'] == 200) {//店下的所有人员
            $allStaff = $res['data'];
        } else {
            return array('code' => 206, 'msg' => '查询店内所有人员接口调用失败', 'data' => '');
        }
        foreach ($allStaff as $key => $val) {//去重小组内的人员
            if (in_array($val['id'], $inGroupStaffIds)) {
                unset($allStaff[$key]);
            }
        }
        foreach ($allStaff as $kk => $vv) {//无小组人员
            $arr = [];
            $arr[0] = '';
            $arr[1] = $vv['staffname'];
            if ($flag == 'ds') {
                $arr[2] = db('c_customerinfo')
                    ->where($where)
                    ->where('dj_staff_id', $vv['id'])
                    ->where('dj_day', 'between', [$start, $end])
                    ->count();
            } else {
                $arr[2] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('sales_staff_id', $vv['id'])
                    ->where('is_valid', 1)
                    ->where('yx_day', 'between', [$start, $end])
                    ->count();
                $arr[3] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('sales_staff_id', $vv['id'])
                    ->where('syjd_day', 'between', [$start, $end])
                    ->count();
                $arr[4] = db('c_customerinfo')
                    ->where($where)
                    ->where($whereT)
                    ->where('sales_staff_id', $vv['id'])
                    ->where('order_day', 'between', [$start, $end])
                    ->count();
            }
            array_push($returnData, $arr);
        }
        foreach ($groups as $k => $v) {
            //小组下的所有人员
            $staffIds = db('c_staff_group_relation')->where('group_id', $v['id'])->field('staff_id')->select();

            $ids = array_column($staffIds, 'staff_id');
            //通过id查询所有人员名
            $url = '5a18e3fa516a1';
            $res = sx_call($url, array('staff_id' => $ids));
            if ($res['code'] == 200) {
                $staff = $res['data'];
                foreach ($staff as $ke => $va) {
                    $arr = [];
                    $arr[0] = $v['group_name'];
                    $arr[1] = $va['staffname'];
                    if ($flag == 'ds') {
                        $arr[2] = db('c_customerinfo')
                            ->where($where)
                            ->where('dj_staff_id', $va['id'])
                            ->where('dj_day', 'between', [$start, $end])
                            ->count();
//                            echo db()->getLastSql();
                    } else {
                        $arr[2] = db('c_customerinfo')
                            ->where($where)
                            ->where($whereT)
                            ->where('sales_staff_id', $va['id'])
                            ->where('is_valid', 1)
                            ->where('yx_day', 'between', [$start, $end])
                            ->count();
                        $arr[3] = db('c_customerinfo')
                            ->where($where)
                            ->where($whereT)
                            ->where('sales_staff_id', $va['id'])
                            ->where('syjd_day', 'between', [$start, $end])
                            ->count();
                        $arr[4] = db('c_customerinfo')
                            ->where($where)
                            ->where($whereT)
                            ->where('sales_staff_id', $va['id'])
                            ->where('order_day', 'between', [$start, $end])
                            ->count();
                    }
                    array_push($returnData, $arr);
                }
            } else {
                return ['code' => 100, 'msg' => '小组下的人员获取失败', 'data' => ''];
            }
        }
        $return['code'] = 200;
        $return['msg'] = '';
        $return['count'] = count($title);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = $returnData[0];
            unset($returnData[0]);
            $file = '24小时PK表.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            if ($return['data']) {
                return json($return);
            } else {
                $return = ['code' => 100, 'msg' => '暂无数据', 'count' => 0, 'data' => '',];
                return json($return);
            }
        }
    }
    //西昌报表
    //电商渠道日报表
    public function ds_channel_day_xc(){
        // 权限
        $auth = check_right('menu1525935313');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }

        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // var_dump($lists);
        // var_dump($lists['brandclassList']);
        // var_dump($lists['shopList']);
        // exit;
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);
        // today
        $today = date('Y-m-d') . ' - ' . date('Y-m-d');
        $this->assign('today', $today);

        $timeArea = getdateArea('this_month');
        $this->assign('start', $timeArea[0]);
        $this->assign('end', $timeArea[1]);

        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);
        $detail = db('s_tracksign')->where('shop_code',session('belong_shop_code'))->select();
        $this->assign('sign',$detail);
        $this->assign('title', '渠道日报表');
        return $this->fetch();
    }
    public function ds_channel_day_xc_data(){
        set_time_limit(0);
        $data = input();
        if(empty($data['start'])){
            $data['start'] = date('Y-m-d 00:00:00',strtotime('-1 day'));
        }else{
            $data['start'] = date('Y-m-d 00:00:00', strtotime($data['start']));
        }
        if(empty($data['end'])){
            $data['end'] = date('Y-m-d 23:59:59',strtotime('-1 day'));
        }else{
            $data['end'] = date('Y-m-d 23:59:59', strtotime($data['end']));
        }


        $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $where['is_status'] = 1;
        $where['customer_type'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        // 消费类型
        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = (int)$data['consultation_type_id'];
        }
        //客资标记
        if ($data['sign_id']) {
            $where['sign_id'] = (int)$data['sign_id'];
        }
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = (int)$data['brandclass_id'];
        }
        //渠道
        $channels = db('s_channel')->where('shop_code',$shop_code)->field('id,channel_name')->select();
        //花费
        $cost = db('c_customer_cost')
            ->where('shop_code', $shop_code)
            ->where('cost_time', 'between time', [$data['start'], $data['end']])
            ->group('channel_id')
            ->column('sum(cost_avg) as num','channel_id');
        //毛客资
        $all = db('c_customerinfo')
            ->where($where)
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->group('customer_channel_id')
            ->column('count(id) as num','customer_channel_id');
        //有效客资
        $valid = db('c_customerinfo')
            ->where($where)
            ->where('is_valid',1)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->group('customer_channel_id')
            ->column('count(id) as num','customer_channel_id');
        //待定客资
        $dd = db('c_customerinfo')
            ->where($where)
            ->where('is_valid',2)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->group('customer_channel_id')
            ->column('count(id) as num','customer_channel_id');
        $where['consultation_type_id'] = HS_TYPE;
        //成交数
        $order = db('c_customerinfo')
            ->where($where)
            ->where('is_success',1)
            ->where('order_day', 'between time', [$data['start'], $data['end']])
            ->group('customer_channel_id')
            ->column('count(id) as num','customer_channel_id');

        //婚纱有效
        $HHvalid  = db('c_customerinfo')
            ->where($where)
            ->where('is_valid',1)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->group('customer_channel_id')
            ->column('count(id) as num','customer_channel_id');
        $returnDate = [];
        $total = [];
        foreach($channels as $k=>$v){
            $arr = [];
            $arr['channel_name'] = $v['channel_name'];
            $arr['cost']           = $cost[$v['id']] ? sprintf('%.2f',$cost[$v['id']]) : 0;//花费
            $arr['all']           = $all[$v['id']] ? $all[$v['id']] : 0;//毛客资
            $arr['hhvalid']           = $HHvalid[$v['id']] ? $HHvalid[$v['id']] : 0;//婚纱有效客资
            $arr['valid']           = $valid[$v['id']] ? $valid[$v['id']] : 0;//有效客资
            $arr['validRate']    = $arr['all']>0 ? sprintf('%.2f',$arr['hhvalid']/$arr['all']*100).'%':'0%';//有效率
            $arr['obtain']       = $arr['hhvalid']>0 ? sprintf('%.2f',$arr['cost']/$arr['hhvalid']): '0';//客资成本
            $arr['order']        = $order[$v['id']] ? $order[$v['id']] : 0;//成交数
            $arr['dd']        = $dd[$v['id']] ? $dd[$v['id']] : 0;//待定客资
            $total['channel_name'] = '汇总';
            $total['cost'] += floatval($arr['cost']);
            $total['all'] += $arr['all'];
            $total['hhvalid'] += $arr['hhvalid'];
            $total['valid'] += $arr['valid'];
            $total['validRate'] = '';
            $total['obtain'] = '';
            $total['order'] += $arr['order'];
            $total['dd'] += $arr['dd'];

            array_push($returnDate,$arr);
        }
        $total['validRate'] = sprintf('%.2f',$total['hhvalid']/$total['all']*100).'%';//有效率
        $total['obtain'] = sprintf('%.2f',$total['cost']/$total['hhvalid']);//客资成本
        array_push($returnDate,$total);

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnDate);
        $return['data'] = $returnDate;
        // 导出
        if ($data['need'] == 1) {
            $title = array( '渠道名称', '花费', '毛客资', '婚纱有效', '总有效客资', '有效率(婚纱)', '有效客资成本(婚纱)', '成交数(婚纱)', '待定客资');
            $file = '渠道日报表.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnDate, $file);
        } else {
            return json($return);
        }
    }
    //电商渠道月报表
    public function ds_channel_month_xc(){
        // 权限
        $auth = check_right('menu1525935348');
        if (!$auth) {
            controller('crm/Index', 'controller')->index();
            exit;
        }

        // 根据员工id获取  事业部，店，部门 list
        $lists = controller('crm/Statistics', 'lib')->getLists(session('staff_id'));
        // 事业部                 列表
        $this->assign('brandclassList', $lists['brandclassList']);
        $this->assign('bsize', count($lists['brandclassList']));
        // 店（电商，网销，渠道） 列表
        $this->assign('shopList', $lists['shopList']);
        $this->assign('ssize', count($lists['shopList']));
        // 部门                   列表
        $this->assign('departmentList', $lists['departmentList']);

        // crm省    列表
        $data['type'] = 1;
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType();
        $this->assign("consumptionType", $consumptionType);

        $this->assign('title', '渠道月报表');
        return $this->fetch();
    }
    public function ds_channel_month_xc_data(){
        set_time_limit(0);
        $data = input();
        if($data['timeArea']){
            $data['start'] = date('Y-m-01', strtotime($data['timeArea']));
            $data['end'] = date('Y-m-d 23:59:59', strtotime($data['start'] . ' +1 month -1 day'));
        }else{
            $data['start'] = date('Y-m-01');
            $data['end'] = date('Y-m-d 23:59:59', strtotime("$data[start] +1 month -1 day"));
        }
        $time = getDates($data['start'],$data['end']);
        $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $where['is_status'] = 1;
        $where['customer_type'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        // 消费类型
//        if ($data['consultation_type_id']) {
//            $where['consultation_type_id'] = (int)$data['consultation_type_id'];
//        }
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = (int)$data['brandclass_id'];
        }

        //花费
        $cost = db('c_customer_cost')
            ->where('shop_code', $shop_code)
            ->where('cost_time', 'between time', [$data['start'], $data['end']])
            ->group('cost_time')
            ->column('sum(cost_avg) as num','cost_time');
        //毛客资
        $all = db('c_customerinfo')
            ->where($where)
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(dj_day,"%Y-%m-%d") days,count(id) as num');
        //有效客资
        $hsvalid = db('c_customerinfo')
            ->where($where)
            ->where('is_valid',1)
            ->where('consultation_type_id',HS_TYPE)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(yx_day,"%Y-%m-%d") days,count(id) as num');
        //有效客资  艺术
        $ysvalid = db('c_customerinfo')
            ->where($where)
            ->where('is_valid',1)
            ->where('consultation_type_id',YS_TYPE)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(yx_day,"%Y-%m-%d") days,count(id) as num');
        //总有效客资
        $valid = db('c_customerinfo')
            ->where($where)
            ->where('is_valid',1)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(yx_day,"%Y-%m-%d") days,count(id) as num');
        //待定客资
        $dd = db('c_customerinfo')
            ->where($where)
            ->where('is_valid',2)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(yx_day,"%Y-%m-%d") days,count(id) as num');
        //成交数 所有
        $order = db('c_customerinfo')
            ->where($where)
            ->where('is_success',1)
            ->where('order_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(order_day,"%Y-%m-%d") days,count(id) as num');
        //婚纱订单
        $hsorder = db('c_customerinfo')
            ->where($where)
            ->where('is_success',1)
            ->where('consultation_type_id',HS_TYPE)
            ->where('order_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(order_day,"%Y-%m-%d") days,count(id) as num');
        //婚纱进店
        $hsInto  = db('c_customerinfo')
            ->where($where)
            ->where('is_intostore',2)
            ->where('consultation_type_id',HS_TYPE)
            ->where('syjd_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(syjd_day,"%Y-%m-%d") days,count(id) as num');
        //艺术成交
        $ysorder = db('c_customerinfo')
            ->where($where)
            ->where('is_success',1)
            ->where('consultation_type_id',YS_TYPE)
            ->where('order_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(order_day,"%Y-%m-%d") days,count(id) as num');
        //艺术进店
        $ysInto  = db('c_customerinfo')
            ->where($where)
            ->where('is_intostore',2)
            ->where('consultation_type_id',YS_TYPE)
            ->where('syjd_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(syjd_day,"%Y-%m-%d") days,count(id) as num');
        $onLineOrder  = db('c_customerinfo')
            ->where($where)
            ->where('order_type',1)
            ->where('is_success',1)
            ->where('syjd_day', 'between time', [$data['start'], $data['end']])
            ->group('days')
            ->column('DATE_FORMAT(syjd_day,"%Y-%m-%d") days,count(id) as num');
        $returnDate = [];
        $total = [];
        foreach($time as $k=>$v){
            if($v > date('Y-m-d')){
                continue;
            }
            $arr = [];
            $arr['time'] = $v;
            $arr['cost']           = $cost[$v] ? sprintf('%.2f',$cost[$v]) : 0;//花费
            $arr['all']           = $all[$v] ? $all[$v] : 0;//毛客资
            $arr['hsvalid']           = $hsvalid[$v] ? $hsvalid[$v] : 0;//婚纱有效客资
            $arr['ysvalid']           = $ysvalid[$v] ? $ysvalid[$v] : 0;//艺术有效客资
            $arr['valid']           = $valid[$v] ? $valid[$v] : 0;//有效客资
            $arr['dd']           = $dd[$v] ? $dd[$v] : 0;//待定客资
            $arr['hsValidRate']    = $arr['all']>0 ? sprintf('%.2f',$arr['hsvalid']/$arr['all']*100).'%':'0%';//有效率--婚纱
            $arr['obtain']       = $arr['hsvalid']>0 ? sprintf('%.2f',$arr['cost']/$arr['hsvalid']): '0';//客资成本--婚纱
            $arr['order']        = $order[$v] ? $order[$v] : 0;//成交数
            $arr['orderRate']        = $arr['valid']>0 ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%': '0';//成交率(订单/有效)
            $arr['orderObtain'] = $arr['order']>0 ? sprintf('%.2f',$arr['cost']/$arr['order']): '0';//成交成本

            $arr['hsInto']        = $hsInto[$v] ? $hsInto[$v] : 0;//婚纱进店
            $arr['hsorder']        = $hsorder[$v] ? $hsorder[$v] : 0;//婚纱成交
            $arr['onLineOrder']        = $onLineOrder[$v] ? $onLineOrder[$v] : 0;//线上成交

            $arr['ysInto']        = $ysInto[$v] ? $ysInto[$v] : 0;//艺术进店
            $arr['ysOrder']        = $ysorder[$v] ? $ysorder[$v] : 0;//艺术成交

            $arr['hsObtail']        = $arr['hsorder']>0 ? sprintf('%.2f',$arr['cost']/$arr['hsorder']): '0';//婚纱客资成本
            $total['time'] = '汇总';
            $total['cost'] += floatval($arr['cost']);
            $total['all'] += $arr['all'];
            $total['hsvalid'] += $arr['hsvalid'];
            $total['ysvalid'] += $arr['ysvalid'];
            $total['valid'] += $arr['valid'];
            $total['dd'] += $arr['dd'];
            $total['validRate'] = '';//客资有效率
            $total['obtain'] = '';//客资成本
            $total['order'] += $arr['order'];
            $total['orderRate'] = '';//婚纱成交率
            $total['orderObtain'] = '';//婚纱订单成本
            $total['hsInto'] += $arr['hsInto'];
            $total['hsorder'] += $arr['hsorder'];
            $total['onLineOrder'] += $arr['onLineOrder'];
            $total['ysInto'] += $arr['ysInto'];
            $total['ysOrder'] += $arr['ysOrder'];
            $total['hsObtain'] =  '';//婚纱客资成本
            array_push($returnDate,$arr);
        }
        $total['validRate'] = sprintf('%.2f',$total['valid']/$total['all']*100).'%';//有效率
        $total['obtain'] = sprintf('%.2f',$total['cost']/$total['valid']);//客资成本
        $total['orderRate'] = sprintf('%.2f',$total['hsorder']/$total['hsvalid']*100).'%';//成交率
        $total['orderObtain'] = sprintf('%.2f',$total['cost']/$total['hsorder']);//婚纱订单成本
        $total['hsObtain'] = sprintf('%.2f',$total['cost']/$total['hsvalid']);//婚纱订单成本
        array_push($returnDate,$total);

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnDate);
        $return['data'] = $returnDate;
        // 导出
        if ($data['need'] == 1) {
            $title = array( '日期', '花费', '接收客资', '婚纱有效', '艺术有效','总有效客资', '待定客资', '有效率(婚纱)', '有效客资成本(婚纱)','当日成交','成交率','成交成本','婚纱进店','进店成交(婚纱)','线上成交','艺术进店','艺术成交','婚纱客资成本');
            $file = '渠道日报表.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnDate, $file);
        } else {
            return json($return);

        }
    }
}
