<?php
/**
 * 百度统计图表Echarts的php实现类(支持 柱形图(bar)、线形图(line)、饼形图(pie))
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */


namespace Common\Vendor;
/**
 *支持 柱形图(bar)、线形图(line)、饼形图(pie)
 * @example: 
*        HTML代码部分：
*            <script src="__PUBLIC__/script/echarts/echarts.js"></script>
*            <body>
        <!-- 线形图、柱形图显示 -->
        <div id="chartArea" style="height:300px;border:1px solid #ccc;padding:10px;"></div>
        <!-- 饼形图显示 -->
        <div id="pieArea" style="height:300px;border:1px solid #ccc;padding:10px;"></div>
    </body>
PHP代码部分：
//  柱形图、线形图模拟数据
$option = array(
    "legend"=>array('data'=>array("邮件营销","联盟广告","视频广告","直接访问","搜索引擎")),
    "xaxis"=>array("type"=>"category","boundaryGap"=>"true","data"=>array("周一","周二","周三","周四","周五","周六","周日")),     
    "series"=>array(
                array("name"=>"邮件营销","type"=>"bar","stack"=>"总量","data"=>array("120","132","101","134","90","230","210")),                  
                array("name"=>"联盟广告","type"=>"bar","stack"=>"总量","data"=>array("220","182","191","234","290","330","310")),             
                array("name"=>"视频广告","type"=>"bar","stack"=>"总量","data"=>array("150","232","201","154","190","330","410")),             
                array("name"=>"直接访问","type"=>"bar","stack"=>"总量","data"=>array("320","332","301","334","390","330","320")),                 
                array("name"=>"搜索引擎","type"=>"bar","stack"=>"总量","data"=>array("820","932","901","934","1290","1330","1320")),          
            ),
    );
$ec = new \Common\Vendor\Echarts();
echo $ec->show('chartArea', $option);  // 显示在指定的dom节点上
// 饼形图模拟数据
$optionPie = array(
        "legend"=>array('orient'=>'布局方式，默认为水平布局，可选为horizontal|vertical','x'=>'center|left|right|{number}','y'=>'top|bottom|center|{number}','data'=>array("邮件营销","联盟广告","视频广告","直接访问","搜索引擎")),
        "series"=>array(
                array("name"=>"邮件营销","type"=>"pie","stack"=>"总量", 'startAngle'=>'起始角度',
                        "data"=>array(
                                array("value"=>"335","name"=>"直接访问"),
                                array("value"=>"310","name"=>"邮件营销"),
                                array("value"=>"234","name"=>"联盟广告"),
                                array("value"=>"135","name"=>"视频广告"),
                                array("value"=>"1548","name"=>"搜索引擎"),
                        ),
                ),
        ),
);
$ec = new \Common\Vendor\Echarts();
echo $ec->show('pieArea', $optionPie,'pie'); // 显示在指定的dom节点上
 */ 
class Echarts{ 
     public static function show($id, array $data,$type='',$title='',$subtext='',$y_unit=''){
       $xaxis =$legend=$series = "";
       if(empty($type))$type='bar';
       $require_char=array(
         'bar,line'=>"'echarts/chart/bar','echarts/chart/line'",
         'bar'=> "'echarts/chart/bar'",
         'line'=>"'echarts/chart/line'",
         'pie'=> "'echarts/chart/pie'"
       );
        if (empty($data)) {           
            $data = array(
                'legend' => array('data'=>array('-')),
                'xaxis' => array(
                    'type' => 'category',
                    'boundaryGap' => 'false',
                    'data' => array('')
                ),
                'series' => array(
                    array(
                        'name' => '-',
                        'type' => 'line',
                        'itemStyle' => "{normal: {areaStyle: {type: 'default'}}}",
                        'data' => array()
                    ),
                )
            );
        }
        foreach ($data as $key => $value) {
            switch ($key) {
                case 'legend':foreach ($value as $k => $v) {$legend[] =  $k .':'. (is_array($v)?json_encode($v):"'".$v."'");}break;
                case 'xaxis':
                    foreach ($value as $k => $v) {
                        switch ($k) {
                            case 'boundaryGap':$xaxis[] = $k . ':' . $v;break;
                            default:$xaxis[] = $k . ':' . (is_array($v)?json_encode($v):"'".$v."'");break;
                        }
                    }$xaxis = '{' . implode(', ', $xaxis) . '}';
                break;                     
                case 'series':
                    foreach ($value as $list) {
                        $tmp = array();
                        foreach ($list as $k => $v) {
                            $tmp[] = $k . ':' . (is_array($v)?json_encode($v):"'".$v."'");
                        }$series[] = '{' . implode(', ', $tmp) . '}';
                    }$series = implode(', ', $series);
               break;
            }
        }
        $y_unit_str='';
        if($y_unit){//Y轴单位
            $y_unit_str=",axisLabel:{formatter:'{value} ".$y_unit."'}";
        }
// Step:3 为模块加载器配置echarts的路径，从当前页面链接到echarts.js，定义所需图表路径
// 把所需图表指向单文件
// Step:4 动态加载echarts然后在回调函数中开始使用，注意保持按需加载结构定义图表路径 
// 按需加载所需图表
$script ="<script type=\"text/javascript\">
require.config({paths:{echarts:'".__ROOT__."/Public/script/echarts/'}});

require(
    ['echarts',".$require_char[$type]."],
    function(ec) {
        var myChart = ec.init(document.getElementById('".$id."'));
        var option = {
            title : {text: '".$title."',subtext: '".$subtext."'},
            tooltip : {trigger: 'axis'},
            legend: {".implode(',',$legend)."},
            toolbox: {show : true,
                feature : {
                    mark : true,
                    dataView : {readOnly: false},
                    magicType:['line', 'bar'],
                    restore : true
                }
            },
            calculable : true,
            xAxis : [".$xaxis."],
            yAxis : [{type:'value'".$y_unit_str."}],
            series : [".$series."]
        }; myChart.setOption(option);
    }
);</script>"; 
return $script;
}

//饼状图
public static function pie_show($id, array $data,$type='',$title='',$subtext=''){
   $xaxis =$legend=$series = "";
   if(empty($type))$type='bar';
   $require_char=array(
     'bar,line'=>"'echarts/chart/bar','echarts/chart/line'",
     'bar'=> "'echarts/chart/bar'",
     'line'=>"'echarts/chart/line'",
     'pie'=> "'echarts/chart/pie'"
   );
    if (empty($data)) {
        $data = array(
            'legend' => array('data'=>array('-')),
            'xaxis' => array(
                'type' => 'category',
                'boundaryGap' => 'false',
                'data' => array('')
            ),
            'series' => array(
                array(
                    'name' => '-',
                    'type' => 'line',
                    'itemStyle' => "{normal: {areaStyle: {type: 'default'}}}",
                    'data' => array()
                ),
            )
        );
    }
    $en_keys=array();
    foreach($data['series'][0]['data'] as $k=>$v){
        $v['value']=trim($v['value']);
        if(!empty($v['value']))$en_keys[]=$k;
    }
    foreach ($data as $key => $value) {
        switch ($key) {
            case 'legend':
            if(empty($value['orient']))$value['orient']='vertical';
            if(empty($value['x']))$value['x']='left';
            foreach ($value as $k => $v) {
                if(is_array($v)){foreach($v as $kk=>$vv){if(!in_array($kk,$en_keys))unset($v[$kk]);}$v=array_values($v);}
                $legend[] =  $k .':'. (is_array($v)?json_encode($v):"'".$v."'");
            }
            break;
            case 'xaxis':
                foreach ($value as $k => $v) {
                    if(is_array($v)){foreach($v as $kk=>$vv){if(!in_array($kk,$en_keys))unset($v[$kk]);}$v=array_values($v);}
                    switch ($k) {
                        case 'boundaryGap':$xaxis[] = $k . ':' . $v;break;
                        default:$xaxis[] = $k . ':' . (is_array($v)?json_encode($v):"'".$v."'");break;
                    }
                }$xaxis = '{' . implode(', ', $xaxis) . '}';
            break;                     
            case 'series':
                foreach ($value as $list) {
                    $tmp = array();
                    foreach ($list as $k => $v) {
                        if(is_array($v)){foreach($v as $kk=>$vv){if(!in_array($kk,$en_keys))unset($v[$kk]);}$v=array_values($v);}
                        $tmp[] = $k . ':' . (is_array($v)?json_encode($v):"'".$v."'");
                    }$series[] = '{' . implode(', ', $tmp) . '}';
                }$series = implode(', ', $series);
           break;
        }
    }
// Step:3 为模块加载器配置echarts的路径，从当前页面链接到echarts.js，定义所需图表路径
// 把所需图表指向单文件
// Step:4 动态加载echarts然后在回调函数中开始使用，注意保持按需加载结构定义图表路径 
// 按需加载所需图表
$script ="<script type=\"text/javascript\">
require.config({paths:{echarts:'".__ROOT__."/Public/script/echarts/'}});
require(
    ['echarts',".$require_char[$type]."],
    function(ec) {
        var myChart = ec.init(document.getElementById('".$id."'));
        var option = {
            title : {text: '".$title."',subtext: '".$subtext."'},
            tooltip : {trigger: 'item',formatter: '{a} <br/>{b} : {c} ({d}%)'},
            legend: {".implode(',',$legend)."},
            toolbox: {show : true,
                feature : {
                    mark : true,
                    dataView : {readOnly: false},
                    magicType:['line', 'bar'],
                    restore : true
                }
            },
            calculable : true,
            series : [".$series."]
        }; myChart.setOption(option);
    }
);</script>"; 
return $script;
}
}
?>