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

class Xa_customer_cource_data extends Report {

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

    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'];
        $shop_code = $data['shop_code']?$data['shop_code']:session('shop_code');

        if(empty($shop_code)){
            return array('code'=>100,'msg'=>'请选择门店');
        }

        // 客户来源  
        $customerCources = [];
        $customerCourceIds = [];
        $allCustomerCource = controller("crm/Customer", "lib")->source();
        foreach ($allCustomerCource as $key => $value) {
            $customerCourceIds[] = $value['id'];
            $customerCources[] = $value['cus_name'];
        }
        // 基础条件
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $where['c.add_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']);
            $whereT['c.customer_channel'] = ['in', $channels];
        }

        $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.yjd_day between "'.$start.'" and "'.$end.'") as yy,';
        $sql .= 'sum(c.syjd_day between "'.$start.'" and "'.$end.'" and c.is_intostore in (\'2\',\'3\',\'5\')) as jd,';
        $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=2) as `intoorder`, ';
        $sql .= 'sum(c.order_day between "'.$start.'" and "'.$end.'" and c.is_success=1 and c.order_type=1) as `onlineorder`';
        $info = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where($whereT)
            ->where('customer_cource_id','in',$customerCourceIds)
            ->group('customer_cource')
            ->column($sql, 'customer_cource');
        $sql1 = db()->getLastSql();
        //实收
        $factMoney = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where('c.customer_cource_id','in',$customerCourceIds)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.customer_cource')
            ->column('sum(c.fact_money) as fact,c.customer_cource_id,c.customer_cource', 'c.customer_cource');
        $sql2 = db()->getLastSql();
        //营收
        $totalMoney = db('c_customerinfo')->alias('c')
            ->join('c_customer_order o','o.order_sn = c.order_number and o.customer_id = c.id','left')
            ->where($where)
            ->where('c.customer_cource_id','in',$customerCourceIds)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.customer_cource')
            ->column('sum(o.order_amount) as total,c.customer_cource_id,c.customer_cource','c.customer_cource');
        $sql3 = db()->getLastSql();
        $returnData = [];
        $arr = [];
        foreach($customerCources as $k=>$v){
            $returnData[$k]['customer_cource'] = $v;
            $returnData[$k]['mkz'] = $info[$v]['mkz'];
            $returnData[$k]['valid'] = $info[$v]['valid'];
            $returnData[$k]['yxRate'] = $info[$v]['valid'] ? sprintf('%.2f',$info[$v]['valid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['unValid'] = $info[$v]['unValid'];
            $returnData[$k]['wxRate'] = $info[$v]['unValid'] ? sprintf('%.2f',$info[$v]['unValid']/$info[$v]['mkz']*100).'%' : '0%';
            $returnData[$k]['dd'] = $info[$v]['dd'];
            $returnData[$k]['ddRate'] = $info[$v]['dd'] ? sprintf('%.2f',$info[$v]['dd']/$info[$v]['mkz']*100).'%' : '0%';
            $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]['onlineorder'] = $info[$v]['onlineorder'];
            // 进店订单 / 进店量 = 进店订单率
            $returnData[$k]['jdOrderRate'] = $info[$v]['intoorder'] ? sprintf('%.2f',$info[$v]['intoorder']/$info[$v]['jd']*100).'%' : '0%';
            // 线上订单 / （有效客资-进店客资）？ = 线上订单率
            // $returnData[$k]['zxOrderRate'] = $info[$v]['onlineorder'] ? sprintf('%.2f',$info[$v]['onlineorder']/($info[$v]['valid']-$info[$v]['jd'])*100).'%' : '0%';
            $returnData[$k]['totalMoney'] = floatval($totalMoney[$v]['total']);
            $returnData[$k]['factMoney'] = floatval($factMoney[$v]['fact']);
            //总计
            $arr['customer_cource'] = '总计';
            $arr['mkz'] += $returnData[$k]['mkz'];
            $arr['valid'] += $returnData[$k]['valid'];
            $arr['unValid'] += $returnData[$k]['unValid'];
            $arr['dd'] += $returnData[$k]['dd'];
            $arr['bh'] += $returnData[$k]['bh'];
            $arr['fbh'] += $returnData[$k]['fbh'];
            $arr['jd'] += $returnData[$k]['jd'];
            $arr['ddl'] += $returnData[$k]['ddl'];
            $arr['order'] += $returnData[$k]['order'];
            $arr['intoorder'] += $returnData[$k]['intoorder'];

            $arr['onlineorder'] += $returnData[$k]['onlineorder'];
            $arr['totalMoney'] += floatval($returnData[$k]['totalMoney']);
            $arr['factMoney'] += floatval($returnData[$k]['factMoney']);
        }
        $arr['yxRate'] = $arr['valid'] ? sprintf('%.2f',$arr['valid']/$arr['mkz']*100).'%' : '0%';
        $arr['wxRate'] = $arr['unValid'] ? sprintf('%.2f',$arr['unValid']/$arr['mkz']*100).'%' : '0%';
        $arr['ddRate'] = $arr['dd'] ? sprintf('%.2f',$arr['dd']/$arr['mkz']*100).'%' : '0%';
        $arr['jdOrderRate'] = $arr['intoorder'] ? sprintf('%.2f',$arr['intoorder']/$arr['jd']*100).'%' : '0%';
        // $arr[$k]['zxOrderRate'] = $arr['onlineorder'] ? sprintf('%.2f',$arr['onlineorder']/($arr['valid']-$arr['jd'])*100).'%' : '0%';
        $returnData[] = $arr;
        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channels);
        $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();
        //来源渠道
        $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);

        // 获取方式
        $accessModel = controller("crm/Customer", "lib")->accessModel();
        $this->assign("accessModel", $accessModel);
        
        $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']);

        $this->assign('did', $info['id']);
        $this->assign('today',date('Y-m-d'));
        $this->assign('yestoday',date('Y-m-d',time()));
        $mc = new \app\common\lib\mcInterface();
        $shopList = $mc->cacheData('5a8fd8296f3d3',['staff_id'=>session('staff_id')]);
        $this->assign('shop_list',$shopList);
        return $this->fetch($display);
    }
}