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

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

    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']));
        $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['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.channel_name';
        $channels = '';
        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.channel_name';
        $cKey = 's.channel_name';
        $channel_name = array_column($channels,'channel_name');
        // 花费
        $cus = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.customer_channel','in',$channel_name)
            ->where('c.dj_day', 'between time', [$start, $end])
            ->column('customer_channel_id','c.id');

        $temp = [];
        $temp1 = [];
        foreach($cus as $k=>$v){
            $temp[] = $k;
            $temp1[$v][] = $k;
        }
        $channelCost = db('c_customer_from')
            ->where('cid','in',$temp)
            ->column('c_channel_cost','cid');
        $cost = [];
        foreach($temp1 as $k=>$v){
            foreach($v as $kk=>$vv){
                $cost[$k] += floatval($channelCost[$vv]);
            }
        }

        // 录入客资量
        $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.is_valid','in',['1','4','5'])
            ->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);
        // 待定客资量
        $ddCustomer =db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->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);
        // 无效客资量
        $wxCustomer =db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.is_valid', 3)
            ->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','in',[1,4,5])
            ->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($whereT)
            ->where('c.is_intostore', 'in', '2,3,5')
            ->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($whereT)
            ->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')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($where)
            ->where('d.pay_type',1)
            ->where('d.pay_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(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('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('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_name'] = '总计';
        foreach ($channels as $k => $v) {
            $returnData[$k]['id'] = $v['id'];
            $returnData[$k]['channel_name'] = $v['channel_info_name'].'=>'.$v['channel_name'];


            $returnData[$k]['id'] = $v['id'];
            $returnData[$k]['channelCost'] = $cost[$v['id']] ? sprintf('%.2f',$cost[$v['id']]) : 0;
            $returnData[$k]['lrCustomer'] = $allCustomer[$v['channel_name']]['num'] ? $allCustomer[$v['channel_name']]['num'] : 0;
            $returnData[$k]['invCustomer'] = $validCustomer[$v['channel_name']]['num'] ? $validCustomer[$v['channel_name']]['num'] : 0;
            $returnData[$k]['dd'] = $ddCustomer[$v['channel_name']]['num'] ? $ddCustomer[$v['channel_name']]['num'] : 0;
            $returnData[$k]['wx'] = $wxCustomer[$v['channel_name']]['num'] ? $wxCustomer[$v['channel_name']]['num'] : 0;
            $returnData[$k]['allTel'] = $allTel[$v['channel_name']]['num'] ? $allTel[$v['channel_name']]['num'] : 0;
            $returnData[$k]['intoNum'] = $intoNum[$v['channel_name']]['num'] ? $intoNum[$v['channel_name']]['num'] : 0;
            $returnData[$k]['orderNum'] = $orderNum[$v['channel_name']]['num'] ? $orderNum[$v['channel_name']]['num'] : 0;
            $returnData[$k]['factMoney'] = $factMoney[$v['channel_name']]['fact_money'] ? sprintf('%.2f',$factMoney[$v['channel_name']]['fact_money']) : 0;
            $returnData[$k]['totalAmount'] = $order_amount_avg[$v['channel_name']]['totalpay_money'] ? sprintf('%.2f',$order_amount_avg[$v['channel_name']]['totalpay_money']) : 0;
            $returnData[$k]['orderAmountAvg'] = $order_amount_avg[$v['channel_name']]['fact_money'] ?
                sprintf('%.2f',$order_amount_avg[$v['channel_name']]['fact_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]['mkzOrderRate'] = (sprintf('%.2f', $returnData[$k]['orderNum'] / $returnData[$k]['lrCustomer'] * 100)) . '%';
            // 毛客资成本
            $returnData[$k]['customerCost'] = sprintf('%.2f', $cost[$v['id']] / $returnData[$k]['lrCustomer']);
            // 有效获取成本
            $returnData[$k]['invCost'] = sprintf('%.2f', $cost[$v['id']] / $returnData[$k]['invCustomer']);
            // 进店成本
            $returnData[$k]['jdCost'] = sprintf('%.2f', $cost[$v['id']] / $returnData[$k]['intoNum']);
            // 新单成本
            $returnData[$k]['orderCost'] = sprintf('%.2f', $cost[$v['id']] / $returnData[$k]['orderNum']);
            // ROI（实收：花费）(营收)
            $returnData[$k]['ROI'] = sprintf('%.2f',intval($returnData[$k]['factMoney'])/intval
                    ($returnData[$k]['channelCost'])).':1';

            $arr['channelCost'] += $cost[$v['id']];   // 花费总计
            $arr['lrCustomer']  += $allCustomer[$v['channel_name']]['num'];    // 录入总计
            $arr['invCustomer'] += $validCustomer[$v['channel_name']]['num'];   // 有效总计
            $arr['dd'] += $returnData[$k]['dd'];   // 有效总计
            $arr['wx'] += $returnData[$k]['wx'];   // 无效总计
            $arr['allTel']      += $allTel[$v['channel_name']]['num'];        // 总手机总计
            $arr['intoNum']     += $intoNum[$v['channel_name']]['num'];       // 进店总计
            $arr['orderNum']    += $orderNum[$v['channel_name']]['num'];      // 订单总计
            $arr['factMoney']   += $factMoney[$v['channel_name']]['fact_money']; // 营收总计
            $arr['totalAmount']   += $order_amount_avg[$v['channel_name']]['totalpay_money']; // 一销套系
        }
        //渠道为空的情况
        $null['id'] = '';
        $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($whereT)
            ->where('is_valid', 'in',[1,4,5])
            ->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['wx'] = db('c_customerinfo')
            ->where($whereN)
            ->where('is_valid',3)
            ->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($whereT)
            ->where('is_valid',1)
            ->where('customer_tel', '<>', '')
            ->where('dj_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($whereT)
            ->where('is_intostore', 'in', '2,3,5')
            ->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($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['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('d.pay_type',1)
            ->where('c.customer_channel_id is null or c.customer_channel_id=0')
            ->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_day', 'between time', [$start, $end])
            ->sum('o.order_amount');

        $null['orderAmountAvg'] = sprintf('%.2f',$null['factMoney']/$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['mkzOrderRate'] = (sprintf('%.2f', $null['orderNum'] / $null['lrCustomer'] * 100)) . '%';
        // 毛客资成本
        $null['customerCost'] = '0.00';
        // 有效获取成本
        $null['invCost'] = '0.00';
        // 新单成本
        $null['orderCost'] = '0.00';
        $null['jdCost'] = '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['wx'] = $arr['wx']+$null['wx'];   // 婚纱有效总计
        $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['factMoney']+$null['factMoney'])/$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['mkzOrderRate'] = sprintf('%.2f', $arr['orderNum'] / $arr['lrCustomer'] * 100) . '%';
        $arr['customerCost'] = sprintf('%.2f', $arr['channelCost'] / $arr['lrCustomer']);
        $arr['invCost'] = sprintf('%.2f', $arr['channelCost'] / $arr['invCustomer']);
        $arr['jdCost'] = sprintf('%.2f', $arr['channelCost'] / $arr['intoNum']);
        $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');
            $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);
    }

}