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

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

    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')->where('d.id',$data['did'])->field('d.id,d.shop_code,d.brandclass_id,f.report_class_name')->find();

        $shop_code = $det['shop_code'];
        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['customer_type'] = 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'];
        }

        $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';
        }
        // var_dump($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');
        }
        $sql0 = db()->getLastSql();
        // 录入客资量
        $allCustomer = db('c_customerinfo')->alias('c')
            ->join('s_channel s', 's.id=c.customer_channel_id', 'left')
            ->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);
        $sql1 = db()->getLastSql();
        // 有效客资量
        $validCustomer =db('c_customerinfo')->alias('c')
            ->join('s_channel s', 's.id=c.customer_channel_id', 'left')
            ->where($where)
            ->where($whereT)
            ->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);
        $sql2 = db()->getLastSql();
        // 无效客资量
        $noValidCustomer =db('c_customerinfo')->alias('c')
            ->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where($whereT)
            ->where('c.is_valid', 3)
            ->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);
        $sql3 = db()->getLastSql();
        // 订单 数
        $orderNum = db('c_customerinfo')->alias('c')
            ->join('s_channel s', 's.id=c.customer_channel_id','left')
            ->join('c_customer_order o','o.customer_id=c.id','left')
            ->where($where)
            ->where($whereT)
            ->where('c.is_success', '<>',2)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->group($group)
            ->column('count(o.id) as num,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', $cKey);
        $sql4 = db()->getLastSql();
        // 营收（实际收入  不区分有效无效）
        $factMoney = db('c_customerinfo')->alias('c')
            ->join('s_channel s', 's.id=c.customer_channel_id','left')
            ->join('c_customer_order o','o.customer_id=c.id','left')
            ->join('c_order_detail d','d.order_sn=o.order_sn','left')
            ->where($where)
            ->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);
        $sql5 = db()->getLastSql();
        // 套系均值（有效单套系应收款均值）
        $order_amount_avg = db('c_customerinfo')->alias('c')
            ->join('s_channel s', 's.id=c.customer_channel_id','left')
            ->join('c_customer_order o','o.customer_id=c.id','left')
            ->where($where)
            ->where('c.is_success', '<>',2)
            ->where('c.order_start_time', '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);
        $sql6 = db()->getLastSql();
        $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_info_name'] = $v['channel_info_name'];
            $returnData[$k]['channel_name'] = $v['channel_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]['orderNum'] = $orderNum[$v['id']]['num'] ? $orderNum[$v['id']]['num'] : 0;
            // 转化率（ 新单 / 毛客资 ）
            $returnData[$k]['changeRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $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]['customerCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['lrCustomer']);
            // 签单均价
            $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]['orderCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['orderNum']);
            // 有效客资
            $returnData[$k]['invCustomer'] = $validCustomer[$v['id']]['num'] ? $validCustomer[$v['id']]['num'] : 0;
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$k]['invRate'] = (sprintf('%.2f', $returnData[$k]['invCustomer'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            // 有效获取成本
            $returnData[$k]['invCost'] = sprintf('%.2f', $channelCost[$v['id']]['cost'] / $returnData[$k]['invCustomer']);
            // 无效客资
            $returnData[$k]['noInvCustomer'] = $noValidCustomer[$v['id']]['num'] ? $noValidCustomer[$v['id']]['num'] : 0;
            // 无效率（ 无效 / 毛客资 ）
            $returnData[$k]['noInvRate'] = (sprintf('%.2f', $returnData[$k]['noInvCustomer'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            // ROI（实收：花费）(营收)
            $returnData[$k]['ROI'] = sprintf('%.2f',intval($returnData[$k]['factMoney'])/intval                    ($returnData[$k]['channelCost'])).':1';
            $arr['channelCost'] += $channelCost[$v['id']]['cost'];   // 花费总计
            $arr['lrCustomer']  += $allCustomer[$v['id']]['num'];    // 录入总计
            $arr['invCustomer'] += $validCustomer[$v['id']]['num'];   // 有效总计
            $arr['noInvCustomer'] += $noValidCustomer[$v['id']]['num'];   // 有效总计
            $arr['orderNum']    += $orderNum[$v['id']]['num'];      // 订单总计
            $arr['factMoney']   += $factMoney[$v['id']]['fact_money']; // 营收总计
            $arr['totalAmount']   += $order_amount_avg[$v['id']]['totalpay_money']; // 一销套系
        }
        // var_dump($returnData);die;
        //渠道为空的情况
        /*
        $null['id'] = '';
        $null['channel_name']  = '渠道未填写';
        $null['channelCost'] = '';
        $whereN['is_status'] = 1;
        $whereN['c_from'] = 1;
        $whereN['customer_type'] = 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($whereT)
            ->where('is_valid',1)
            ->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($whereT)
            ->where('is_valid',3)
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->where('dj_day', 'between time', [$start, $end])
            ->count();
        // 订单 数
        $null['orderNum'] = db('c_customerinfo')
            ->where($whereN)
            ->where($whereT)
            ->where('is_success', 1)
            ->where('order_start_time', 'between time', [$start, $end])
            ->where('customer_channel_id is null or customer_channel_id=0')
            ->count();
        // 营收（实际收入  不区分有效无效）
        $null['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($whereN)
            ->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['totalAmount'] = 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($whereN)
            ->where('c.customer_channel_id is null or c.customer_channel_id=0')
            ->where('c.is_success', 1)
            ->where('c.order_start_time', 'between time', [$start, $end])
            ->sum('o.order_amount');

        $null['orderAmountAvg'] = sprintf('%.2f',$null['totalAmount']/$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['zhuaninvCustomer'] = $arr['zhuaninvCustomer']+$null['zhuaninvCustomer'];   // 有效总计
        $arr['dd'] = $arr['dd']+$null['dd'];   // 婚纱有效总计
        $arr['bh'] = $arr['bh']+$null['bh'];   // 婚纱有效总计
        $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['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['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);
        
        $return['sql0'] = $sql0;
        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $return['sql4'] = $sql4;
        $return['sql5'] = $sql5;
        $return['sql6'] = $sql6;

        $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');
            $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);
        $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);
    }

}