<?php
namespace admin\action;
!defined('BR') && define('BR',"\r\n"); //回车换行符
!defined('XLSBR') && define('XLSBR'," &#10;"); //Excel换行符
use \model\pdflib\pdfset;
use \model\pdflib\pdfSS;
use \model\pdflib\pdfSS2;

class pdflibAction  extends \action
{
	public function __construct()
	{

	}
	/**
	  * @method 版式配置
	  * @param
	  */
	function pdfset($cateid = '', $tplid = '')
	{
		$pdfset = new pdfset();
		$cates = $pdfset->getCateAll();
		\view::set('cates', $cates);
		if (!empty($cateid)) {
			$found_key = array_search($cateid, array_column($cates, 'pdfc_id'));
			$caterow = $cates[$found_key];
			$procates = ($caterow && $caterow['pdfc_cates']) ? make(\model\pro\cate::class)->getRowsByKeys($caterow['pdfc_cates']) : [];
			
			\view::set('procates', $procates);
			\view::set('caterow', $caterow);
			\view::set('tpls', $pdfset->getTpls($cateid));
		}
		if (!empty($tplid)) {
			\view::set('tplrow', $pdfset->getTplRow($tplid));
		}
		\view::put('pdflib/setup');
	}

	function pdfsetSS($cateid = '11', $tplid = '')
	{
		$pdfset = new pdfset();
		$cates = $pdfset->getCateAll();
		\view::set('cates', $cates);
		if (!empty($cateid)) {
			$found_key = array_search($cateid, array_column($cates, 'pdfc_id'));
			$caterow = $cates[$found_key];
			$procates = ($caterow && $caterow['pdfc_cates']) ? make(\model\pro\cate::class)->getRowsByKeys($caterow['pdfc_cates']) : [];
			//$nameArr = array_column($procates,'en_name');
			//array_multisort($nameArr,SORT_ASC,$procates);
			$areas = (new \model\element('m_area'))->getRowsByFieldValue('ma_isend', '1');
			$vers = (new \model\element('tags'))->getRowsAll();
			\view::set('procates', $procates);
			\view::set('caterow', $caterow);
			\view::set('areas', $areas);
			\view::set('vers', $vers);
			\view::set('cateid', $cateid);
			\view::set('tpls', $pdfset->getTpls($cateid));
		}
		if (!empty($tplid)) {
			\view::set('tplrow', $pdfset->getTplRow($tplid));
		}
		\view::put('pdflib/setupSS');
	}

	/**
	 * @method 悬挂件 新版目录
	 * @param
	 */
    function pdfSS($id,$cateIds)
	{
		if(empty($id)) $this->errorJson(500);
		$result = make(pdfset::class)->saveSetCate($id,$cateIds);
		if($result===true)
			$this->successJson();
		else
			$this->errorJson(2001,$result);
    }

		
	/**
	  * @method 为大版选择 品名
	  * @param
	  */
    function saveSetCate($id,$cateIds)
	{
		if(empty($id)) $this->errorJson(500);
		$result = make(pdfset::class)->saveSetCate($id,$cateIds);
		if($result===true)
			$this->successJson();
		else
			$this->errorJson(2001,$result);
    }

	/**
	  * @method 保存车型区域
	  * @param
	  */
    function saveArea($id,$ma_id)
	{
		if(empty($id)) $this->errorJson(500);
		make(pdfset::class)->changeArea($id,$ma_id);
		$this->successJson();
    }

	/**
	  * @method 保存版本
	  * @param
	  */
    function saveVer($id,$ver)
	{
		if(empty($id)) $this->errorJson(500);
		make(pdfset::class)->changeVer($id,$ver);
		$this->successJson();
    }

	/**
	  * @method 保存模板相关
	  * @param
	  */
    function saveTplLink($id,$data)
	{
		if(empty($id)) $this->errorJson(500);
		make(pdfset::class)->saveTplLink($id,$data);
		$this->successJson();
    }


	/**
	  * @method 删除图片
	  * @param
	  */
    function deleteImage($id,$fileid)
	{
		make(\model\files::class)->deleteJsonFile('pdf_tpl_link','pdftl_json','pdftl_id',$id,$fileid);
		$this->successJson();
    }


	/**
	 * @method 生成界面弹窗
	 * @param
	 */
	function exectueView($cateid)
	{
		$pdfset = new pdfset();
		$cate = $pdfset->getCateByKey($cateid);
		\view::set('cate', $cate);
		\view::put('pdflib/execute');
	}

	/**
	 * @method 生成SS
	 * @param
	 */
	function exectueSS($cateid, $selectModels = '')
	{
		if (getOpuser() == 'test.admin') {
			$pdfSS = new pdfSS2($cateid, $selectModels);
			//$pdfSS = new pdfSS($cateid, $selectModels);
		} else {
			$pdfSS = new pdfSS2($cateid, $selectModels);
			//$pdfSS = new pdfSS($cateid, $selectModels);
		}
		$pdfSS->execute();
	}

	/**
	 * @method 导出相同GSP型号的小车型列表
	 * @param
	 */
	function exportSameModelGspNo($cateid, $selectModels = '')
	{
		$symbols = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩'];
		$pdfSS = new pdfSS($cateid, $selectModels);
		list($sameOutnums, $diffRemarks) = $pdfSS->exportSameModelGspNo();
		//dd($sameOutnums, $diffRemarks);
		$html = '';
		$html .= '<table id="report" class="table" border="1">';
		$html .= '<thead><tr><th>大车型</th><th>小车型</th><th>GSP 型号</th><th>备注</th></tr></thead>';
		$gi = 0;
		foreach ($diffRemarks as $make => $groups) {
			foreach ($groups as $gk => $group) {
				$modelsText = '';
				foreach ($sameOutnums[$make][$gk] as $mi => $model) {
					if ($modelsText) $modelsText .= "<br>\n";
					$modelsText .= $symbols[$mi] . ' ' . $model;
				}
				$bgColor = 'F4F4F4';
				if ($gi % 2 == 0) {
					$bgColor = '#FFFFFF';
				}
				foreach ($group as $outnum => $item) {
					if ($item['diff']) {
						$remark = $item['remarksChange'];
						$html .= '<tr>';
						$html .= "<td style='vertical-align: middle;background-color:{$bgColor}'>{$make}</td>";
						$html .= "<td style='vertical-align: middle;background-color:{$bgColor}'>{$modelsText}</td>";
						$html .= "<td style='vertical-align: middle;background-color:{$bgColor}'>{$outnum}</td>";
						$html .= "<td style='vertical-align: middle;background-color:{$bgColor}'>{$remark}</td>";
						$html .= '</tr>';
					}
				}
				$gi++;
			}
		}
		$html .= '</table>';
		\view::set('html', $html);
		\view::put();
	}

	/**
	 * @method 生成PDF
	 * @param $method
	 */
    function execute($cateId,$type,$selectModels='')
	{
		ini_set('memory_limit', \mvc::$cfg['export_memory_limit']);
		set_time_limit(0);
		ignore_user_abort(true);
		$brand = $type;
		if($type=='excel'){
    		$brand = 'gsp';
		}elseif($type=='excel2'){
    		$brand ='gsp';
		}elseif($type=='excelG'){
    		$brand ='g';
		}elseif($type=='excel2G'){
    		$brand ='g';
		}
		//大版配置
		$pdfset = new pdfset();
		$cate = $pdfset->getCateByKey($cateId);

		if(empty($cate)){
			$this->errorJson(404, sprintf('没有找到指定的排版类别[%s]',$cateId) );
		}

		//输出的目录与文件名
		$pdfpath = \mvc::$cfg['dir']['pdflib'];
		$filepath = \mvc::$cfg['dir']['files'].'/pdf';
		if(!is_dir($filepath)) mkdir($filepath,0777);
		$filepath .= '/'.getOpuser();
		if(!is_dir($filepath)) mkdir($filepath,0777);
		$filename = $cate['pdfc_filename'].'-'.date('Y').'.pdf';
		$color = ($brand=='g') ? 'red' : 'blue';
        
		//调用PHPLIB
		$options = [
			'debug' => true, // 调试某块子版式的时候, 设置debug为FALSE
			'style' => $cate['pdfc_style'], // 选择目录版式
			'remark' => $cate['pdfc_remark'],

            'color' => $color, // 风格: 蓝色(blue) | 红色(red)
			'name' => $filename, // 文件名称
			'path' => $filepath, // 存放目录

			'browser' => false, // 是否浏览器调试模式 / 保存文件返回文件名
			'resources' => sprintf('%s/storage', \mvc::$cfg['dir']['pdflib']), // 资源目录
		];
		$data = $pdfset->getCateInfo($cate,$selectModels,$brand);
		$options = array_merge($data['options'],$options);
		$values = $data['values'];
        if(empty($values)){
           $this->msgJson('没有找到数据');
        }
        if($type=='excel'){
    		$this->outputExcel($cate['pdfc_filename'],$this->tplData($values));
    		exit();
        }
        if($type=='excel2'){
    		$this->xlsx($cate['pdfc_filename'],$this->tplData($values));
    		exit();
        }
        if($type=='excelG'){
    		$this->outputExcel($cate['pdfc_filename'],$this->tplData($values));
    		exit();
        }
        if($type=='excel2G'){
    		$this->xlsx($cate['pdfc_filename'],$this->tplData($values));
    		exit();
        }
        //dd($options);
        //dd($data);
		//file_put_contents('f:/data.json',json_encode($data));

		$catalog = new \Catalog($options, $values);
		$catalog->run();
		
		//消息记录与在线提醒
		$pdffileUrl = \mvc::$cfg['path']['files'].'/pdf/'.getOpuser().'/'.$filename;

		$msg = [
			'amsg_title'=>'生成PDF电子目录',
			'amsg_body'=> '生成PDF电子目录完成: '.$cate['pdfc_name'],
			'amsg_url'=> $pdffileUrl,
			'amsg_urltitle'=> basename($pdffileUrl),
		];
		$message = new \model\message();
	    $message->send([getOpuser()],$msg);
		socketSendMsg([getOpuser()],$msg);


		//返回到前端
		$this->successJson(['pdffile'=>$pdffileUrl]);
    }
    
    function tplData($data){
        $tplIds = [];
        foreach($data as $tpl=>$item){
            $data[$tpl]['tplid'] = explode('.',$tpl)[1];
            $tplIds[] = $data[$tpl]['tplid'];
        }
		$pdfset = new pdfset();
		$tplRows = $pdfset->getTplRows($tplIds);
		foreach($tplRows as $tplrow){
		    if(in_array($tplrow['pdft_type'],['staticimage','mainindex','modelindex'])){
		        foreach($data as $tpl=>$item){
		            if($item['tplid']==$tplrow['pdftl_id']){
		                unset($data[$tpl]);
		            }
		        }
		    }else{
		        foreach($data as $tpl=>$item){
		            if($item['tplid']==$tplrow['pdftl_id']){
		                $data[$tpl]['name'] = $tplrow['pdftl_name'];
		            }
		        }
		    }
		}
		return $data;
    }
    
    function outputExcel($cateName, $data){
        $filename = '';
		$filename = $cateName.'-'.getOpuser().'-'.date('Y-m-d').'.xlsx';
        $dir = \mvc::$cfg['dir']['files'].'/pdf';
        $path = \mvc::$cfg['path']['files'].'/pdf';
        mkdirs($this->dir);
        foreach($data as $k=>$v){
            $firstArr = $data[$k];
            unset($data[$k]);
            break;
        }
        $sheetData = $this->arr2excelData($firstArr);
        $excel  = new \Vtiful\Kernel\Excel(['path' => $dir]);
        $xlsfile = $excel->fileName($filename);
        $xlsfile->data($sheetData);
        foreach($data as $k=>$v){
            $sheetData = $this->arr2excelData($v);
			$name = strtr($v['name'], ['/'=>'-']);
            $excel->addSheet($name)->data($sheetData);
        }
        $xlsfile->output();
        $excel->close();
        
		//返回到前端
		$this->successJson(['pdffile'=>$path.'/'.$filename]);
    }
    
    function arr2excelData($arr){
        $arr = (isset($arr['value']['value'])) ? $arr['value']['value'] : $arr['value'];
        $data = [];
		if(!is_array($arr)) return $data;
        $regI = 0;
        foreach($arr as $k=>$v){
            if(isset($v['value']) && is_array($v['value']) && !empty($v['value'])){
                 foreach($v['value'] as $ck => $cv){
                    $c = 0; 
                    foreach($v as $gk => $gv){
                        if($gk!='value'){
                            $data[$regI][$c] = $gv; 
                            $c++;
                        }
                    }
                    foreach($cv as $colk => $colv){
                        if(strpos($colv,'.png')!==false){
                            $colv = str_replace('.png','',basename($colv));
                        }
                        $data[$regI][$c] = $colv;
                        $c++;
                    }
                    $regI++;
                 }
            }else if(isset($v['col2']) && is_array($v['col2'])){
                 foreach($v['col2'] as $ck => $cv){
                    $c = 0; 
                    foreach($v as $gk => $gv){
                        if($gk!='col2'){
                            $data[$regI][$c] = $gv; 
                            $c++;
                        }
                    }
                    foreach($cv as $colk => $colv){
                        $data[$regI][$c] = $colv;
                        $c++;
                    }
                    $regI++;
                 }
            }else if(is_array($v) && !empty($v)){
                $c = 0;
                foreach($v as $colk => $colv){
                    $data[$regI][$c] = $colv;
                    $c++;
                }
                $regI++;
            }else{
                $data[$regI++][0] = $v;
            }
        }
        return $data;
    }
    
	function xlsx($cateName, $data){
        ob_end_clean();
        error_reporting(0);
        header('Content-Description: File Transfer');
        header("Content-type:application/vnd.ms-excel");
        header('Content-Disposition: attachment; filename='.$cateName.'.xlsx');
        echo '<?xml version="1.0"?>'.BR;
        echo '<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'.BR;
        foreach($data as $k=>$v){
            $this->outputSheet($this->arr2excelData($v),$v['name']);
        }
        echo '</ss:Workbook>'.BR;
        ob_end_flush();
        exit();
	}
    public function specialchars($value){
        return str_replace('&amp;','&',htmlspecialchars($value));
    }
	
	//输出一个Sheet
	public function outputSheet($data,$sheetName){
        echo '<ss:Worksheet ss:Name="'.$sheetName.'">'.BR;
        echo '<ss:Table>'.BR;
		foreach($data as $row){
            echo '<ss:Row>'.BR;
            foreach($row as $v){
	            echo '<ss:Cell><ss:Data ss:Type="String">'.$this->specialchars($v).'</ss:Data></ss:Cell>'.BR;
		    }
    	    echo '</ss:Row>'.BR;
            flush();
            ob_flush();
		}
        echo '</ss:Table>'.BR;
        echo '</ss:Worksheet>'.BR;
	}
    
}
