<?php
/**
 * 报表实现类 西安绝对人气 定制 来源渠道数据统计
 * *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong 2020-06 $
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;

class Xa_channel_data extends Report {

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

    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'];
        $add_shop_code = session('shop_code');
        $shop_code = $data['shop_code']?$data['shop_code']:session('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($add_shop_code);
            $channels = array_column($channels,'channel_name');
        }
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $add_shop_code;
        if($data['shop_code']){
            $where['c.shop_code'] = $shop_code;
        }
        $whereCost['shop_code'] = $add_shop_code;
        // 花费录入维度
        $method = db_config('cost_method_'.session('shop_code'));
        if ($method == 'belong') {
            $whereCost['belong_shop_code'] = $shop_code;
        }
        if((int)$data['consultation_type_id']){
            $where['consultation_type_id'] = (int)$data['consultation_type_id'];
        }

        $yxconfig = db_config('yx_config') ? db_config('yx_config') : "'1','5'";
		$wxconfig = db_config('wx_config') ? db_config('wx_config') : "'3','4'";
		$ddconfig = db_config('dd_config') ? db_config('dd_config') : "'2'";

        $sql = '';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'") as mkz,';
        
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid in ('.$yxconfig.')) as valid,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid in ('.$wxconfig.')) as unValid,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and is_valid in ('.$ddconfig.')) as dd,';
        $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and yjd_day is not null) as yy,';
        $sql .= 'sum(syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in (\'2\',\'3\',\'5\')) as jd,';
        $sql .= 'sum(order_start_time between "'.$start.'" and "'.$end.'" and is_success!=2) as ddl, ';
        $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1) as `order`,';
        $sql .= 'sum(order_day between "'.$start.'" and "'.$end.'" and is_success=1 and order_type=2) as `intoorder`';
        
        $info = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where('customer_channel','in',$channels)
            ->group('customer_channel')
            ->column($sql, 'customer_channel');
        $sql1 = db()->getLastSql();
        // echo db()->getLastSql();
        // die;
        //花费
        $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');
        $sql2 = db()->getLastSql();
        //实收
        $factMoney = 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])
            ->where('o.refund',1)->where('o.is_delete',2)
            ->group('c.customer_channel')
            ->column('sum(o.order_fact) as fact,s.channel_name,s.channel_class_name,s.channel_info_name,s.id', 'c.customer_channel');
        $sql3 = db()->getLastSql();
        //营收
        $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])
            ->where('o.refund',1)->where('o.is_delete',2)
            ->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');
        $sql4 = db()->getLastSql();
        $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]['ddl'] = $info[$v]['ddl'];
            $returnData[$k]['order'] = $info[$v]['order'];
			$returnData[$k]['intoorder'] = $info[$v]['intoorder'];
            $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]['intoorder'] ? sprintf('%.2f',$info[$v]['intoorder']/$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'] = $cost[$v] ? sprintf('%.2f',$cost[$v]) : '0';
            $returnData[$k]['mkzCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['mkz']) : '0';
            $returnData[$k]['validCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['valid']) : '0';
            $returnData[$k]['jdCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['jd']) : '0';
            $returnData[$k]['orderCost'] = $cost[$v] ? sprintf('%.2f',$cost[$v]/$info[$v]['order']) : '0';
            $returnData[$k]['orderAVG']  =  $info[$v]['order'] ? sprintf('%.2f',$totalMoney[$v]['total']/$info[$v]['order']) : '0';
            $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['ddl'] += $returnData[$k]['ddl'];
            $arr['order'] += $returnData[$k]['order'];
			$arr['intoorder'] += $returnData[$k]['intoorder'];
            $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['unValid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['ddRate'] = $arr['dd'] ? sprintf('%.2f',$arr['dd']/$arr['mkz']*100).'%' : '0%';
        $arr['mkzJdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['mkz']*100).'%' : '0%';
        $arr['validJdRate'] = $arr['jd'] ? sprintf('%.2f',$arr['jd']/$arr['valid']*100).'%' : '0%';
        $arr['jdOrderRate'] = $arr['intoorder'] ? sprintf('%.2f',$arr['intoorder']/$arr['jd']*100).'%' : '0%';
        $arr['mkzOrderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['mkz']*100).'%' : '0%';
        $arr['validOrderRate'] = $arr['order'] ? sprintf('%.2f',$arr['order']/$arr['valid']*100).'%' : '0%';
        $arr['mkzCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['mkz']) : '0';
        $arr['validCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['valid']) : '0';
        $arr['jdCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['jd']) : '0';
        $arr['orderCost'] = $arr['cost'] ? sprintf('%.2f',$arr['cost']/$arr['order']) : '0';
        $arr['orderAVG'] = $arr['totalMoney'] ? sprintf('%.2f',$arr['totalMoney']/$arr['order']) : '0';
        $arr['totalMoney'] = sprintf('%.2f',$arr['totalMoney']);
        $arr['factMoney'] = sprintf('%.2f',$arr['factMoney']);
        $arr['ROI'] = $arr['totalMoney'] ? sprintf('%.2f',$arr['totalMoney']/$arr['cost']) : '';

        $returnData[] = $arr;
        if (isMobile()) {
            // 定义空数组
            $arr = array();
            $i = 0;
            foreach ($returnData as $key => $value) {
                $arr[$i] = $value;
                $i++;
            }
            $return['rows'] = $arr;
            return json($return);
        }
        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $return['sql4'] = $sql4;
        $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'=>$add_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(session('shop_code'));
        $this->assign("channel", json_encode($channel));*/
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>session('brandclass_id')]);
        $this->assign("consumptionType", $consumptionType);

        if (isMobile()) {
            //来源渠道
            $c = controller('crm/Customer', 'lib')->getChannel($info['shop_code']);
            $channel_infos = array_column($c,'channel_info_name');
            //二级渠道
            $url = '59fd5e729e5a8';
            $res = sx_call($url, []);
            $channels = $res['data'];
            //过滤掉本店不存在的二级渠道
            foreach($channels as $k => $v){
                if(!in_array($v['channel_name'],$channel_infos)){
                    unset($channels[$k]);
                }
            }
            $channel_name = array_column($channels, 'channel_name');
            $channel_data = db('s_channel')->where("channel_info_name","in",$channel_name)->order("order_sort")->select();
            // $channel_datas = array_column($channel_data, 'channel_info_name');
            $this->assign('channel',$channel_data);

            $report = "report_wap";
        }else{
            //来源渠道
            $channel = getChannelJson(session('shop_code'));
            $this->assign("channel", json_encode($channel));

            $report = "report";
        }

        $info = db('s_report_form')->where('code', $code)->field('report_class_name,report_name')->find();
        $display = APP_PATH.'crm'.DS.'view'.DS.$report.DS.strtolower($info['report_class_name']).'.html';
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);
        $this->assign('title', session('shop_name').'-'.$info['report_name']);
        
        $mc = new \app\common\lib\mcInterface();
        $shopList = $mc->cacheData('5a8fd8296f3d3',['staff_id'=>session('staff_id')]);
        $this->assign('shop_list',$shopList);


        $this->assign('did', $info['id']);
        $this->assign('today',date('Y-m-d'));
        $this->assign('yestoday',date('Y-m-d',time()));

        return $this->fetch($display);
    }
}