<?php
/**
 * 报表实现类 莱色电商渠道漏斗
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wangzhenya 2018-06-15 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;

class Ls_ds_channel_ld extends Report {

    private $level=1;
    private $type=1;
    private $code='code1535693823';

    public function getLevel(){
        return $this->level;

    }
    public function getType(){
        return $this->type;
    }
    public function getCode(){
        return $this->code;
    }
    public function data()
    {
        set_time_limit(0);
        $data = input();

        $start = date('Y-m-d 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $det = db('s_report_form')->alias('f')->join('s_report_detail d','d.form_id=f.id','left')->where('d.id',$data['did'])->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();
        $belong_shop_code = $data['shop_code'];
        $shop_code = $det['shop_code'];
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        $whereN['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'];
            $whereC['province_id'] = (int)$data['province'];
            $whereN['province_id'] = (int)$data['province'];
        }
        if ($data['city']) {
            $where['city_id'] = (int)$data['city'];
            $whereC['city_id'] = (int)$data['city'];
            $whereN['city_id'] = (int)$data['city'];
        }
        if($data['shop_code']){
            // $where['c.shop_code'] = $data['shop_code'];
            // $whereN['c.shop_code'] = $data['shop_code'];
            $sql = "c.shop_code in :shop_code";
            $arr['shop_code']    = $belong_shop_code;
            $sqlN = "c.shop_code in :shop_code";
            $arrN['shop_code']    = $belong_shop_code;
        }
        $group = 's.id';
        $channels = '';
        if ($data['channel'] == true) {
            if ($data['channel_name']) {
                $channel_name = explode(',',$data['channel_name']);
                $findSql = ' FIND_IN_SET("'.$shop_code.'",share_shops) ';
                $channels = db('s_channel')->where('channel_name', 'in',$channel_name)->where($findSql)->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;
        // 花费
        $sqlC = '';
        $sqlI = '';
        $sqlN = '';
        if($belong_shop_code){
            $belong_shop_code = "('".str_replace(',',"','",$belong_shop_code)."')";
            $sqlC .= 'belong_shop_code in '.$belong_shop_code;
            $sqlI .= 'c.shop_code in '.$belong_shop_code;
            $sqlN .= 'shop_code in '.$belong_shop_code;
        }

        if($data['channel']){
            $channelCost = db('s_channel_cost')
                ->where($whereC)
                ->where($sqlC)
                // ->where('belong_shop_code','in',$belong_shop_code)
                ->where('cost_date', 'between time', [$start, $end])
                ->group('channel_id')
                ->column('sum(cost) as cost,id,channel_class_name,channel_info_name,channel_info_id','channel_id');
        }else{
            $channelCost = db('s_channel_cost')
                ->where($whereC)
                ->where($sqlC)
                // ->where('belong_shop_code','in',$belong_shop_code)
                ->where('cost_date', 'between time', [$start, $end])
                ->group('channel_info_id')
                ->column('sum(cost) as cost,id,channel_class_name,channel_info_name,channel_info_id','channel_info_id');
        }
        $consultation_type_id = $data['consultation_type_id'] ? intval($data['consultation_type_id']) : '';
        $sql = 's.channel_name,s.channel_class_name,s.channel_info_name,s.id,';
        $sql .= "sum(c.dj_day between '$start' and '$end') as mkz,";//毛客资
        if($consultation_type_id){
            $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_valid=1 and c.dj_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_intostore in ('2','3','5') c.and syjd_day between '$start' and '$end') as jd,";//进店
            // $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
            // $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
            // $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_intostore=2 and c.is_success=1 and c.order_day between '$start' and '$end') as `order`,";//进店成交量
            $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
            $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.order_type=2 and c.is_success=1 and c.order_day between '$start' and '$end') as `order`,";//进店成交量
            $sql .= "sum(c.consultation_type_id = ".$consultation_type_id." and (is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
        }else{
            $sql .= "sum(c.is_valid=1 and c.dj_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(c.is_intostore in ('2','3','5') and c.syjd_day between '$start' and '$end') as jd,";//进店
            // $sql .= "sum(c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
            // $sql .= "sum(c.is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
            // $sql .= "sum(c.is_success=1 and c.is_intostore=2 and c.order_day between '$start' and '$end') as `order`,";//进店成交量
            $sql .= "sum(c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
            $sql .= "sum(c.order_type=2 and c.is_success=1 and c.order_day between '$start' and '$end') as `order`,";//进店成交量
            $sql .= "sum(is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
        }
        $sql .= "sum(c.is_valid=2 and c.dj_day between '$start' and '$end') as dd,";//待定
        $sql .= "sum((c.customer_tel is not null and c.customer_tel<>'') and c.dj_day between '$start' and '$end') as tel,";//手机
        $sql .= "sum((is_intostore=2 or is_intostore=3 or is_intostore=5) and c.is_success=2 and c.syjd_day between '$start' and '$end') as zd";//走单
        $info = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where($sqlI)
            ->group($cKey)
            ->column($sql,$cKey);
        $sql1 = db()->getLastSql();
        /* // 录入客资量
         $allCustomer = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
             ->where($where)
             ->where($sql)
            // ->where('c.shop_code','in',$belong_shop_code)
             ->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 =db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
             ->where($where)
             ->where($whereT)
             ->where($sql)
             ->where('c.is_valid', 1)
             ->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);

         // 待定客资量
         $ddCustomer =db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
             ->where($where)
             ->where($sql)
             ->where('c.is_valid', 2)
             ->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($sql)
             ->where($whereT)
             ->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 = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
             ->where($where)
             ->where($sql)
             ->where($whereT)
             ->where('c.is_intostore', 'in', '2,3')
             ->where('c.syjd_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);
         //网络订单
         $orderOnline = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
             ->where($where)
             ->where($sql)
             ->where($whereT)
             ->where('c.order_type', 1)
             ->where('c.is_success', 1)
             ->where('c.order_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);
         //进店订单
         $orderJD = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
             ->where($where)
             ->where($sql)
             ->where($whereT)
             ->where('c.is_intostore', 'in', '2,3')
             ->where('c.order_type', 2)
             ->where('c.is_success', 1)
             ->where('c.order_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);
         // 有效订单 数
         $orderNum = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
             ->where($where)
             ->where($sql)
             ->where($whereT)
             ->where('c.is_success', 1)
             ->where('c.order_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);*/
        // 营收（实际收入  不区分有效无效）
        $factMoney = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($where)
            ->where($sqlI)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group($group)
            ->column('sum(d.order_fact) as fact_money,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);
        // 套系均值（有效单套系应收款均值）
        $order_amount_avg = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($where)
            ->where($sqlI)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group($group)
            ->column('sum(o.order_amount) as totalpay_money,s.channel_name,s.channel_class_name,s.channel_info_name', $cKey);
        $returnData = [];
        $amount = 0;
        $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'] = $info[$v['id']]['mkz'] ? $info[$v['id']]['mkz'] : 0;
            $returnData[$k]['invCustomer'] = $info[$v['id']]['valid'] ? $info[$v['id']]['valid'] : 0;
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$k]['invRate'] = (sprintf('%.2f', $returnData[$k]['invCustomer'] / $returnData[$k]['lrCustomer'] * 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]['dd'] = $info[$v['id']]['dd'] ? $info[$v['id']]['dd'] : 0;
            $returnData[$k]['allTel'] = $info[$v['id']]['tel'] ? $info[$v['id']]['tel'] : 0;
            $returnData[$k]['orderJD'] = $info[$v['id']]['order'] ? $info[$v['id']]['order'] : 0;
            $returnData[$k]['orderOnline'] = $info[$v['id']]['order1'] ? $info[$v['id']]['order1'] : 0;
            $returnData[$k]['orderNum'] = $info[$v['id']]['order2'] ? $info[$v['id']]['order2'] : 0;
            // 新单成本
            $returnData[$k]['orderCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['orderNum']);
            // 转化率（ 有效新单 / 毛客资 ）
            $returnData[$k]['mkzRate'] = (sprintf('%.2f', ($returnData[$k]['orderJD']+$returnData[$k]['orderOnline']) /$returnData[$k]['lrCustomer'] * 100)) . '%';
            $returnData[$k]['totalAmount'] = $order_amount_avg[$v['id']]['totalpay_money'] ? sprintf('%.2f',$order_amount_avg[$v['id']]['totalpay_money']) : 0;
            $returnData[$k]['factMoney'] = $factMoney[$v['id']]['fact_money'] ? sprintf('%.2f',$factMoney[$v['id']]['fact_money']) : 0;
            $returnData[$k]['intoNum'] = $info[$v['id']]['jd'] ? $info[$v['id']]['jd'] : 0;
            $returnData[$k]['zd'] = $info[$v['id']]['zd'] ? $info[$v['id']]['zd'] : 0;
            $returnData[$k]['orderAmountAvg'] = $order_amount_avg[$v['id']]['totalpay_money'] ?
                sprintf('%.2f',$order_amount_avg[$v['id']]['totalpay_money']/$returnData[$k]['orderNum']) : 0;
            // 进店率（ 实际进店 / 有效获取 ）
            $returnData[$k]['intoRate'] = (sprintf('%.2f', $returnData[$k]['intoNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$k]['orderRate'] = (sprintf('%.2f', $returnData[$k]['orderJD'] / $returnData[$k]['intoNum'] * 100)) . '%';
            //全款率 实收/营收
            $returnData[$k]['qkRate'] = (sprintf('%.2f', $returnData[$k]['factMoney'] / $returnData[$k]['totalAmount'] * 100)) . '%';
            //进店成本
            $returnData[$k]['jdCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['intoNum']);
            //广告费占比 花费/一销套系
            $returnData[$k]['notice'] = (sprintf('%.2f', $returnData[$k]['channelCost'] / $returnData[$k]['totalAmount'] * 100)) . '%';
            // 转化率（ 有效新单 / 有效获取 ）
            $returnData[$k]['changeRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['invCustomer'] * 100)) . '%';
            // 营收ROI（营收：花费）
            $returnData[$k]['amountROI'] = sprintf('%.2f',intval($returnData[$k]['totalAmount'])/intval
                ($returnData[$k]['channelCost']));

            // 实收ROI（实收：花费）
            $returnData[$k]['factROI'] = sprintf('%.2f',intval($returnData[$k]['factMoney'])/intval
                ($returnData[$k]['channelCost']));

            $arr['channelCost'] += $channelCost[$v['id']]['cost'];   // 花费总计
            $arr['lrCustomer']  += $info[$v['id']]['mkz'];    // 录入总计
            $arr['invCustomer'] += $info[$v['id']]['valid'];   // 有效总计
            $arr['invRate'] = '';
            $arr['customerCost'] = '';
            $arr['invCost'] = '';
            $arr['dd'] += $returnData[$k]['dd'];   // 婚纱有效总计
            $arr['allTel']      += $info[$v['id']]['tel'];        // 总手机总计
            $arr['orderJD']    += $info[$v['id']]['order'];      // 订单总计
            $arr['orderOnline']    += $info[$v['id']]['order1'];      // 订单总计
            $arr['orderNum']    += $info[$v['id']]['order2'];      // 订单总计
            $arr['orderCost'] = '';
            $arr['mkzRate'] = '';
            $arr['totalAmount']   += $order_amount_avg[$v['id']]['totalpay_money']; // 一销套系
            $arr['factMoney']   += $factMoney[$v['id']]['fact_money']; // 营收总计
            $arr['intoNum']     += $info[$v['id']]['jd'];       // 进店总计
            $arr['zd']     += $returnData[$k]['zd'];       // 进店总计
            $arr['orderAmountAvg']   = ''; // 营收总计
            $arr['intoRate'] = '';
            $arr['orderRate'] = '';
            $arr['qkRate'] = '';
            $arr['jdCost'] = '';
            $arr['notice'] = '';
            $arr['changeRate'] = '';
            $arr['amountROI'] = '';
            $arr['factROI'] = '';
        }
        //渠道为空的情况
        $null['id'] = '';
        $null['channel_info_name']  = '渠道未填写';
        $null['channel_name']  = '渠道未填写';
        $null['channelCost'] = '';
        $whereN['is_status'] = 1;
        $whereN['c_from'] = 1;
        if($data['shop_code']){
            unset($whereN['c.shop_code']);
            $whereN['shop_code'] = $data['shop_code'];
        }
        $sql_null = '';
        $sql_null .= "sum(c.dj_day between '$start' and '$end') as mkz,";//毛客资
        if($consultation_type_id){
            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_valid=1 and c.dj_day between '$start' and '$end') as valid,";//有效
            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_intostore in ('2','3','5') c.and syjd_day between '$start' and '$end') as jd,";//进店
//            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
//            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
//            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.is_intostore=2 and c.is_success=1 and c.order_day between '$start' and '$end') as `order`,";
            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
            $sql_null .= "sum(c.consultation_type_id = ".$consultation_type_id." and c.order_type=2 and c.is_success=1 and c.order_day between '$start' and '$end') as `order`,";//进店成交量
        }else{
            $sql_null .= "sum(c.is_valid=1 and c.dj_day between '$start' and '$end') as valid,";//有效
            $sql_null .= "sum(c.is_intostore in ('2','3','5') and c.syjd_day between '$start' and '$end') as jd,";//进店
//            $sql_null .= "sum(c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
//            $sql_null .= "sum(c.is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
//            $sql_null .= "sum(c.is_success=1 and c.is_intostore=2 and c.order_day between '$start' and '$end') as `order`,";//进店成交量
            $sql_null .= "sum(c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as order1,";//网付
            $sql_null .= "sum(c.order_type=1 and c.is_success=1 and c.order_day between '$start' and '$end') as `order2`,";
            $sql_null .= "sum(c.order_type=2 and c.is_success=1 and c.order_day between '$start' and '$end') as `order`,";//进店成交量
        }
        $sql_null .= "sum(c.is_valid=2 and c.dj_day between '$start' and '$end') as dd,";//待定
        $sql_null .= "sum((c.customer_tel is not null and c.customer_tel<>'') and c.dj_day between '$start' and '$end') as tel,";//手机
        $sql_null .= "sum((is_intostore=2 or is_intostore=3 or is_intostore=5) and c.is_success=2 and c.syjd_day between '$start' and '$end') as zd";//走单
        $info_null = db('c_customerinfo')->alias('c')
            ->where($whereN)
            ->where('c.customer_channel_id is null or c.customer_channel_id=0')
            ->field($sql_null)->find();
        /* //毛客资
         $null['lrCustomer'] = db('c_customerinfo')
             ->where($whereN)
             ->where($sqlN)
             ->where('customer_channel_id is null or customer_channel_id=0')
             ->where('dj_day', 'between time', [$start, $end])
             ->count();

         //有效客资
         $null['invCustomer'] = db('c_customerinfo')
             ->where($whereN)
             ->where($sqlN)
             ->where($whereT)
             ->where('is_valid',1)
             ->where('customer_channel_id is null or customer_channel_id=0')
             ->where('yx_day', 'between time', [$start, $end])
             ->count();*/
        $null['lrCustomer'] = $info_null['mkz'];
        $null['invCustomer'] = $info_null['valid'];
        // 有效率（ 有效获取 / 毛客资 ）
        $null['invRate'] = (sprintf('%.2f', $info_null['valid'] / $info_null['mkz'] * 100)) . '%';
        // 毛客资成本
        $null['customerCost'] = '0.00';
        // 有效获取成本
        $null['invCost'] = '0.00';
        /*//待定客资
        $null['dd'] = db('c_customerinfo')
            ->where($whereN)
            ->where($sqlN)
            ->where('is_valid',2)
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->where('yx_day', 'between time', [$start, $end])
            ->count();
        // 总手机  手机号不为空的客资总数（按录入时间计算）
        $null['allTel'] = db('c_customerinfo')
            ->where($whereN)
            ->where($sqlN)
            ->where($whereT)
            ->where('is_valid',1)
            ->where('customer_tel', '<>', '')
            ->where('yx_day', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->count();
        // 进店订单 数
        $null['orderJD'] = db('c_customerinfo')
            ->where($whereN)
            ->where($sqlN)
            ->where($whereT)
            ->where('is_intostore', 'in', '2,3')
            ->where('order_type', 2)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->count();
        // 网络订单 数
        $null['orderOnline'] = db('c_customerinfo')
            ->where($whereN)
            ->where($sqlN)
            ->where($whereT)
            ->where('order_type', 1)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->count();
        // 有效订单 数
        $null['orderNum'] = db('c_customerinfo')
            ->where($whereN)
            ->where($whereT)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->count();*/
        $null['dd'] = $info_null['dd'];
        $null['allTel'] = $info_null['tel'];
        $null['orderJD'] = $info_null['order'];
        $null['orderOnline'] = $info_null['order1'];
        $null['orderNum'] = $info_null['order2'];
        // 新单成本
        $null['orderCost'] = '0.00';
        // 毛客资转化率（ 有效新单 / 有效获取 ）
        $null['mkzRate'] = (sprintf('%.2f', ($null['orderJD']+$null['orderOnline']) / $null['lrCustomer'] * 100)) . '%';

        /* // 进店数量
         $null['intoNum'] = db('c_customerinfo')
             ->where($whereN)
             ->where($sqlN)
             ->where($whereT)
             ->where('is_intostore', 'in', '2,3')
             ->where('syjd_day', 'between time', [$start, $end])
             ->where('customer_channel_id is null or customer_channel_id=0')
             ->count();*/
        if($data['shop_code']){
            unset($whereN['shop_code']);
            $sqlN = 'c.shop_code in '.$belong_shop_code;
        }
        // 套系均值（有效单套系应收款均值）
        $null['totalAmount'] = db('c_customerinfo')->alias('c')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($whereN)
            ->where($sqlN)
            ->where('c.customer_channel_id is null or c.customer_channel_id=0')
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->sum('o.order_amount');
        // 营收（实际收入  不区分有效无效）
        $null['factMoney'] = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($whereN)
            ->where($sqlN)
            ->where('c.customer_channel_id is null or c.customer_channel_id=0')
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->sum('d.order_fact');


        $null['zd']    = $info_null['jd']-$info_null['order2'];      // 订单总计
        $null['orderAmountAvg'] = sprintf('%.2f',$null['totalAmount']/$info_null['order2']);

        // 进店率（ 实际进店 / 有效获取 ）
        $null['intoRate'] = (sprintf('%.2f', $info_null['jd'] / $info_null['valid'] * 100)) . '%';
        // 成交率（ 有效新单 / 实际进店 ）
        $null['orderRate'] = (sprintf('%.2f', $info_null['order'] / $info_null['jd'] * 100)) . '%';
        //全款率 实收/营收
        $null['qkRate'] = (sprintf('%.2f', $null['factMoney'] / $null['totalAmount'] * 100)) . '%';
        $null['jdCost'] = '0.00';
        $null['notice'] = '0.00';

        // 转化率（ 有效新单 / 有效获取 ）
        $null['changeRate'] = (sprintf('%.2f', $info_null['order2'] / $info_null['valid'] * 100)) . '%';


        // ROI（实收：花费）(营收)
        $null['amountROI'] = '0.00';
        $null['factROI'] = '0.00';

        array_push($returnData,$null);
        //加上渠道为空的数量
        $arr['lrCustomer']  = $arr['lrCustomer']+$null['lrCustomer'];    // 录入总计
        $arr['invCustomer'] = $arr['invCustomer']+$null['invCustomer'];   // 有效总计
        $arr['invRate'] = '';
        $arr['dd'] = $arr['dd']+$null['dd'];   // 婚纱有效总计
        $arr['allTel']      = $arr['allTel']+$null['allTel'];        // 总手机总计
        $arr['intoNum']     = $arr['intoNum']+$null['intoNum'];       // 进店总计
        $arr['orderOnline']    = $arr['orderOnline']+$null['orderOnline'];      // 订单总计
        $arr['orderJD']    = $arr['orderJD']+$null['orderJD'];      // 订单总计
        $arr['orderNum']    = $arr['orderNum']+$null['orderNum'];      // 订单总计
        $arr['zd']    = $arr['zd']+$null['zd'];      // 订单总计
        $arr['factMoney']   = sprintf('%.2f',$arr['factMoney']+$null['factMoney']); // 营收总计
        $arr['totalAmount']   = sprintf('%.2f',$arr['totalAmount']+$null['totalAmount']); // 一销套系
        $arr['orderAmountAvg'] = sprintf('%.2f',($arr['totalAmount']+$null['totalAmount'])/$arr['orderNum']);

        $arr['invRate'] = sprintf('%.2f', $arr['invCustomer'] / $arr['lrCustomer'] * 100) . '%';
        $arr['intoRate'] = sprintf('%.2f', $arr['intoNum'] / $arr['invCustomer'] * 100) . '%';
        $arr['orderRate'] = sprintf('%.2f', $arr['orderJD'] / $arr['intoNum'] * 100) . '%';
        $arr['qkRate'] = sprintf('%.2f', $arr['factMoney'] / $arr['totalAmount'] * 100) . '%';
        $arr['jdCost'] = sprintf('%.2f', $arr['channelCost'] / $arr['intoNum']);
        $arr['notice'] = sprintf('%.2f', $arr['channelCost'] / $arr['totalAmount'] * 100) . '%';
        $arr['mkzRate'] = sprintf('%.2f', ($arr['orderOnline']+$arr['orderJD']) / $arr['lrCustomer'] * 100) . '%';
        $arr['changeRate'] = sprintf('%.2f', $arr['orderNum'] / $arr['invCustomer'] * 100) . '%';
        $arr['customerCost'] = sprintf('%.2f', $arr['channelCost'] / $arr['lrCustomer']);
        $arr['invCost'] = sprintf('%.2f', $arr['channelCost'] / $arr['invCustomer']);
        $arr['orderCost'] = sprintf('%.2f', $arr['channelCost'] / $arr['orderNum']);
        $arr['amountROI'] = sprintf('%.2f',intval($arr['totalAmount'])/intval($arr['channelCost']));
        $arr['factROI'] = sprintf('%.2f',intval($arr['factMoney'])/intval($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','实收ROI');
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
            $file = $shop[0]['shop_name'].'-'.$ff.'.xlsx';
            controller("crm/Customer", "lib")->export($title, $returnData, $file);
        } else {
            return json($return);
        }
    }

    public function show(){
        $did = strtolower(input('param.did'));
        $info = db('s_report_form')->alias('f')->join('s_report_detail d','d.form_id=f.id')->where('d.id',$did)->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();
        $city = db('s_shop_address')->where('shop_code',$info['shop_code'])->where('type',2)->select();
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);

        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //来源渠道
//        $channel = controller("Customer", "lib")->getChannel($info['shop_code']);
//        $this->assign("channel", $channel);
        $channels = getChannelJson($info['shop_code']);
        $this->assign('channel', json_encode($channels));
        //已设置的归属店
        $checked_shop = db_config('dj_shops_'.session('shop_code'));
        $this->assign('shop',$checked_shop);
        $code = $this->getCode();
        $display = APP_PATH.'crm'.DS.'view'.DS.'report'.DS.strtolower($info['report_class_name']).'.html';
        $title = db('s_report_form')->where('code', $code)->value('report_name');
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', $shopInfo[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}