<?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_access_model_data extends Report {

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

    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'=>'请选择门店。');
        }

        // 获取方式  
        $accessModels = [];
        $accessModelIds = [];
        $allAccessModel = controller("crm/Customer", "lib")->accessModel();
        foreach ($allAccessModel as $key => $value) {
            $accessModelIds[] = $value['id'];
            $accessModels[] = $value['accessmodel'];
        }
        // 基础条件
        $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['dj_staff']){
            $where['c.dj_staff_id'] = ['in',$data['dj_staff']];
        }
        // 渠道名称
        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.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('access_model_id','in',$accessModelIds)
            ->group('access_model')
            ->column($sql, 'access_model');
        $sql1 = db()->getLastSql();
        //实收
        $factMoney = db('c_customerinfo')->alias('c')
            ->where($where)
            ->where('c.access_model_id','in',$accessModelIds)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.access_model')
            ->column('sum(c.fact_money) as fact,c.access_model_id,c.access_model', 'c.access_model');
        $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.access_model_id','in',$accessModelIds)
            ->where('c.order_day', 'between time', [$start, $end])
            ->group('c.access_model')
            ->column('sum(o.order_amount) as total,c.access_model_id,c.access_model','c.access_model');
        $sql3 = db()->getLastSql();
        $returnData = [];
        $arr = [];
        foreach($accessModels as $k=>$v){
            $returnData[$k]['access_model'] = $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]['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]['factMoney'] = $factMoney[$v]['fact'] ? sprintf('%.2f',$factMoney[$v]['fact']) : 0;
			$returnData[$k]['totalMoney'] = $totalMoney[$v]['total'] ? sprintf('%.2f',$totalMoney[$v]['total']) : 0;
           
            //总计
            $arr['access_model'] = '总计';
            $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'] += $returnData[$k]['factMoney'];
			$arr['factMoney'] += $returnData[$k]['totalMoney'];
        }
        $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%';

        $returnData[] = $arr;
        $return['sql1'] = $sql1;
        $return['sql2'] = $sql2;
        $return['sql3'] = $sql3;
        $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'=>$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'));
        $shop_code = session('shop_code');
        // $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($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);

        $mc = new \app\common\lib\mcInterface();
        // 部门 
        $departmentList = $mc->getDepartmentByShopcode($shop_code);
        foreach ($departmentList as $key => $value) {
            if ($value['department_name']==session('department_name')) {
                $departmentList[$key]['selected']=1;
                $departmentId = $value['id'];
            }
        }
        $this->assign("departmentList",$departmentList);
        $staffParam['department_id'] = $departmentId;
        $staffParam['get_main'] = 2;
        // 登记人
        $djStaffList = $mc->getStaffByDepartp($staffParam);
        $this->assign("djStaffList",$djStaffList);

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

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