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

class Xa_wx_group_data extends Report {

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

    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'=>'请选择门店');
        }
        // 基础条件
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.shop_code'] = $shop_code;
        // 消费类型
        if((int)$data['consultation_type_id']){
            $whereT['c.consultation_type_id'] = (int)$data['consultation_type_id'];
        }
        // 渠道
        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');
            // $channels = db('c_customerinfo')
            //     // ->whereTime('dj_day', 'month')
            //     ->where('shop_code',$shop_code)
            //     ->group('customer_channel')->field('customer_channel')
            //     ->select();
            //$channels = array_column($channels,'customer_channel');
        }
        // 所有的组
        $allGroups = db('c_staff_group')->where('shop_code',$shop_code)->select();
        $groups = array_column($allGroups,'group_name');

        $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(c.dj_day between "'.$start.'" and "'.$end.'") as mkz,';//毛客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$yxconfig.')) as valid,';//有效客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$wxconfig.')) as unValid,';//无效客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.is_valid in ('.$ddconfig.')) as dd,';//待定客资
        $sql .= 'sum(c.dj_day between "'.$start.'" and "'.$end.'" and c.wechat_status=2) as jiaWx,';//已加微信
        // $sql .= 'sum(dj_day between "'.$start.'" and "'.$end.'" and yjd_day is not null) as yy,';
        $sql .= 'sum(c.syjd_day between "'.$start.'" and "'.$end.'" and c.is_intostore in (\'2\',\'3\',\'5\')) as jd,';//实际进店
        $sql .= 'sum(c.syjd_day between "'.$start.'" and "'.$end.'" and c.is_intostore in ("2","3","5") and DATE_FORMAT(c.syjd_day,"%w") IN (0,6) ) as wendjd,';//周末进店量
        // 成交量
        $sql .= 'sum(c.order_start_time between "'.$start.'" and "'.$end.'" and c.is_success!=2) as ddl, ';
        $sql .= 'sum(c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1) as `order`, ';
        // 线上成交量
        $sql .= 'sum(c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1 and c.order_type=1) as `onlineorder`, ';
        // 当日订单量
        $sql .= 'sum(DATE_FORMAT(c.dj_day, "%Y%m%d")=DATE_FORMAT(c.order_day,"%Y%m%d") and c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1 ) as todayOrder, ';
        // 当日全款量
        $sql .= 'sum(DATE_FORMAT(o.bargainoverdate, "%Y%m%d")=DATE_FORMAT(c.order_start_time,"%Y%m%d") and c.order_start_time between "'.$start.'" and "'.$end.'" and c.is_success=1 ) as oneTimeMoneyOrder, ';
//        历史订单量（当月之前的客资归属于历史）
        $sql .= 'sum((DATE_FORMAT(c.dj_day, "%Y%m")!=DATE_FORMAT("'.$start.'","%Y%m")) and (DATE_FORMAT(c.order_day, "%Y%m")=DATE_FORMAT("'.$start.'","%Y%m")) and c.is_success=1 ) as `historyOrder`';

        $info = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->join('c_customer_order o','c.order_number=o.order_sn','left')
            ->where($where)->where($whereT)
            ->where('c.customer_channel','in',$channels)
            ->where('f.sales_group_name','in',$groups)
            ->group('f.sales_group_name')
            ->column($sql, 'f.sales_group_name');
        $sql1 = db()->getLastSql();
//        echo $sql1;die;

        $sql = '';
        //当月客资总量
        $sql .= 'sum(DATE_FORMAT(c.dj_day, "%Y%m")=DATE_FORMAT("'.$start.'","%Y%m")) as `thisMonthkz`,c.id';
        $info2 = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->join('c_customer_order o','c.order_number=o.order_sn','left')
            ->where($where)->where($whereT)
            ->where('c.customer_channel','in',$channels)
            ->where('f.sales_group_name','in',$groups)
            ->group('f.sales_group_name')
            ->column($sql, 'f.sales_group_name');
        $sql8 = db('c_customerinfo')->getLastSql();
//        echo $sql6;die;

        $sql = '';
        //        当月订单量（当月客资当月定单）
        $sql .= 'sum((DATE_FORMAT(c.dj_day, "%Y%m")=DATE_FORMAT("'.$start.'","%Y%m")) and (DATE_FORMAT(c.order_day, "%Y%m")=DATE_FORMAT("'.$start.'","%Y%m")) and c.is_success=1 ) as `thisMonthOrder`,c.id';
        $info3 = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->join('c_customer_order o','c.order_number=o.order_sn','left')
            ->where($where)->where($whereT)
            ->where('c.customer_channel','in',$channels)
            ->where('f.sales_group_name','in',$groups)
            ->group('f.sales_group_name')
            ->column($sql, 'f.sales_group_name');
        $sql7 = db('c_customerinfo')->getLastSql();
//        echo $sql7;die;

        // 组实收
        $factMoney = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->join('c_customer_order o','o.order_sn = c.order_number and o.customer_id = c.id','left')
            ->where($where)->where($whereT)
            ->where('c.customer_channel','in',$channels)
            ->where('f.sales_group_name','in',$groups)
            ->where('c.order_day', 'between time', [$start, $end])
            ->where('o.refund',1)->where('o.is_delete',2)
            ->group('f.sales_group_name')
            ->column('sum(o.order_fact) as fact,f.sales_group_name', 'f.sales_group_name');
        $sql2 = db()->getLastSql();
        // 组营收
        $totalMoney = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->join('c_customer_order o','o.order_sn = c.order_number and o.customer_id = c.id','left')
            ->where($where)->where($whereT)
            ->where('c.customer_channel','in',$channels)
            ->where('f.sales_group_name','in',$groups)
            ->where('c.order_day', 'between time', [$start, $end])
            ->where('o.refund',1)->where('o.is_delete',2)
            ->group('f.sales_group_name')
            ->column('sum(o.order_amount) as total,f.sales_group_name', 'f.sales_group_name');
        $sql3 = db()->getLastSql();
        // 计算组客资花费
        // $whereCost['shop_code'] = $add_shop_code;
        // 花费录入维度
        $method = db_config('cost_method_'.session('shop_code'));
        if ($method == 'belong') {
            $whereCost['belong_shop_code'] = $shop_code;
        }
        // $whereCost['belong_shop_code'] = $shop_code;
        // $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        // $channels = array_column($channels,'channel_name');
        // var_dump($channels);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');
        $sql4 = db()->getLastSql();
        // var_dump($cost);die;
        // 渠道客资
        $cusNum = db('c_customerinfo')->alias('c')
            ->where('c.dj_day', 'between time', [$start, $end])
            ->where($where)
            ->where('c.customer_channel','in',$channels)
            ->group('c.customer_channel')
            ->column('count(c.id) as num','c.customer_channel');
        $sql5 = db()->getLastSql();

        $allChannelInfo = [];
        foreach ($cost as $key => $value) {
            $allChannelInfo[$key]['channel_name'] = $key;
            $allChannelInfo[$key]['cost'] = $value;
            $allChannelInfo[$key]['num'] = $cusNum[$key];
            $allChannelInfo[$key]['cb']  = $value / $cusNum[$key];
        }

        // 组渠道客资量
        $groupCusNum = db('c_customerinfo')->alias('c')
            ->join('c_customer_from f', 'c.id=f.cid','left')
            ->where($where)->where('f.sales_group_name','not null')
            ->where('c.dj_day', 'between time', [$start, $end])
            ->where('c.customer_channel','in',$channels)
            ->group('f.sales_group_name,c.customer_channel')
            ->field('f.sales_group_name,c.customer_channel,count(c.id) as num')
            ->select();
        $sql6 = db()->getLastSql();
        // 组客资花费
        $groupCost = [];
        foreach ($groupCusNum as $key => $value) {
            $groupCost[$value['sales_group_name']] += $allChannelInfo[$value['customer_channel']]['cb']*$value['num'];
        }

        $returnData = [];
        $arr = [];
        foreach($groups as $k=>$v){
            $returnData[$k]['sales_group_name'] = $v;
            //当月客资转化率 当月订单量（当月客资当月定单）÷当月总客资量
            $returnData[$k]['thisMonthkzConversionRate'] = $info3[$v]['thisMonthOrder'] ? sprintf('%.2f',$info3[$v]['thisMonthOrder']/$info2[$v]['thisMonthkz']*100).'%' : '0%';
            //历史客资转化率=历史订单量（当月之前的客资归属于历史）÷当月总客资量
            $returnData[$k]['historyMonthkzConversionRate'] = $info[$v]['historyOrder'] ? sprintf('%.2f',$info[$v]['historyOrder']/$info2[$v]['thisMonthkz']*100).'%' : '0%';
            //毛客资成交率 =历史客资转化率+当月客资转化率
            $returnData[$k]['mkzDealRate'] = $returnData[$k]['historyMonthkzConversionRate'] ? sprintf('%.2f',($returnData[$k]['historyMonthkzConversionRate']+ $returnData[$k]['thisMonthkzConversionRate'])*1).'%' : '0%';

            $returnData[$k]['thisMonthOrder'] = $info3[$v]['thisMonthOrder'];
            $returnData[$k]['thisMonthkz'] = $info2[$v]['thisMonthkz'];
            $returnData[$k]['historyOrder'] = $info[$v]['historyOrder'];

            $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]['yjwechat'] = $info[$v]['jiaWx'];
            $returnData[$k]['wechatRate']= $info[$v]['jiaWx'] ? sprintf('%.2f',$info[$v]['jiaWx']/$info[$v]['mkz']*100).'%' : '0%';
            // $returnData[$k]['yy'] = $info[$v]['yy'];
            $returnData[$k]['jd'] = $info[$v]['jd'];
            $returnData[$k]['wendjd'] = $info[$v]['wendjd'];
            $returnData[$k]['nwendjd'] = $info[$v]['jd'] - $info[$v]['wendjd'];
            $returnData[$k]['ddl'] = $info[$v]['ddl'];
            $returnData[$k]['order'] = $info[$v]['order'];
            $returnData[$k]['todayOrder'] = $info[$v]['todayOrder'];
            $returnData[$k]['dayOrderRate'] = $info[$v]['todayOrder'] ? sprintf('%.2f',$info[$v]['todayOrder']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['onlineorder'] = $info[$v]['onlineorder'];
            $returnData[$k]['intoorder'] = $returnData[$k]['order'] - $returnData[$k]['onlineorder'];
            $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]['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',$groupCost[$v]);
            $returnData[$k]['mkzCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['mkz']) : '0';
            $returnData[$k]['validCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['valid']) : '0';
            $returnData[$k]['jdCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['jd']) : '0';
            $returnData[$k]['orderCost'] = $groupCost[$v] ? sprintf('%.2f',$groupCost[$v]/$info[$v]['order']) : '0';
            $returnData[$k]['orderAVG'] =  $info[$v]['order'] ? sprintf('%.2f',$totalMoney[$v]/$info[$v]['order']) : '0';
            $returnData[$k]['totalMoney'] =  sprintf('%.2f',$totalMoney[$v]);
            $returnData[$k]['factMoney'] =  sprintf('%.2f',$factMoney[$v]);

            $returnData[$k]['oneTimeMoneyOrder'] = $info[$v]['oneTimeMoneyOrder'];
            $returnData[$k]['oneTimeMoneyOrderRate'] = $info[$v]['oneTimeMoneyOrder'] ? sprintf('%.2f',$info[$v]['oneTimeMoneyOrder']/$info[$v]['order']*100).'%' : '0%';

            $returnData[$k]['ROI'] = $returnData[$k]['totalMoney'] ? sprintf('%.2f',$returnData[$k]['totalMoney']/$returnData[$k]['cost']) : '';

            //总计
            $arr['sales_group_name'] = '总计';
            $arr['mkz'] += $returnData[$k]['mkz'];
            $arr['valid'] += $returnData[$k]['valid'];
            $arr['unValid'] += $returnData[$k]['unValid'];
            $arr['yjwechat'] += $returnData[$k]['yjwechat'];
            $arr['dd'] += $returnData[$k]['dd'];
            // $arr['yy'] += $returnData[$k]['yy'];
            $arr['jd'] += $returnData[$k]['jd'];
            $arr['wendjd'] += $returnData[$k]['wendjd'];
            $arr['nwendjd'] += $returnData[$k]['nwendjd'];
            $arr['ddl'] += $returnData[$k]['ddl'];
            $arr['order'] += $returnData[$k]['order'];
            $arr['todayOrder'] += $returnData[$k]['todayOrder'];
            $arr['onlineorder'] += $returnData[$k]['onlineorder'];
            $arr['intoorder'] += $returnData[$k]['intoorder'];
            $arr['cost'] += $returnData[$k]['cost'];
            $arr['totalMoney'] += floatval($returnData[$k]['totalMoney']);
            $arr['factMoney'] += floatval($returnData[$k]['factMoney']);
            $arr['oneTimeMoneyOrder'] += $returnData[$k]['oneTimeMoneyOrder'];
            $arr['thisMonthOrder'] += $returnData[$k]['thisMonthOrder'];
            $arr['thisMonthkz'] += $returnData[$k]['thisMonthkz'];
            $arr['historyOrder'] += $returnData[$k]['historyOrder'];
            $arr['historyMonthkzConversionRate'] += $returnData[$k]['historyMonthkzConversionRate'];
        }
        $arr['wechatRate']= $arr['yjwechat'] ? sprintf('%.2f',$arr['yjwechat']/$arr['mkz']*100).'%' : '0%';
        $arr['dayOrderRate'] = $arr['todayOrder'] ? sprintf('%.2f',$arr['todayOrder']/$arr['mkz']*100).'%' : '0%';
        $arr['thisMonthkzConversionRate'] = $arr['thisMonthOrder'] ? sprintf('%.2f',$arr['thisMonthOrder']/$arr['thisMonthkz']*100).'%' : '0%';
        $arr['historyMonthkzConversionRate'] = $arr['historyOrder'] ? sprintf('%.2f',$arr['historyOrder']/$arr['thisMonthkz']*100).'%' : '0%';
        $arr['mkzDealRate'] = $arr['historyMonthkzConversionRate'] ? sprintf('%.2f',($arr['historyMonthkzConversionRate']+ $arr['thisMonthkzConversionRate'])*1).'%' : '0%';
        $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['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']) : '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['oneTimeMoneyOrderRate'] = $arr['oneTimeMoneyOrder'] ? sprintf('%.2f',$arr['oneTimeMoneyOrder']/$arr['order']*100).'%' : '0%';
        $arr['ROI'] = $arr['totalMoney'] ? sprintf('%.2f',$arr['totalMoney']/$arr['cost']) : '';

        $returnData[] = $arr;
        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $return['sql4'] = $sql4;
        $return['sql5'] = $sql5;
        $return['sql6'] = $sql6;
        $return['sql7'] = $sql7;
        $return['sql8'] = $sql8;

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $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(session('shop_code'));
        $this->assign("channel", json_encode($channel));
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>session('brandclass_id')]);
        $this->assign("consumptionType", $consumptionType);

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