<?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;
use think\image\Exception;

class Cshy_ds_channel_data extends Report {

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

    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);
        // 权限
        $auth = check_right('menu1521352658');
        if (!$auth) {
            $return = ['code' => 0, 'msg' => '', 'count' => 0, 'data' => ''];
            return json($return);
        }
        $data = input();

        $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();
        $shopCode = $det['shop_code'];
        if(empty($shopCode)){
            return array('code'=>100,'msg'=>'报表配置有误');
        }

        if($data['channel_name']){
            $channel = db('s_channel')->where('shop_code','in',$shopCode)->where('channel_name','in',explode(',',trim($data['channel_name'])))->order('order_sort')->select();
        }else{
            //来源渠道
            $channel = db('s_channel')->where('shop_code','in',$shopCode)->order('order_sort')->select();
        }


        // 时间区域
        $start = date('Y-m-d', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        if($data['consultation_type_id']){
            $consultation_type_id = intval($data['consultation_type_id']);
        }
        if($data['access_model_id']){
            $where['c.access_model_id'] = intval($data['access_model_id']);
        }
        if($data['province_id']){
            $where['c.province_id'] = intval($data['province_id']);
            $whereCost['province_id'] = intval($data['province_id']);
        }
        if($data['city_id']){
            $where['c.city_id'] = intval($data['city_id']);
            $whereCost['city_id'] = intval($data['city_id']);
        }
        $where['c.add_shop_code'] = $shopCode;
        //花费
        $cost = db('s_channel_cost')
            ->where($whereCost)
            ->where('channel_name','in',array_column($channel,'channel_name'))
            ->where('cost_date','between',[$start,$end])
            ->where('shop_code',$shopCode)
            ->group('channel_name')
            ->column('sum(cost)','channel_name');
        $sql = '';
        $sql .= "sum(dj_day between '$start' and '$end') as mkz,";
        if($consultation_type_id){
            $sql .= "sum(is_valid<>3 and consultation_type_id=".$consultation_type_id." and dj_day between '$start' and '$end') as valid,";//有效
            $sql .= "sum(is_intostore in('2','3','5') and  consultation_type_id=".$consultation_type_id." and syjd_day between '$start' and '$end') as jd,";//进店
            $sql .= "sum(is_success=1 and consultation_type_id=".$consultation_type_id." and order_day between '$start' and '$end') as `order`";//成交
        }else{
            $sql .= "sum(is_valid<>3 and dj_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=1 and order_day between '$start' and '$end') as `order`";//成交
        }

            $info= db('c_customerinfo c')->join('c_customer_from f','c.id=f.cid','left')
                ->where($where)
                ->where('customer_channel','in',array_column($channel,'channel_name'))
                ->group('c.customer_channel')
                ->column($sql,'c.customer_channel');

        //套系
        $amount = db('c_customerinfo')->alias('c')->join('s_channel s', 's.channel_name=c.customer_channel')->join('c_customer_order o','o.order_sn=c.order_number')
            ->where($where)
            ->where('c.is_success', 1)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.customer_channel')
            ->column('sum(o.order_amount) as totalpay_money', 'c.customer_channel');
        $total = [];//最后总计
        $returnData = [];
        $i = 1;
        foreach($channel as $k=>$v){
                $arr = [];
                $arr['id'] = $i;
                $arr['channel_name'] = $v['channel_name'];
                $arr['cost'] = $cost[$v['channel_name']] ? sprintf('%.2f',$cost[$v['channel_name']]) : '';
                $arr['mkz'] = $info[$v['channel_name']]['mkz'];
                $arr['valid'] = $info[$v['channel_name']]['valid'];
                $arr['validRate'] = $info[$v['channel_name']]['valid']?sprintf('%.2f',$info[$v['channel_name']]['valid']/$info[$v['channel_name']]['mkz']*100).'%':'';
                $arr['validCost'] = $cost[$v['channel_name']]?sprintf('%.2f',$cost[$v['channel_name']]/$info[$v['channel_name']]['valid']):'';
                $arr['jd'] = $info[$v['channel_name']]['jd'];
                $arr['jdRate'] = $info[$v['channel_name']]['jd']?sprintf('%.2f',$info[$v['channel_name']]['jd']/$info[$v['channel_name']]['valid']*100).'%':'';
                $arr['order'] = $info[$v['channel_name']]['order'];
                $arr['validOrderRate'] = $info[$v['channel_name']]['order']?sprintf('%.2f',$info[$v['channel_name']]['order']/($arr['valid'])*100).'%': '';
                $arr['orderCost'] = $cost[$v['channel_name']]?sprintf('%.2f',$cost[$v['channel_name']]/($arr['order'])): '';
                $arr['orderAmount'] = $amount[$v['channel_name']] ? sprintf('%.2f',$amount[$v['channel_name']]) : '';
                $arr['avg'] = $amount[$v['channel_name']] ? sprintf('%.2f',$amount[$v['channel_name']]/$info[$v['channel_name']]['order']) : '';
                if(empty($cost[$v['channel_name']]) && empty($info[$v['channel_name']]['mkz']) && empty($info[$v['channel_name']]['valid']) && empty($info[$v['channel_name']]['jd']) && empty($info[$v['channel_name']]['order'])){
                    unset($arr);
                }else{
                    $returnData[] = $arr;
                    //最后总计
                    $total['channel_name'] = '总计';
                    $total['cost'] += $cost[$v['channel_name']];
                    $total['mkz'] += $info[$v['channel_name']]['mkz'];
                    $total['valid'] += $info[$v['channel_name']]['valid'];
                    $total['validRate'] = '';
                    $total['validCost'] = '';
                    $total['jd'] += $info[$v['channel_name']]['jd'];
                    $total['jdRate'] = '';
                    $total['order'] += $info[$v['channel_name']]['order'];
                    $total['validOrderRate'] = '';
                    $total['orderCost'] = '';
                    $total['orderAmount'] += $arr['orderAmount'];
                    $total['avg'] = '';
                    $i++;
                }
        }
        $total['validRate'] = $total['valid']?sprintf('%.2f',$total['valid']/($total['mkz'])*100).'%': '';
        $total['validCost'] = $total['cost']?sprintf('%.2f',$total['cost']/($total['valid'])): '';
        $total['jdRate'] = $total['jd']?sprintf('%.2f',$total['jd']/($total['valid'])*100).'%': '';
        $total['validOrderRate'] = $total['order']?sprintf('%.2f',$total['order']/($total['valid'])*100).'%': '';
        $total['orderCost'] = $total['cost']?sprintf('%.2f',$total['cost']/($total['order'])): '';
        $total['orderAmount'] = $total['orderAmount']?sprintf('%.2f',$total['orderAmount']): '';
        $total['avg'] = $total['orderAmount']?sprintf('%.2f',$total['orderAmount']/($total['order'])): '';
        $returnData[] = $total;

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

        $channels = getChannelJson($info['shop_code']);
        $this->assign('channel', json_encode($channels));
        //消费类型
        $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);
        $this->assign('province', $province);
        //获取方式
        $accessModel = controller("Customer", "lib")->accessModel(array('shop_code' =>$info['shop_code']));
        $this->assign("accessModel", $accessModel);
        $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);
        $this->assign('did', $info['id']);
        return $this->fetch($display);
    }

}