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

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

    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'=>'报表配置有误');
        }
        if($data['channel_id']){
            $channels = explode(',',$data['channel_id']);
        }else{
            // 来源渠道
            $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
            $channels = array_column($channels,'channel_name');
        }
        // 省
        $province = db('s_shop_address')->where('type',1)->where('shop_code',session('shop_code'))->select();
        $provinces= array_column($province,'name');
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;
        if((int)$data['consultation_type_id']){
            $whereT['consultation_type_id'] = (int)$data['consultation_type_id'];
        }

        switch ($data['data_type']) {
        	case 'mkz':
        		$sql = 'dj_day between "'.$start.'" and "'.$end.'"';
        		break;
        	case 'valid':
        		$yxconfig = db_config('yx_config') ? db_config('yx_config') : "'1','5'";
        		$sql = 'dj_day between "'.$start.'" and "'.$end.'" and is_valid in ('.$yxconfig.')';
        		break;
        	case 'unValid':
        		$wxconfig = db_config('wx_config') ? db_config('wx_config') : "'3','4'";
        		$sql = 'dj_day between "'.$start.'" and "'.$end.'" and is_valid in ('.$wxconfig.')';
        		break;
        	case 'dd':
        		$ddconfig = db_config('dd_config') ? db_config('dd_config') : "'2'";
        		$sql = 'dj_day between "'.$start.'" and "'.$end.'" and is_valid in ('.$ddconfig.')';
        		break;
        	case 'yy':
        		$sql = 'yjd_day between "'.$start.'" and "'.$end.'"';
        		break;
        	case 'jd':
        		$sql = 'syjd_day between "'.$start.'" and "'.$end.'" and is_intostore in (\'2\',\'3\',\'5\')';
        		break;
        	case 'order':
        		$sql = 'order_day between "'.$start.'" and "'.$end.'" and is_success=1';
        		break;
        	case 'validRate':
        		# code...
        		break;
        	case 'unValidRate':
        		# code...
        		break;
        	case 'ddRate':
        		# code...
        		break;
        	case 'mkzJdRate':
        		# code...
        		break;
        	case 'validJdRate':
        		# code...
        		break;
        	case 'jdOrderRate':
        		# code...
        		break;
        	case 'mkzOrderRate':
        		# code...
        		break;
        	case 'validOrderRate':
        		# code...
        		break;
            default:
                $sql = 'dj_day between "'.$start.'" and "'.$end.'"';
                break;
        }
        // var_dump($sql);die;
        // 查询省条件
        $param['sql'] = $sql;
    	$param['where'] = $where;
    	$param['provinces'] = $provinces;
    	$param['channels'] = $channels;
        if ($data['getProvince']) {
        	return $this->getProvince($param);
        }
        // 省
        $column = $this->getProvince($param);
        // var_dump($column);die;
        // 渠道
        $channel = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('province','in',$provinces)->where('customer_channel','in',$channels)
            ->group('customer_channel')->column('customer_channel');
        // 数据
        $info = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('province','in',$provinces)->where('customer_channel','in',$channels)
            ->group('customer_channel,province')
            ->field('customer_channel,province,COUNT(id) AS num')
            ->select();
        $nullinfo = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('province','')->where('customer_channel','in',$channels)
            ->group('customer_channel')
            ->field('customer_channel,province,COUNT(id) AS num')
            ->select();
        
        foreach($nullinfo as $k=>$v){
            array_push($info,$nullinfo[$k]);    
        }
        $returnData = [];
        $arr = [];
        foreach ($channel as $key => $value) {
        	// var_dump($value);
        	$returnData[$key]['channel_name'] = $value;
        	foreach ($info as $k => $v) {
        		if ($value == $v['customer_channel']) {
        			$returnData[$key][$v['province']?$v['province']:'其他'] = $v['num'] ? $v['num'] : 0;
        			$returnData[$key]['总计'] += $v['num'] ? $v['num'] : 0;
        		}
        	}
        	$all += $returnData[$key]['总计'];
        }
        $arr = [];
        $arr['channel_name'] = '总计';
        $arr['总计'] = $all;
        foreach ($column as $key => $value) {
        	$arr[$value] = '';
        	foreach ($returnData as $k => $v) {
        		$arr[$value] += $v[$value];
        	}
        }

        // die;
        array_unshift($returnData, $arr);
        $return['code'] = 0;
        $return['msg'] = '';
        $return['count'] = count($channel)+1;
        $return['data'] = $returnData;
        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);
        // 省
        $province = db('s_shop_address')->where('type',1)->where('shop_code',$shop_code)->select();
        $this->assign('province', $province);
        $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';
        
        $this->assign('title', session('shop_name').'-'.$info['report_name']);

        // $shop= controller('crm/Customer','lib')->get_shop(['shop_code'=>$info['shop_code']]);

        $this->assign('did', $info['id']);
        $this->assign('today',date('Y-m-d'));
        $this->assign('yestoday',date('Y-m-d',time()));


        $channels = controller('crm/Customer', 'lib')->getChannel($shop_code);
        $channels = array_column($channels,'channel_name');
        // 省
        $province = db('s_shop_address')->where('type',1)->where('shop_code',session('shop_code'))->select();
        $provinces= array_column($province,'name');

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['add_shop_code'] = $shop_code;

        $sql = 'dj_day between "'.date('Y-m-d 00:00:00',time()).'" and "'.date('Y-m-d 23:59:59').'"';
        $param['sql'] = $sql;
    	$param['where'] = $where;
    	$param['provinces'] = $provinces;
    	$param['channels'] = $channels;
        $mc = new \app\common\lib\mcInterface();
        $shopList = $mc->cacheData('5a8fd8296f3d3',['staff_id'=>session('staff_id')]);
        $this->assign('shop_list',$shopList);
        $header = $this->getProvince($param);
        $this->assign('header',$header);
        return $this->fetch($display);
    }
    public function getProvince($param){
    	$where = $param['where'];
    	$sql = $param['sql'];
    	$provinces = $param['provinces'];

    	$column = db('c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('province','in',$provinces)
            // ->where('customer_channel','in',$channels)
            ->group('province')
            ->order('num desc')
            ->field('COUNT(id) as num,province')
            // ->fetchSql(true)
            ->select();
        // var_dump($column);
        // echo db()->getLastSql();
        // die;
        $allProvince = array_column($column,'province');
        array_push($allProvince,'其他');
        return $allProvince;
    }
}