<?php
require_once CORE_LIB.'/PHPExcel/Classes/PHPExcel.php';

class StatisticDownloader {

    /**
     *
     */
    protected $objPHPExcel;
    /**
     *数据源
     */
    protected $data;
    /**
     * 1,单天详情；2，平均；3，合计；
     */
    protected $type;

    protected $fileName= 'default.xls';

    protected $column;

    protected $dataListener = array();

    public function __construct() {
        PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_to_discISAM);
        $this->objPHPExcel = new PHPExcel();
        $this->column = getAbc();
    }

    public function getObjPHPExcel() {
        return $this->objPHPExcel;
    }

    public function setData($data) {
        $this->data = $data;
    }
    public function getData() {
        return $this->data;
    }
    public function setType($type) {
        $this->type = $type;
    }
    public function getType() {
        return $this->type;
    }
    public function createTitle() {

    }


    public function setFileName($fileName) {
        $this->fileName = $fileName;
    }
    public function output() {
        // Redirect output to a client’s web browser (Excel5)
        global $debug;
        if($debug) {
            $objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel5');
            echo str_replace('.php', '.xls', __FILE__);
            $objWriter->save(str_replace('.php', '.xls', __FILE__));
        } else {
            header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$this->fileName.'"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0

        $objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        }

    }

    public function setCellValue($key,$value) {
        $value = iconv('gbk', 'utf-8', $value);
        $this->objPHPExcel->setActiveSheetIndex(0)->setCellValue($key,$value);
    }

    public function setCellFont($key,$font='SimSun',$size='10',$bold=true) {
        $this->objPHPExcel->getActiveSheet()->getStyle($key)->getFont()->setName($font);
        $this->objPHPExcel->getActiveSheet()->getStyle($key)->getFont()->setSize($size);
        $this->objPHPExcel->getActiveSheet()->getStyle($key)->getFont()->setBold($bold);
        //$this->objPHPExcel->getActiveSheet()->getStyle($key)->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
        //$this->objPHPExcel->getActiveSheet()->getStyle($key)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
    }

    /**
     *PHPExcel_Style_Alignment::HORIZONTAL_RIGHT
     *PHPExcel_Style_Alignment::VERTICAL_CENTER
     */
    public function setCellAlign($key,$horizontal,$vertical) {
        $objAlignA5 = $this->objPHPExcel->getActiveSheet()->getStyle($key)->getAlignment();
        $objAlignA5->setHorizontal($horizontal);
        $objAlignA5->setVertical($vertical);
    }

    public function setCellSize($key,$width = null) {
         $column = $this->objPHPExcel->getActiveSheet()->getColumnDimension($key);
        if($width) {
           $column->setAutoSize(true);
        }else {
            $column->setWidth($width);
        }
    }

    public function mergerCells($key1,$key2) {
        $this->objPHPExcel->getActiveSheet()->mergeCells($key1.':'.$key2);
    }

    public function dataListener($key,$value) {
        $arr = array('publish_rate','star_publish_rate','refresh_rate','sell_publish_rate','rent_publish_rate','sell_star_rate','rent_star_rate');
        if(in_array($key,$arr)) {
            $value = number_format($value, 1, '.', '').'%';
//round( $value , 1 )."%";
            return $value;
        } else if($key=='streetid') {
            $arr = getStreetBaseById($value);
            return $arr['streetname'];
        } else {
            return $value;
        }
    }
}


class AgencyStatisticDownloader extends StatisticDownloader {

    private $agencyDownloadColumn;
    private $dataDownloadColumn;
    private $downloadType='field';  //下载类型
    private $useColumn;

    public function setAgencyDownloadColumn($agencyDownloadColumn) {
        $this->agencyDownloadColumn = $agencyDownloadColumn;
    }

    public function setDataDownloadColumn($dataDownloadColumn) {
        $this->dataDownloadColumn = $dataDownloadColumn;
    }
    public function prepare() {

    }

    public function createTitle() {

        if(1) {
            $this->createAgencyInfoTitle();

            //$this->objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'Hello')->setCellValue('B2', 'world!')->setCellValue('C1', 'Hello')->setCellValue('D2', 'world!');
            $this->createDataUnitTitle();
            //print_r($this->column);
        }
    }

    public function writeData() {
        global $debug;

        if($this->data) {
        foreach($this->data as $key=>$data) {
            //从第三行开始
            $line =3;
            $line += $key;
            foreach($this->useColumn as $cellKey=>$c) {
                $value = $this->dataListener($c,$data[$c]);
                //echo $cellKey.$line;
                //echo $value.'|';
                if($c =='agenttel') {$value = ' '.$value;
                    $this->objPHPExcel->getActiveSheet()->getStyle($cellKey.$line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                }
                $this->setCellValue($cellKey.$line,$value);


            }
            if($debug) {
                echo memory_get_usage()/1024, '<br />';
            }
            //echo '<br/>';
            //print_r($data);
        }
        }
        //exit;
    }

    private function createTitleStyleOne($TitleConfig) {
        //print_r($TitleConfig);
        $value  = $TitleConfig;
            $cell = $this->getColums(1);
                $key1 = $cell[0].'1';
                $key2 = $cell[0].'2';
                $key = $cell[0].'1';
                $this->setCellValue($key,$value['name']);
                $this->setCellFont($key);
                $this->setCellAlign($key,
                    PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $this->setCellSize($key,$width);
                $this->mergerCells($key1,$key2);

                $this->useColumn[$cell[0]] = $value['field'];
    }

    private function createAgencyInfoTitle() {
        $TitleConfig= array();
        if($this->getType()==1) {
        $TitleConfig['time'] = array('0'=>array('name'=>'时间','field'=>'stattime'));

            foreach($TitleConfig['time'] as $key=>$value) {
            $cell = $this->getColums(1);
            $key1 = $cell[0].'1';
            $key2 = $cell[0].'2';
            $key = $cell[0].'1';
            $this->setCellValue($key,$value['name']);
            $this->setCellFont($key);
            $this->setCellAlign($key,
            PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $this->setCellSize($key,$width);
            $this->mergerCells($key1,$key2);
            $this->useColumn[$cell[0]] = $value['field'];
            }
        }
            //print_r($this->useColumn);exit;
        if($this->agencyDownloadColumn) {
        $TitleConfig['agency'] = $this->agencyDownloadColumn->getNeedColumn();
        foreach($TitleConfig['agency'] as $key=>$value) {
            $cell = $this->getColums(1);
                $key1 = $cell[0].'1';
                $key2 = $cell[0].'2';
                $key = $cell[0].'1';
                $this->setCellValue($key,$value['name']);
                $this->setCellFont($key);
                $this->setCellAlign($key,
                    PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $this->setCellSize($key,$width);
                $this->mergerCells($key1,$key2);
                $this->useColumn[$cell[0]] =$value['field'];
            }
        }
        //$c = $TitleConfig['time']+$TitleConfig['agency'];
        //print_r($TitleConfig['agency']);exit;
        

            //print_r($this->useColumn);exit;
    }

    /**
     *
     */
    private function createDataUnitTitle() {
        if($this->dataDownloadColumn) {
        $allColumns = $this->dataDownloadColumn->getNeedColumn();
        //print_r($allColumns);exit;
        foreach($allColumns as $v) {
            if(count($v['value'])) {
            $cells = $this->getColums(count($v['value']));
            $this->drawOneUnit($cells,$v);
            } else {
            $this->createTitleStyleOne($v);
            }
        }
        }
        //print_r($this->useColumn);exit;
    }

    /**
     *
     *@param $cells = array('E','F');
     *@param $v = array('key'=>'有效房源','value'=>array('1'=>'总量','3'=>'发布率'));
     */
    private function drawOneUnit($cells,$v) {
        $number = count($cells);
        $this->setCellValue($cells[0].'1',$v['key']);
        $this->setCellFont($cells[0].'1','SimSun','10',true);
        $this->setCellAlign($cells[0].'1',
                 PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                 PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //$this->setCellSize($key,$width);
        if($number>0) {
        $this->mergerCells($cells[0].'1',$cells[$number-1].'1');}
        $i=0;
        $line = 2;
        $sub = $v['value'];
        foreach($sub as $s) {
            $cv = $s['name'];
            if($this->getType()==2) {
               $cv = $s['prefix'].$cv;
            }

            $this->setCellValue($cells[$i].$line,$cv);

            $colum = $this->getDownloadType();
            $this->useColumn[$cells[$i]] = $s[$colum];

            $this->setCellFont($cells[$i].$line,'SimSun','10',false);
            $this->setCellAlign($cells[$i].$line,
                 PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                 PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $i++;
        }
    }

    public function getDownloadType(){
        return $this->downloadType;
    }

    public function setDownloadType($downloadType)
    {

        switch ($downloadType){
            case 'sell':
                $type = 'sell_field';
                break;
            case 'rent':
                $type = 'rent_field';
                break;
            default :
                $type = 'field';
        }

        $this->downloadType = $type;
    }

    private function getColums($number){
        $i = 0;
        $arr = array();
        for($i;$i<$number;$i++) {
            $arr[] = array_shift ($this->column);
        }
        return $arr;
    }
}

class BrokerStatisticDownloader extends StatisticDownloader {

}


function getAbc($i='A') {
    //$i = 'A';
    $abc = array();
    for($n;$n<100;$n++) {
        $abc[]  = $i++;
    }
    return $abc;
}
$column = getAbc();

class AgencyDownloadColumn {
    public $allColumns = array(
        '1'=>array('name'=>'区属','field'=>'dist'),
        '2'=>array('name'=>'板块','field'=>'streetid'),
        '3'=>array('name'=>'门店编号','field'=>'agentcode'),
        '4'=>array('name'=>'所属片区','field'=>'cat_name'),
        '5'=>array('name'=>'门店名称','field'=>'agentshortname'),
        '6'=>array('name'=>'店长','field'=>'director'),
        '7'=>array('name'=>'联系方式','field'=>'agenttel','style'=>'text'),
        '8'=>array('name'=>'经纪人数量','field'=>'broker_num'),
        );

    private $columnKey;

    private $needColumnKeys;

    public function __construct(array $keys = null) {
        $this->needColumnKeys = $keys;
        //$this->columnKey = getAbc();
        //print_r($this->needColumnKeys);
    }

    public function getNeedColumn() {
        $nc = array();
        if($this->needColumnKeys) {
        foreach($this->allColumns as $key=>$v ) {
            if(in_array($key,$this->needColumnKeys)) {
                $nc[] = $v;
            }
        }
        } else {
            $nc = $this->allColumns;
        }

        return $nc;
    }
    function getAllColumns() {
        return $this->allColumns;
    }

    function setAllColumns($allColumns) {
        $this->allColumns = $allColumns;
    }

}


class DataDownloadColumn {
    public $allColumns = array(
        '1'=>array('key'=>'有效房源',
                    'value'=>array(
                        '1'=>array('name'=>'总量','displayname'=>'有效房源总量','field'=>'house_num','prefix'=>'日均'),
                        '2'=>array('name'=>'上限','displayname'=>'有效房源上限','field'=>'postlimit','prefix'=>''),
                        '3'=>array('name'=>'发布率','displayname'=>'房源发布率','field'=>'publish_rate','prefix'=>'日均'))
                  ),
        '2'=>array('key'=>'多图房源',
                    'value'=>array(
                        '1'=>array('name'=>'有效多图','displayname'=>'有效多图总量','field'=>'star_num','prefix'=>'日均'),
                        '2'=>array('name'=>'有效总量','displayname'=>'有效房源总量','field'=>'house_num','prefix'=>'日均'),
                        '3'=>array('name'=>'多图率','displayname'=>'房源多图率','field'=>'star_publish_rate','prefix'=>'日均'))
                    ),
        '3'=>array('key'=>'新增房源',
                    'value'=>array(
                        '1'=>array('name'=>'有效出售','displayname'=>'新增有效出售','field'=>'sell_add','prefix'=>'日均'),
                        '2'=>array('name'=>'有效出租','displayname'=>'新增有效出租','field'=>'rent_add','prefix'=>'日均'),
                        '3'=>array('name'=>'总量','displayname'=>'新增合计','field'=>'addNum','prefix'=>'日均'))
                    ),
        '4'=>array('key'=>'刷新使用',
                    'value'=>array(
                        '1'=>array('name'=>'已用','displayname'=>'已用刷新次数','field'=>'refresh','prefix'=>'日均'),
                        '2'=>array('name'=>'上限','displayname'=>'刷新次数上限','field'=>'refresh_limit','prefix'=>''),
                        '3'=>array('name'=>'刷新率','displayname'=>'刷新使用率','field'=>'refresh_rate','prefix'=>'日均'))
                    ),
        '5'=>array('key'=>'点击量',
                    'value'=>array(
                        '1'=>array('name'=>'出售点击','displayname'=>'出售点击','field'=>'sell_click','prefix'=>'日均'),
                        '2'=>array('name'=>'出租点击','displayname'=>'出租点击','field'=>'rent_click','prefix'=>'日均'),
                        '3'=>array('name'=>'总量','displayname'=>'点击总量','field'=>'click_num','prefix'=>'日均'))
                    ),
        '6'=>array('key'=>'标签房源',
                    'value'=>array(
                        '1'=>array('name'=>'在用','displayname'=>'当前标签房源数','field'=>'tag_num','prefix'=>'日均'),
                        '2'=>array('name'=>'剩余','displayname'=>'剩余标签数','field'=>'remainTagNum','prefix'=>''),
                        '3'=>array('name'=>'上限','displayname'=>'标签上限','field'=>'package_tag_num','prefix'=>''))
                    ),
        /*'7'=>array('key'=>'标签房源','name'=>'登录次数','field'=>'broker_num',
                    'value'=>array()
                    ),*/
       '7'=>array('key'=>'新房直售',
                'value'=>array(
                    '1'=>array('name'=>'在用','displayname'=>'新房直售在用','field'=>'nofee_num','sell_field'=>'nofee_num','rent_field'=>'-','prefix'=>'日均','behind_fix'=>''),
                    '2'=>array('name'=>'上限','displayname'=>'新房直售上限','field'=>'nofee_limit','sell_field'=>'sell_star_num','rent_field'=>'-','prefix'=>'','behind_fix'=>'')
                ),
    )

    );

    public function __construct(array $keys = null) {
        //$keys = array(1=>array(1,3),3=>array(1,2),5=>array(2,3),6=>array(1,2,3));
        $this->needColumnKeys = $keys;
    }


    public function getNeedColumn() {
        $nc = array();
        $i = 1;
        $res = array();
        if($this->needColumnKeys) {
            foreach($this->needColumnKeys as $k=>$v) {
                if(array_key_exists($k,$this->allColumns)) {
                    $temp = $this->allColumns[$k];
                    foreach($temp['value'] as $vk=>&$vv) {
                        if(!in_array($vk,$v)) {
                            unset($temp['value'][$vk]);
                        }
                    }
                    $res[] = $temp;
                }
            }
        }
        if(!$res) {
            $res = $this->allColumns;
        }
        return $res;
    }

    function getAllColumns() {
        return $this->allColumns;
    }
    function setAllColumns($allColumns) {
        $this->allColumns = $allColumns;
    }

}

class CommonReport {
    static public $types = array(
        'a'=>array('title'=>'单天门店工作质量报表','description'=>'所选择的片区门店、所选择的截止时间的门店单天使用统计数据。'),
        'b'=>array('title'=>'一周门店工作质量每日报表','description'=>'所选择的片区门店、所选择的截止时间前一周的门店每天使用统计数据。'),
        'c'=>array('title'=>'一周门店工作质量平均报表','description'=>'所选择的片区门店、所选择的截止时间前一周的门店7天平均使用统计数据。'),
        'd'=>array('title'=>'单天经纪人工作质量报表','description'=>'所选择的片区门店、所选择的截止时间的经纪人单天使用统计数据。'),
        'e'=>array('title'=>'一周经纪人工作质量每日报表','description'=>'所选择的片区门店、所选择的截止时间前一周的经纪人每天使用统计数据。'),
        'f'=>array('title'=>'一周经纪人工作质量平均报表','description'=>'所选择的片区门店、所选择的截止时间前一周的经纪人7天平均使用统计数据。'),
        'g'=>array('title'=>'一周经纪人工作质量合计报表','description'=>'所选择的片区门店、所选择的截止时间前一周的经纪人7天总计使用统计数据。')
    );
    private $type;
    private $endTime;
    public function __construct($type,$endTime) {
        $this->type = $type;
        $this->endTime = $endTime;
    }

    public function getStatisticTime() {
        if($this->type=='a') {
            $time = array('starttime'=>$this->endTime,'endtime'=>$this->endTime);
        }
        if($this->type=='b') {
            $time =  $this->getTime(2,$this->endTime);
        }
        if($this->type=='c') {
            $time =  $this->getTime(2,$this->endTime);
        }
        if($this->type=='d') {
            $time = $this->getTime(1,$this->endTime);
        }
        if($this->type=='e') {
            $time =  $this->getTime(2,$this->endTime);
        }
        if($this->type=='f') {
            $time =  $this->getTime(2,$this->endTime);
        }
        if($this->type=='g') {
            $time =  $this->getTime(2,$this->endTime);
        }
        //print_r($time);exit;
        return $time;
    }

    /**
     *@param $timeType 1 单天，2 一周
     */
    private function getTime($timeType,$endTime) {
        if($timeType ==1) {//昨天
            $beginTime = strtotime("0days",strtotime($endTime));
            $beginTime = date("Y-m-d",$beginTime);
            $endTime = strtotime("0days",strtotime($endTime));
            $endTime = date("Y-m-d",$endTime);
        //echo date("Y-m-d",$endTime);
    } else if($timeType==2) {//过去一周
        $beginTime = strtotime("-6days",strtotime($endTime));
        $beginTime = date("Y-m-d",$beginTime);
        $endTime = strtotime("-0days",strtotime($endTime));
        $endTime = date("Y-m-d",$endTime);
        //echo date("Y-m-d",$endTime);
    } else {//自定义时间
        $beginTime = $beginTime;
        $endTime = $endTime;
    }
    return $time = array('starttime'=>$beginTime,'endtime'=>$endTime);
    }

    public function getStatisticType() {
        if($this->type=='a') {
            $stype = 1;
        }
        if($this->type=='b') {
            $stype = 1;
        }
        if($this->type=='c') {
            $stype = 2;
        }
        if($this->type=='d') {
            $stype = 1;
        }
        if($this->type=='e') {
            $stype = 1;
        }
        if($this->type=='f') {
            $stype = 2;
        }
        if($this->type=='g') {
            $stype = 3;
        }
        return $stype;
    }

    public function getFileName($agencyName='',$areaName='',$subAgencyName='',$brokerName='') {
        if($this->type=='a') {
            $stype = 1;
            $type = 1;
        }
        if($this->type=='b') {
            $stype = 1;
            $type = 1;
        }
        if($this->type=='c') {
            $stype = 2;
            $type = 1;
        }
        if($this->type=='d') {
            $stype = 1;
            $type = 2;
        }
        if($this->type=='e') {
            $stype = 1;
            $type = 2;
        }
        if($this->type=='f') {
            $stype = 2;
            $type = 2;
        }
        if($this->type=='g') {
            $stype = 3;
            $type = 2;
        }
        $dateArr = $this->getStatisticTime();
        //print_r($dateArr);exit;
        $SdFileName = new SdFileName($dateArr,$type,$agencyName,$areaName,$subAgencyName,$brokerName);
        return $SdFileName->getFileName();
    }

}


class BrokerDownloadColumn {
    public $allColumns = array(
        '1'=>array('name'=>'经纪人姓名','field'=>'truename'),
		'2'=>array('name'=>'经纪人账号','field'=>'username'),
        '3'=>array('name'=>'公司内部系统号','field'=>'agentcode'),
        '4'=>array('name'=>'所属门店','field'=>'agentshortname'),
        '5'=>array('name'=>'店长姓名','field'=>'director'),
        '6'=>array('name'=>'所属片区','field'=>'cat_name'),
        '7'=>array('name'=>'套餐类型','field'=>'groupname'),
        '8'=>array('name'=>'开通日期','field'=>'regdate'),
        '9'=>array('name'=>'账号剩余天数','field'=>'remain_valid_days'),
        );

    private $columnKey;

    private $needColumnKeys;

    public function __construct(array $keys = null) {
        $this->needColumnKeys = $keys;
    }

    public function getNeedColumn() {
        $nc = array();
        if($this->needColumnKeys) {
        foreach($this->allColumns as $key=>$v ) {
            if(in_array($key,$this->needColumnKeys)) {
                $nc[] = $v;
            }
        }
        } else {
            $nc = $this->allColumns;
        }

        return $nc;
    }
    function getAllColumns() {
        return $this->allColumns;
    }

}


/**
 *
 */
class SdFileName {

    private $dateArr;
    private $type;
    private $agencyName;
    private $areaName;
    private $subAgencyName;
    private $brokerName;
    public function __construct($dateArr,$type=1,$agencyName='',$areaName='',$subAgencyName='',$brokerName='') {
        $this->dateArr= $dateArr;
        $this->type = $type;
        $this->agencyName = $agencyName;
        $this->areaName = $areaName;
        $this->subAgencyName = $subAgencyName;
        $this->brokerName = $brokerName;

    }

    public function getFileName() {
        return $this->agencyName.$this->areaName.$this->subAgencyName.$this->brokerName.$this->getTypeString().$this->getDateString().'.xls';
    }

    private function getTypeString() {
        $arr = array(1=>'租售宝门店使用数据统计',2=>'租售宝经纪人使用数据统计');
        return $arr[$this->type];
    }

    private function getDateString() {
        //array('starttime'=>$beginTime,'endtime'=>$endTime);
        if($this->dateArr['starttime']==$this->dateArr['endtime']) {
            return str_replace(".","-",$this->dateArr['starttime']);
        } else {
            return str_replace(".","-",$this->dateArr['starttime']).'至'.str_replace(".","-",$this->dateArr['endtime']);
        }
    }
}
?>