<?php
/**
 * 报表实现类 洛阳兰高定渠道数据统计
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong/wangzhenya 2018-05-29 $
 * 备注：网付（网付500算一单）
 * 毛客资转化率=进店+网付（500元+）/毛客资
 * 订单转化率=进店订单（满100+）+网付（500元+）+/毛客资
 * 成交率=进店订单/进店单量
 * 均价=实收金额/订单单量
 * 进店=客资转化+CPM系统转订单转流失为准   (网付500以上  线下预约了  转流失  转订单 这4四种都是进店)
 * 有效  待定  无效标记来算
 * 订单数是按开单来算
 * 实收是按一销来算
 */
namespace app\crm\lib\report;
use app\crm\lib\Report;
use think\Controller;
use think\image\Exception;

class Lgd_channel_data extends Report {

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

    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();
        // 时间区域
        if (!$data['start'] || !$data['end']) {
            $return = ['code' => 200, 'msg' => '请选择时间区间', 'count' => 0, 'data' => '',];
            return json($return);
        }
        $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'=>'报表配置有误');
        }
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $where['is_status'] = 1;
        $data['shop_code'] = $data['shop_code'] ? $data['shop_code'] : $shop_code;
        $where['c_from'] = 1;

        if($data['consultation_type_id']){
            $consultation_type_id = intval($data['consultation_type_id']);
        }
        // 地域id，拼接where条件
        if ($data['province_id']) {
            $where['province_id'] = (int)$data['province_id'];
            $whereC['province_id'] = (int)$data['province_id'];
            $whereD['c.province_id'] = (int)$data['province_id'];
        }
        if ($data['city_id']) {
            $where['city_id'] = (int)$data['city_id'];
            $whereC['city_id'] = (int)$data['city_id'];
            $whereD['c.city_id'] = (int)$data['city_id'];
        }

        if ($data['accessModel_id']) {//获取方式
            $where['access_model_id'] = (int)$data['accessModel_id'];
            $whereD['c.access_model_id'] = (int)$data['accessModel_id'];
        }
        if ($data['channel_name']) {//渠道
            $channel = db('s_channel')->where('shop_code',$shop_code)->where('channel_name','in',trim($data['channel_name']))->select();
        }else{
            $channel = db('s_channel')->where('shop_code',$shop_code)->select();
        }
        $channel_name = array_column($channel,'channel_name');

        $method = 'customer_channel';
        $code = 'add_shop_code';
        $sql = '';
        $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 order_start_time between '$start' and '$end') as `order`,";
            $sql .= "sum(order_type=1 and is_success=1 and order_day between '$start' and '$end') as wf,";//网付订单
        }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(order_start_time between '$start' and '$end') as `order`,";
            $sql .= "sum(order_type=1 and is_success=1 and order_day between '$start' and '$end') as wf,";//网付订单
        }
        $sql .= "sum(is_valid=2 and yx_day between '$start' and '$end') as dd,";
        $sql .= "sum(is_valid=3 and yx_day between '$start' and '$end') as wx,";
        $sql .= "sum(erp_loss=2 and erp_loss_time between '$start' and '$end') as loss";
        // 录入客资量
        $info= db('c_customerinfo')
            ->where($where)
            ->where($code, $data['shop_code'])
            ->where('customer_channel', 'in',$channel_name)
            ->group($method)
            ->column($sql,$method);
//        echo db()->getLastSql();die;
        //营收
        $detail = db('c_customerinfo')->alias('c')->join('c_order_detail d','d.order_sn=c.order_number')
            ->where($where)
            ->where('c.'.$code, $data['shop_code'])
            ->where('c.customer_channel', 'in',$channel_name)
            ->where('d.pay_type',1)
            ->where('d.pay_time', 'between time', [$start, $end])
            ->group('c.'.$method)
            ->column('sum(d.order_fact) as fact','c.'.$method);
        //套系
        $whereTx['c.c_from'] = 1;
        $whereTx['c.is_status'] = 1;
        $whereTx['c.is_status'] = 1;

        $total = db('c_customerinfo')->alias('c')->join('c_customer_order o','c.order_number=o.order_sn')
            ->where($whereTx)
            ->where('c.'.$code, $data['shop_code'])
            ->where('c.customer_channel', 'in',$channel_name)
            ->where('o.order_valid', 2)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.'.$method)
            ->column('sum(o.order_amount) as total','c.'.$method);
        $returnData = [];
        $arr = [];
        $i = 1;
        $arr['id'] = '&nbsp;';
        foreach ($channel as $key => $value) {
            $returnData[$key]['id'] = $i;
            $returnData[$key]['channel_name'] = $value['channel_name'];
            $returnData[$key]['lrCustomer'] = $info[$value['channel_name']]['mkz'];
            $returnData[$key]['invCustomer'] = $info[$value['channel_name']]['valid'];
            // 有效率（ 有效获取 / 毛客资 ）
            $returnData[$key]['invRate'] = (number_format($returnData[$key]['invCustomer'] / $returnData[$key]['lrCustomer']*100, 2)) . '%';
            $returnData[$key]['dd'] = $info[$value['channel_name']]['dd'];
            $returnData[$key]['wx'] = $info[$value['channel_name']]['wx'];
            $returnData[$key]['wf'] = $info[$value['channel_name']]['wf'];
            $returnData[$key]['intoNum'] = $info[$value['channel_name']]['jd'];
            $returnData[$key]['intoRate'] = (number_format($returnData[$key]['intoNum'] / $returnData[$key]['invCustomer']*100, 2)) . '%';
            $returnData[$key]['orderNum'] = $info[$value['channel_name']]['order'];
            $returnData[$key]['loss'] = $info[$value['channel_name']]['loss'];
            // 流失率（ 流失 / 实际进店 ）
            $returnData[$key]['lossRate'] = (number_format($returnData[$key]['loss'] / $returnData[$key]['intoNum']*100, 2)) . '%';
            // 成交率（ 有效新单 / 实际进店 ）
            $returnData[$key]['orderRate'] = (number_format($returnData[$key]['orderNum'] / $returnData[$key]['intoNum']*100, 2)) . '%';
            // 毛客资转化率（ 进店 / 毛客资 ）
            $returnData[$key]['mkzJdRate'] = (number_format($returnData[$key]['intoNum'] / $returnData[$key]['lrCustomer']*100, 2)) . '%';
            // 订单转化率（ 有效新单 / 毛客资 ）
            $returnData[$key]['mkzOrderRate'] = (number_format($returnData[$key]['orderNum'] / $returnData[$key]['lrCustomer']*100, 2)) . '%';

            $returnData[$key]['orderAmount'] = sprintf('%.2f',$total[$value['channel_name']]);
            $returnData[$key]['factMoney'] = sprintf('%.2f',$detail[$value['channel_name']]);
            $returnData[$key]['orderAmountAvg'] = sprintf('%.2f',$detail[$value['channel_name']]/$info[$value['channel_name']]['order']);

            $arr['channel_name'] = '总计';
            $arr['lrCustomer'] += $info[$value['channel_name']]['mkz'];
            $arr['invCustomer'] += $info[$value['channel_name']]['valid'];
            $arr['invRate'] = '';
            $arr['dd'] += $info[$value['channel_name']]['dd'];
            $arr['wx'] += $info[$value['channel_name']]['wx'];
            $arr['wf'] += $info[$value['channel_name']]['wf'];
            $arr['intoNum'] += $info[$value['channel_name']]['jd'];
            $arr['loss'] += $info[$value['channel_name']]['loss'];
            $arr['intoRate'] = '';
            $arr['orderNum'] += $info[$value['channel_name']]['order'];
            $arr['orderRate'] = '';
            $arr['mkzOrderRate'] = '';
            $arr['orderAmount'] += $total[$value['channel_name']];
            $arr['factMoney'] += $detail[$value['channel_name']];
            $arr['orderAmountAvg'] = '';
            $i++;
        }
        $arr['invRate'] = sprintf('%.2f',$arr['invCustomer']/$arr['lrCustomer']*100).'%';
        $arr['intoRate'] = sprintf('%.2f',$arr['intoNum']/$arr['invCustomer']*100).'%';
        $arr['lossRate'] = sprintf('%.2f',$arr['loss']/$arr['intoNum']*100).'%';
        $arr['orderRate'] = sprintf('%.2f',$arr['orderNum']/$arr['intoNum']*100).'%';
        $arr['mkzJdRate'] = sprintf('%.2f',$arr['intoNum']/$arr['lrCustomer']*100).'%';
        $arr['mkzOrderRate'] = sprintf('%.2f',$arr['orderNum']/$arr['lrCustomer']*100).'%';
        $arr['orderAmountAvg'] = sprintf('%.2f',$arr['factMoney']/$arr['orderNum']);
        array_push($returnData,$arr);

        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($returnData);
        $return['data'] = $returnData;
        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();
        $shop= controller('crm/Customer','lib')->get_shop(['shop_code' =>$info['shop_code']]);
        $this->assign('shop', $shop);
        //获取方式
        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' =>$info['shop_code']));
        $this->assign("accessModel", $accessModel);

        //客资地域
        // crm省    列表
        $data['type'] = 1;
        $data['shop_code'] = $info['shop_code'];
        $province = controller("Customer", "lib")->address($data);
        $this->assign('province', $province);
        //消费类型
        $consumptionType = controller("Customer", "lib")->consumptionType(['brandclass_id'=>$info['brandclass_id']]);
        $this->assign("consumptionType", $consumptionType);
        $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');
        $this->assign('title', $shop[0]['shop_name'].'-'.$title);

        $channels = getChannelJson($info['shop_code']);
        $this->assign('channel', json_encode($channels));
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}
