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

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

    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['customer_type'] = 1;
        $where['add_shop_code'] = $shop_code;
        $whereN['add_shop_code'] = $shop_code;
        if($data['consultation_type_id']){
            $consultation_type_id = $data['consultation_type_id'];
        }

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

        // 花费
        $cost = db('s_channel_cost')->alias('c')
            ->where('c.cost_date', 'between time', [$start, $end])
            ->where('c.shop_code', $shop_code)
            ->group('c.channel_name')
            ->column('sum(c.cost) as cost','c.channel_name');
        $sql = "sum(dj_day between '$start' and '$end') as mkz,";
        if($data['consultation_type_id']){
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_valid=1 and yx_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_intostore in ('2','3','5') and syjd_day between '$start' and '$end') as jd,";
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and is_success in ('1','3') and order_start_time between '$start' and '$end') as newOrder,";//订单
            $sql .= "sum(consultation_type_id = ".$consultation_type_id." and (is_success=1 or is_success=3) and fact_money>0 and order_start_time between '$start' and '$end') as validOrder";//订单
        }else{
            $sql .= "sum(is_valid=1 and yx_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(is_intostore in ('2','3','5') and syjd_day between '$start' and '$end') as jd,";
            $sql .= "sum(is_success in ('1','3') and order_start_time between '$start' and '$end') as newOrder,";
            $sql .= "sum((is_success=1 or is_success=3) and fact_money>0 and order_start_time between '$start' and '$end') as validOrder";
        }


        // 录入客资量
        $info= db('c_customerinfo')
            ->where($where)
            ->group('customer_channel')
            ->column($sql,'customer_channel');
        // 营收（实际收入  不区分有效无效）
        $fact = 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_time', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(d.order_fact) as fact_money,s.channel_name,s.id', 'c.customer_channel');

        $returnData = [];
        $method = array('花费', '毛客资', '有效获取', '进店', '新单', '有效单', '成交金额','成交均值', '毛客资成本', '有效获取成本', '成交成本','获取转进店率', '有效获取到成交率', '毛客资到成交率', );
        $hf = 0;
        $mkz = 0;
        $valid = 0;
        $jd = 0;
        $order = 0;
        $validOrder = 0;
        $fact_money = 0;
        $count = count($channels);
        foreach ($method  as $kk=>$vv) {
            switch($vv){
                case '花费':
                $returnData[$kk]['method'] = '花费';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = sprintf('%.2f',$cost[$v['channel_name']]);
                    $hf += $cost[$v['channel_name']];
                }
                $returnData[$kk]['total'] = sprintf('%.2f',$hf);
                break;
                case '毛客资':
                $returnData[$kk]['method'] = '毛客资';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['mkz'];
                    $mkz += $info[$v['channel_name']]['mkz'];
                }
                $returnData[$kk]['total'] = $mkz;
                break;
                case '有效获取':
                $returnData[$kk]['method'] = '有效获取';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['valid'];
                    $valid += $info[$v['channel_name']]['valid'];
                }
                $returnData[$kk]['total'] = $valid;
                break;
                case '进店':
                $returnData[$kk]['method'] = '进店';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['jd'];
                    $jd += $info[$v['channel_name']]['jd'];
                }
                $returnData[$kk]['total'] = $jd;
                break;
                case '新单':
                $returnData[$kk]['method'] = '新单';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['newOrder'];
                    $order += $info[$v['channel_name']]['newOrder'];
                }
                    $returnData[$kk]['total'] = $order;
                break;
                case '有效单':
                $returnData[$kk]['method'] = '有效单';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['validOrder'];
                    $validOrder += $info[$v['channel_name']]['validOrder'];
                }
                    $returnData[$kk]['total'] = $validOrder;
                break;
                case '成交金额':
                $returnData[$kk]['method'] = '成交金额';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $fact[$v['channel_name']]['fact_money'] ? sprintf('%.2f',$fact[$v['channel_name']]['fact_money']) : '';
                    $fact_money += $fact[$v['channel_name']]['fact_money'];
                }
                    $returnData[$kk]['total'] = sprintf('%.2f',$fact_money);
                break;
                case '成交均值':
                $returnData[$kk]['method'] = '成交均值';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = sprintf('%.2f',$fact[$v['channel_name']]['fact_money']/$info[$v['channel_name']]['validOrder']);
                }
                $returnData[$kk]['total'] = sprintf('%.2f',$fact_money/$validOrder);
                break;
                case '毛客资成本':
                $returnData[$kk]['method'] = '毛客资成本';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = sprintf('%.2f',$cost[$v['channel_name']]['fact_money']/$info[$v['channel_name']]['mkz']);
                }
                $returnData[$kk]['total'] = sprintf('%.2f',$hf/$mkz);
                break;
                case '有效获取成本':
                $returnData[$kk]['method'] = '有效获取成本';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = sprintf('%.2f',$cost['fact_money'][$v['channel_name']]/$info[$v['channel_name']]['valid']);
                }
                $returnData[$kk]['total'] = sprintf('%.2f',$hf/$valid);
                break;
                case '成交成本':
                $returnData[$kk]['method'] = '成交成本';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = sprintf('%.2f',$cost[$v['channel_name']]['fact_money']/$info[$v['channel_name']]['validOrder']);
                }
                $returnData[$kk]['total'] = sprintf('%.2f',$hf/$validOrder);
                break;
                case '获取转进店率':
                $returnData[$kk]['method'] = '获取转进店率';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['jd']/$info[$v['channel_name']]['valid']>0 ? sprintf('%.2f',$info[$v['channel_name']]['jd']/$info[$v['channel_name']]['valid']*100).'%' : '';
                }
                $returnData[$kk]['total'] = $jd/$valid>0 ? sprintf('%.2f',$jd/$valid*100).'%'  : '';
                break;
                case '有效获取到成交率':
                $returnData[$kk]['method'] = '有效获取到成交率';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['validOrder']/$info[$v['channel_name']]['valid'] > 0 ? sprintf('%.2f',$info[$v['channel_name']]['validOrder']/$info[$v['channel_name']]['valid']*100).'%' : '';
                }
                $returnData[$kk]['total'] = $validOrder/$valid>0 ? sprintf('%.2f',$validOrder/$valid*100).'%'  : '';
                break;
                case '毛客资到成交率':
                $returnData[$kk]['method'] = '毛客资到成交率';
                foreach ($channels as $k => $v) {
                    $returnData[$kk][$v['channel_name']] = $info[$v['channel_name']]['validOrder']/$info[$v['channel_name']]['mkz']>0 ?sprintf('%.2f',$info[$v['channel_name']]['validOrder']/$info[$v['channel_name']]['mkz']*100).'%' : '';
                }
                    $returnData[$kk]['total'] = $validOrder/$valid>0 ? sprintf('%.2f',$validOrder/$mkz*100).'%'  : '';
                break;
            }
        }



        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channels);
        $return['data'] = $returnData;
        // 导出
        if ($data['need'] == 1) {
            $title = ['统计类别'];
            $channel_name = array_column($channels,'channel_name');
            $title = array_merge($title,$channel_name);
            array_push($title,'总计');
            $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();

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

        //来源渠道
        $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);
    }

}