<?php
/**
 * 报表实现类 上海桔子摄影----渠道数据统计
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong/wangzhenya 2018-05-29 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
class Jz_channel_data extends Report{
    private $level=1;
    private $type=1;
    private $code='code1536997100';

    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', 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'=>'报表配置有误');
        }
        if($data['channel_id']){
            $channels = explode(',',$data['channel_id']);
        }else{
            // 来源渠道
            $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
            $channels = array_column($channels,'channel_name');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        $whereCost['shop_code'] = $shop_code;
        if((int)$data['consultation_type_id']){
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        if((int)$data['consultation_type_id']){
            $sql .= 'sum(consultation_type_id = '.(int)$data['consultation_type_id'].' and dj_day between "'.$start.'" and "'.$end.'" and is_valid in (\'1\',\'5\',\'4\',\'2\')) as valid,';
            $sql .= 'sum(consultation_type_id = '.(int)$data['consultation_type_id'].' and yjd_day between "'.$start.'" and "'.$end.'") as yy,';
            $sql .= 'sum(consultation_type_id = '.(int)$data['consultation_type_id'].' and syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in (\'2\',\'3\',\'5\')) as jd,';
            $sql .= 'sum(consultation_type_id = '.(int)$data['consultation_type_id'].' and order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`,';
            $sql .= 'sum(consultation_type_id = '.(int)$data['consultation_type_id'].' and dj_day between "'.$start.'" and "'.$end.'" and is_valid=2) as dd,';
            $sql .= 'sum(consultation_type_id = '.(int)$data['consultation_type_id'].' and dj_day between "'.$start.'" and "'.$end.'" and is_valid=3) as unValid';
        }else{
            $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid in (\'1\',\'5\',\'4\',\'2\')) as valid,';
            $sql .= 'sum(yjd_day between "'.$start.'" and "'.$end.'") as yy,';
            $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in (\'2\',\'3\',\'5\')) as jd,';
            $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`, ';
            $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=2) as dd,';
            $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid=3) as unValid';
        }
        
        $info = db('c_customerinfo')
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->group('customer_channel')
            ->column($sql, 'customer_channel');
        //花费
        $cost = db('s_channel_cost')
            ->where('cost_date', 'between time', [$start, $end])
            ->where($whereCost)
            ->where('channel_name','in',$channels)
            ->group('channel_name')
            ->column('sum(cost) as cost','channel_name');
        //实收
        $factMoney = db('c_customerinfo')->alias('c')->join('s_channel s', 's.id=c.customer_channel_id')
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->where('order_day', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(c.fact_money) as fact,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', 'c.customer_channel');

        //营收
        $totalMoney = 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 and o.customer_id = c.id','left')
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(o.order_amount) as total,s.channel_name,s.channel_class_name,s.channel_info_name,s.id','c.customer_channel');
        $returnData = [];
        $arr = [];
        foreach($channels as $k=>$v){
            $returnData[$k]['channel_name'] = $v;
            $returnData[$k]['mkz'] = $info[$v]['mkz'];
            $returnData[$k]['valid'] = $info[$v]['valid'];
            $returnData[$k]['unValid'] = $info[$v]['unValid'];
            $returnData[$k]['dd'] = $info[$v]['dd'];
            $returnData[$k]['yy'] = $info[$v]['yy'];
            $returnData[$k]['jd'] = $info[$v]['jd'];
            $returnData[$k]['order'] = $info[$v]['order'];
            $returnData[$k]['validRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValidRate'] = $info[$v]['unValid'] ? sprintf('%.2f',$info[$v]['unValid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['ddRate'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['mkzJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validJdRate'] = $info[$v]['jd'] ? sprintf('%.2f',$info[$v]['jd']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['jdOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['jd']*100).'%' : '0%';
            $returnData[$k]['mkzOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['validOrderRate'] = $info[$v]['order'] ? sprintf('%.2f',$info[$v]['order']/$info[$v]['valid']*100).'%' : '0%';
            $returnData[$k]['cost'] = sprintf('%.2f',$cost[$v]);
            $returnData[$k]['mkzCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['mkz']) : '';
            $returnData[$k]['validCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['valid']) : '';
            $returnData[$k]['jdCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['jd']) : '';
            $returnData[$k]['orderCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['order']) : '';
            $returnData[$k]['orderAVG'] =  $info[$v]['order'] ? sprintf('%.2f',$totalMoney[$v]['total']/$info[$v]['order']) : '';
            $returnData[$k]['totalMoney'] =  sprintf('%.2f',$totalMoney[$v]['total']);
            $returnData[$k]['factMoney'] =  sprintf('%.2f',$factMoney[$v]['fact']);
            $returnData[$k]['ROI'] = $returnData[$k]['totalMoney'] ? sprintf('%.2f',$returnData[$k]['totalMoney']/$returnData[$k]['cost']) : '';
            //总计
            $arr['channel_name'] = '总计';
            $arr['mkz'] += $returnData[$k]['mkz'];
            $arr['valid'] += $returnData[$k]['valid'];
            $arr['unValid'] += $returnData[$k]['unValid'];
            $arr['dd'] += $returnData[$k]['dd'];
            $arr['yy'] += $returnData[$k]['yy'];
            $arr['jd'] += $returnData[$k]['jd'];
            $arr['order'] += $returnData[$k]['order'];
            $arr['validRate'] = '';
            $arr['unValidRate'] = '';
            $arr['ddRate'] = '';
            $arr['mkzJdRate'] = '';
            $arr['validJdRate'] = '';
            $arr['jdOrderRate'] = '';
            $arr['mkzOrderRate'] = '';
            $arr['validOrderRate'] = '';
            $arr['cost'] += $returnData[$k]['cost'];
            $arr['mkzCost'] = '';
            $arr['validCost'] = '';
            $arr['jdCost'] = '';
            $arr['orderCost'] = '';
            $arr['orderAVG'] = '';
            $arr['totalMoney'] += floatval($returnData[$k]['totalMoney']);
            $arr['factMoney'] += floatval($returnData[$k]['factMoney']);
            $arr['ROI'] = '';
        }


        $arr['validRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '0%';
        $arr['unValidRate'] = $arr['valid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['ddRate'] = $arr['valid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['mkzJdRate'] = $arr['valid'] ? sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%' : '0%';
        $arr['validJdRate'] = $arr['valid'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '0%';
        $arr['jdOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['jd']*100).'%' : '0%';
        $arr['mkzOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%' : '0%';
        $arr['validOrderRate'] = $arr['valid'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '0%';
        $arr['mkzCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['mkz']) : '';
        $arr['validCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['valid']) : '';
        $arr['jdCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['jd']) : '';
        $arr['orderCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['order']) : '';
        $arr['orderAVG'] = $arr['totalMoney'] ? sprintf('%.2f',$arr['totalMoney']/$arr['order']) : '';
        $arr['totalMoney'] = sprintf('%.2f',$arr['totalMoney']);
        $arr['factMoney'] = sprintf('%.2f',$arr['factMoney']);
        $arr['ROI'] = $arr['totalMoney'] ? sprintf('%.2f',$arr['totalMoney']/$arr['cost']) : '';

        $returnData[] = $arr;
        $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(){
        $code = $this->getCode();
        $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();

        //来源渠道
        $channel = getChannelJson($info['shop_code']);
        $this->assign("channel", json_encode($channel));
        //消费类型
        $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);
        $data['type'] = 2;
        $data['shop_code'] = $info['shop_code'];
        $city =  controller("Customer", "lib")->address($data);*/


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

        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', $shop[0]['shop_name'].'-'.$title);
        $this->assign('did', $info['id']);
        $this->assign('today',date('Y-m-d'));
        $this->assign('yestoday',date('Y-m-d',time()-86400));
        return $this->fetch($display);
    }
}