<?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 Wx_ds_channel_ld extends Report {

    private $level=1;
    private $type=3;
    private $code='code1529029232';

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

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

        $start = date('Y-m-d 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $shop_code = $data['shop_code'];
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;

        // 如果不是旅拍事业部，那么网销报表中查新客资，如果是旅拍事业部，不限制类型
        if (session('brandclass_id') != 2) {
            $where['c.customer_type'] = 1;
        }

        $whereN['add_shop_code'] = $shop_code;
        // 地域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(session('shop_type') == 1 || session('shop_type') == 3){
        //     $whereT['c.consultation_type_id'] = HS_TYPE;
        // }

        $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 = db('c_customerinfo')->alias('c')->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 =db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where($whereT)
            // ->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($whereT)
            ->where('is_valid',1)
            ->where('c.customer_tel', '<>', '')
            ->where('c.yx_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('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 = db('c_customerinfo')->alias('c')->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 = db('c_customerinfo')->alias('c')->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'] ? sprintf('%.2f',$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']/$returnData[$k]['orderNum']) : 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']; // 营收总计
//            }
        }
        //渠道为空的情况
        $null['id'] = '';
        $null['channel_info_name']  = '渠道未填写';
        $null['channel_name']  = '渠道未填写';
        $null['channelCost'] = '';
        $whereN['is_status'] = 1;
//        $whereN['c_from'] = 1;
        //毛客资
        $null['lrCustomer'] = db('c_customerinfo')
            ->where($whereN)
            ->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('consultation_type_id',HS_TYPE)
            ->where('is_valid',1)
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->where('yx_day', 'between time', [$start, $end])
            ->count();
        //待定客资
        $null['dd'] = db('c_customerinfo')
            ->where($whereN)
            ->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('consultation_type_id',HS_TYPE)
            ->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['intoNum'] = db('c_customerinfo')
            ->where($whereN)
            ->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();
        // 有效订单 数
        $null['orderNum'] = db('c_customerinfo')
            ->where($whereN)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->count();
        // 营收（实际收入  不区分有效无效）
        $null['factMoney'] = db('c_customerinfo')
            ->where($whereN)
            ->where('order_start_time', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->count();
        // 套系均值（有效单套系应收款均值）
        $order_avg = db('c_customerinfo')
            ->where($whereN)
            ->where('is_success', 1)
            ->where('order_day', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->sum('totalpay_money');
        $null['orderAmountAvg'] = sprintf('%.2f',$order_avg/$null['orderNum']);
        // 有效率（ 有效获取 / 毛客资 ）
        $null['invRate'] = (sprintf('%.2f', $null['invCustomer'] / $null['lrCustomer'] * 100)) . '%';
        // 进店率（ 实际进店 / 有效获取 ）
        $null['intoRate'] = (sprintf('%.2f', $null['intoNum'] / $null['invCustomer'] * 100)) . '%';
        // 成交率（ 有效新单 / 实际进店 ）
        $null['orderRate'] = (sprintf('%.2f', $null['orderNum'] / $null['intoNum'] * 100)) . '%';
        // 转化率（ 有效新单 / 有效获取 ）
        $null['changeRate'] = (sprintf('%.2f', $null['orderNum'] / $null['invCustomer'] * 100)) . '%';
        // 毛客资成本
        $null['customerCost'] = '0.00';
        // 有效获取成本
        $null['invCost'] = '0.00';
        // 新单成本
        $null['orderCost'] = '0.00';
        // ROI（实收：花费）(营收)
        $null['ROI'] = '0.00:1';

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

        $arr['orderAmountAvg'] = '';
        $arr['invRate'] = sprintf('%.2f', $arr['invCustomer'] / $arr['lrCustomer'] * 100) . '%';
        $arr['intoRate'] = sprintf('%.2f', $arr['intoNum'] / $arr['invCustomer'] * 100) . '%';
        $arr['orderRate'] = sprintf('%.2f', $arr['orderNum'] / $arr['intoNum'] * 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['ROI'] = sprintf('%.2f',intval($arr['factMoney'])/intval($arr['channelCost'])).':1';
        $arr['orderAmountAvg'] = '';
        $arr['invRate'] = sprintf('%.2f', $arr['invCustomer'] / $arr['lrCustomer'] * 100) . '%';
        $arr['intoRate'] = sprintf('%.2f', $arr['intoNum'] / $arr['invCustomer'] * 100) . '%';
        $arr['orderRate'] = sprintf('%.2f', $arr['orderNum'] / $arr['intoNum'] * 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['ROI'] = sprintf('%.2f',intval($arr['factMoney'])/intval($arr['channelCost'])).':1';
        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');
            $code = $this->getCode();
            $ff = db('s_report_form')->where('code', $code)->value('report_name');
            $file = session('department_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();
        // 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);
        $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');
        $this->assign('title', session('department_name').'-'.$title);
        //查询事业部下的电商店
        $shop = controller('crm/Customer','lib')->shop(['belong_shop_code'=>$info['shop_code']]);
        $this->assign('shop', $shop);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}