<?php

// +----------------------------------------------------------------------
// | JiZhiCMS { 极致CMS，给您极致的建站体验 }  
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2099 http://www.jizhicms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 留恋风 <2581047041@qq.com>
// +----------------------------------------------------------------------
// | Date：2020/03/30
// +----------------------------------------------------------------------


namespace A\plugins;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use A\c\CommonController;
use FrPHP\lib\Controller;
use FrPHP\Extend\Page;
class ExcelController extends CommonController
{



    function import(){
        $filepath = $this->frparam('excel_path',1);

        $excel_style = $this->frparam('excel_style',0,2);
        $excel_molds = $this->frparam('excel_molds',1,'article');
        $excel_molds_biaoshi = $this->frparam('newmolds',1);
        $molds_name = $this->frparam('molds_name',1);
        if($filepath==''){
            Error('请上传Excel文件');
        }
        extendFile('excel/vendor/autoload.php');
        $spreadsheet = IOFactory::load(APP_PATH.$filepath);
        $worksheet = $spreadsheet->getActiveSheet();



        /*取图片*/
        $imgData=array();

        if(isset($this->webconf['admin_save_path'])){
            //替换日期事件
            $t = time();
            $d = explode('-', date("Y-y-m-d-H-i-s"));
            $format = $this->webconf['admin_save_path'];
            $format = str_replace("{yyyy}", $d[0], $format);
            $format = str_replace("{yy}", $d[1], $format);
            $format = str_replace("{mm}", $d[2], $format);
            $format = str_replace("{dd}", $d[3], $format);
            $format = str_replace("{hh}", $d[4], $format);
            $format = str_replace("{ii}", $d[5], $format);
            $format = str_replace("{ss}", $d[6], $format);
            $format = str_replace("{time}", $t, $format);
            if($format!=''){
                //检查文件是否存在
                if(strpos($format,'/')!==false && !file_exists(APP_PATH.$format)){
                    $path = explode('/',$format);
                    $path1 = APP_PATH;
                    foreach($path as $v){
                        if($path1==APP_PATH){
                            if(!file_exists($path1.$v)){
                                mkdir($path1.$v,0777);
                            }
                            $path1.=$v;
                        }else{
                            if(!file_exists($path1.'/'.$v)){
                                mkdir($path1.'/'.$v,0777);
                            }
                            $path1.='/'.$v;
                        }
                    }
                }else if(!file_exists(APP_PATH.$format)){
                    mkdir(APP_PATH.$format,0777);
                }
                $admin_save_path = $format;

            }else{
                $admin_save_path = 'public/Admin';
            }


        }else{
            $admin_save_path = 'public/Admin';
        }

        $imageFilePath=$admin_save_path.'/';//图片保存目录


        // 处理图片
        $images = $worksheet->getDrawingCollection();

        $imagePaths = []; // 用于保存图片路径的数组

        foreach ($images as $image) {
            if ($image instanceof Drawing) {
                $filename = $image->getPath();
                $extension = $image->getExtension();
                $imageData = $image->getImageData();

                // 处理图片数据
                // 可以将图片保存到本地文件或进行其他操作
                // 例如：保存图片到本地
                $imagePath = $imageFilePath . uniqid() . '.' . $extension;
                file_put_contents($imagePath, $imageData);

                // 将图片路径保存到数组
                $imagePaths[] = '/'.$imagePath;
            }
        }

        // 处理数据
        $data = [];

        foreach ($worksheet->getRowIterator() as $row) {
            $rowData = [];

            foreach ($row->getCellIterator() as $cell) {
                $cellValue = $cell->getValue();

                // 如果单元格包含图片，使用缓存的图片地址
                if ($cellValue instanceof Drawing) {
                    $imageIndex = $cellValue->getParent()->getIndex($cellValue);
                    $imagePath = $imagePaths[$imageIndex];
                    $rowData[] = $imagePath;
                } else {
                    $rowData[] = $cellValue;
                }
            }

            $data[] = $rowData;
        }


        //循环读取excel文件
        $table = array_shift($data);//表头
        $fields = [];//字段
        $exceldata = $data;
        if($excel_style==2){
            $fields = array_shift($exceldata);

        }

        setCache('excel_import_data',$exceldata);
        setCache('excel_import_fields',$fields);
        setCache('excel_import_table',$table);
        setCache('excel_molds',$excel_molds);
        setCache('excel_molds_biaoshi',$excel_molds_biaoshi);
        setCache('excel_molds_name',$molds_name);
        $this->molds = $excel_molds;
        $this->molds_name = $molds_name;
        $this->excel_molds_biaoshi = $excel_molds_biaoshi;
        $this->fields = $fields;
        $this->table = $table;
        if($excel_molds=='newmolds'){

            if($molds_name=='' || $excel_molds_biaoshi==''){
                Error('模块名和标识不能为空');
            }

            $sql = "SHOW TABLES";
            $tables = M()->findSql($sql);
            $ttable = array();
            foreach($tables as $value){
                foreach($value as $vv){
                    $ttable[] = $vv;
                }

            }
            $excel_molds_biaoshi = strtolower($excel_molds_biaoshi);
            //JsonReturn(array('code'=>1,'msg'=>$ttable));
            if(in_array(DB_PREFIX.$excel_molds_biaoshi,$ttable)){

                Error('新创建的模块已存在！');
            }
            //检测是否存在该模块
            if(M('Molds')->find(array('biaoshi'=>$excel_molds_biaoshi))){

                Error('新创建的模块已存在！');
            }

            $n = M('Molds')->add(array('name'=>$molds_name,'biaoshi'=>$excel_molds_biaoshi));
            if($n){
                if(defined('DB_TYPE') && DB_TYPE=='sqlite'){
                    $sql = "CREATE TABLE IF NOT EXISTS `".DB_PREFIX.$excel_molds_biaoshi."` (
					`id` INTEGER PRIMARY KEY AUTOINCREMENT,
					`tid` int(11) DEFAULT 0,
					`tids` varchar(255) DEFAULT NULL ,
					`title` varchar(255) DEFAULT NULL ,
					`litpic` varchar(255) DEFAULT NULL ,
					`keywords` varchar(255) DEFAULT NULL ,
					`description` varchar(500) DEFAULT NULL ,
					`body` text DEFAULT NULL ,
					`molds` varchar(50) DEFAULT '".$excel_molds_biaoshi."',
					`userid` int(11) DEFAULT 0,
					`orders` int(11) DEFAULT 0,
					`member_id` int(11) DEFAULT 0,
					`comment_num` int(11) DEFAULT 0,
					`htmlurl` varchar(100) DEFAULT NULL ,
					`isshow` tinyint(1) DEFAULT 1 ,
					`target` varchar(255) DEFAULT NULL,
					`ownurl` varchar(255) DEFAULT NULL ,
					`jzattr` tinyint(2) DEFAULT 0 ,
					`hits` int(11) DEFAULT 0 ,
					`zan` int(11) DEFAULT 0 ,
					`tags` varchar(255) DEFAULT NULL ,
					`addtime` int(11) DEFAULT 0 
					) ";
                }else{
                    $sql = "CREATE TABLE IF NOT EXISTS `".DB_PREFIX.$excel_molds_biaoshi."` (
					`id` int(11) unsigned NOT NULL auto_increment,
					`tid` int(11) DEFAULT 0 COMMENT '所属栏目',
					`tids` varchar(255) DEFAULT NULL COMMENT '副栏目',
					`title` varchar(255) DEFAULT NULL COMMENT '标题',
					`litpic` varchar(255) DEFAULT NULL COMMENT '缩略图',
					`keywords` varchar(255) DEFAULT NULL COMMENT '关键词',
					`description` varchar(500) DEFAULT NULL COMMENT '简介',
					`body` text DEFAULT NULL COMMENT '内容',
					`molds` varchar(50) DEFAULT '".$excel_molds_biaoshi."' COMMENT '模型标识',
					`userid` int(11) DEFAULT 0 COMMENT '发布管理员',
					`orders` int(11) DEFAULT 0 COMMENT '排序',
					`member_id` int(11) DEFAULT 0 COMMENT '前台用户',
					`comment_num` int(11) DEFAULT 0 COMMENT '评论数',
					`htmlurl` varchar(100) DEFAULT NULL COMMENT '栏目链接',
					`isshow` tinyint(1) DEFAULT 1 COMMENT '是否显示',
					`target` varchar(255) DEFAULT NULL COMMENT '外链',
					`ownurl` varchar(255) DEFAULT NULL COMMENT '自定义URL',
					`jzattr` tinyint(2) DEFAULT 0 COMMENT '推荐属性',
					`hits` int(11) DEFAULT 0 COMMENT '点击量',
					`zan` int(11) DEFAULT 0 COMMENT '点赞数',
					`tags` varchar(255) DEFAULT NULL COMMENT 'TAG',
					`addtime` int(11) DEFAULT 0 COMMENT '发布时间',
				PRIMARY 
				KEY  (`id`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
                }


                $x = M()->runSql($sql);
                //添加权限管理

                $data['biaoshi'] = $excel_molds_biaoshi;
                $w['field'] = 'title';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '标题';
                $w['tips'] = '默认为空';
                $w['fieldtype'] = 1;
                $w['fieldlong'] = 255;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 1;
                $w['islist'] = 1;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'tid';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '所属栏目';
                $w['tips'] = '选择栏目';
                $w['fieldtype'] = 17;
                $w['fieldlong'] = 11;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 1;
                $w['islist'] = 1;
                $w['vdata'] = 0;
                M('fields')->add($w);
                $w['field'] = 'tids';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '副栏目';
                $w['tips'] = '绑定后可以在当前模型的其他栏目中显示';
                $w['fieldtype'] = 18;
                $w['fieldlong'] = 255;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'keywords';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '关键词';
                $w['tips'] = '每个词用英文逗号(,)拼接';
                $w['fieldtype'] = 1;
                $w['fieldlong'] = 255;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'tags';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = 'TAG';
                $w['tips'] = '每个词用英文逗号(,)拼接';
                $w['fieldtype'] = 19;
                $w['fieldlong'] = 255;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'litpic';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '缩略图';
                $w['tips'] = '可留空';
                $w['fieldtype'] = 5;
                $w['fieldlong'] = 255;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 1;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'description';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '简介';
                $w['tips'] = '可留空';
                $w['fieldtype'] = 2;
                $w['fieldlong'] = 500;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'body';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '内容';
                $w['tips'] = '可留空';
                $w['fieldtype'] = 3;
                $w['fieldlong'] = 500;
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'member_id';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '发布会员';
                $w['tips'] = '前台发布会员ID记录';
                $w['fieldtype'] = 13;
                $w['fieldlong'] = 11;
                $w['body'] = '3,username';
                $w['ismust'] = 0;
                $w['isshow'] = 0;
                $w['isadmin'] = 0;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $w['field'] = 'userid';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '管理员';
                $w['tips'] = '后台发布管理员ID记录';
                $w['fieldtype'] = 13;
                $w['fieldlong'] = 11;
                $w['body'] = '11,name';
                $w['ismust'] = 0;
                $w['isshow'] = 0;
                $w['isadmin'] = 0;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $w['field'] = 'target';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '外链URL';
                $w['tips'] = '默认为空，系统访问内容则直接跳转到此链接';
                $w['fieldtype'] = 1;
                $w['fieldlong'] = 255;
                $w['ismust'] = 0;
                $w['isshow'] = 0;
                $w['isadmin'] = 0;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'ownurl';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '自定义URL';
                $w['tips'] = '默认为空，自定义URL';
                $w['fieldtype'] = 1;
                $w['fieldlong'] = 255;
                $w['ismust'] = 0;
                $w['isshow'] = 0;
                $w['isadmin'] = 0;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '';
                M('fields')->add($w);
                $w['field'] = 'hits';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '点击量';
                $w['tips'] = '系统自动添加';
                $w['fieldtype'] = 4;
                $w['fieldlong'] = 11;
                $w['body'] = '';
                $w['ismust'] = 0;
                $w['isshow'] = 0;
                $w['isadmin'] = 0;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $w['field'] = 'comment_num';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '评论数';
                $w['tips'] = '系统自带';
                $w['fieldtype'] = 4;
                $w['fieldlong'] = 11;
                $w['body'] = '';
                $w['ismust'] = 0;
                $w['isshow'] = 0;
                $w['isadmin'] = 0;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $w['field'] = 'zan';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '点赞数';
                $w['tips'] = '系统自带';
                $w['fieldtype'] = 4;
                $w['fieldlong'] = 11;
                $w['body'] = '';
                $w['ismust'] = 0;
                $w['isshow'] = 0;
                $w['isadmin'] = 0;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $w['field'] = 'orders';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '排序';
                $w['tips'] = '系统自带';
                $w['fieldtype'] = 4;
                $w['fieldlong'] = 11;
                $w['body'] = '';
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 1;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $w['field'] = 'addtime';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '添加时间';
                $w['tips'] = '选择时间';
                $w['fieldtype'] = 11;
                $w['fieldlong'] = 11;
                $w['format'] = 'date_2';
                $w['body'] = '';
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 1;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $id = M('molds')->getField(['biaoshi'=>'attr'],'id');
                $w['field'] = 'jzattr';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '推荐属性';
                $w['tips'] = '1置顶2热点3推荐';
                $w['fieldtype'] = 16;
                $w['fieldlong'] = 50;
                $w['format'] = NULL;
                $w['body'] = $id.',name';
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 0;
                $w['islist'] = 0;
                $w['vdata'] = '0';
                M('fields')->add($w);
                $w['field'] = 'isshow';
                $w['molds'] = $data['biaoshi'];
                $w['fieldname'] = '是否显示';
                $w['tips'] = '显示隐藏';
                $w['fieldtype'] = 7;
                $w['fieldlong'] = 1;
                $w['format'] = NULL;
                $w['body'] = '显示=1,未审=0,退回=2';
                $w['ismust'] = 0;
                $w['isshow'] = 1;
                $w['isadmin'] = 1;
                $w['issearch'] = 1;
                $w['islist'] = 1;
                $w['vdata'] = 1;
                M('fields')->add($w);
                $data['name'] = $molds_name;
                //添加权限管理
                if(strlen($data['name'])>12){
                    $ruler['name'] = $data['name'];
                }else{
                    $ruler['name'] = $data['name'].'列表';
                }

                $ruler['fc'] = 'Extmolds/index/molds/'.$data['biaoshi'];
                $ruler['pid'] = 77;
                $ruler['isdesktop'] = 1;
                $m_id = M('Ruler')->add($ruler);
                $ruler['isdesktop'] = 0;
                $ruler['name'] = '新增'.$data['name'];
                $ruler['fc'] = 'Extmolds/addmolds/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                $ruler['name'] = '修改'.$data['name'];
                $ruler['fc'] = 'Extmolds/editmolds/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                $ruler['name'] = '复制'.$data['name'];
                $ruler['fc'] = 'Extmolds/copymolds/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                $ruler['name'] = '删除'.$data['name'];
                $ruler['fc'] = 'Extmolds/deletemolds/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                $ruler['name'] = '批量删除'.$data['name'];
                $ruler['fc'] = 'Extmolds/deleteAll/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                $ruler['name'] = '批量修改'.$data['name'].'栏目';
                $ruler['fc'] = 'Extmolds/changeType/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                $ruler['name'] = '批量复制'.$data['name'];
                $ruler['fc'] = 'Extmolds/copyAll/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                if(strlen($data['name'])>12){
                    $ruler['name'] = '批量修改'.$data['name'];
                }else{
                    $ruler['name'] = '批量修改'.$data['name'].'列表';
                }

                $ruler['fc'] = 'Extmolds/editOrders/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);
                $ruler['name'] = '批量审核'.$data['name'];
                $ruler['fc'] = 'Extmolds/checkAll/molds/'.$data['biaoshi'];
                M('Ruler')->add($ruler);


                //写入左侧导航栏
                $this->admin = $_SESSION['admin'];
                $desktop = M('Layout')->find(array('gid'=>$_SESSION['admin']['gid']));
                if(!$desktop){
                    $desktop = M('Layout')->find(array('isdefault'=>1));
                }

                $left_layout = json_decode($desktop['left_layout'],1);
                $left_layout[]=[
                    "name" => $molds_name.'模块',
                    "icon" => '&amp;#xe6cb;',
                    "nav" => array($m_id)
                ];
                $left_layout = json_encode($left_layout,JSON_UNESCAPED_UNICODE);
                M('layout')->update(['id'=>$desktop['id']],['left_layout'=>$left_layout]);



            }else{
                //Error('添加失败！');
                Error('新创建的模块失败！');

            }

            $this->field_exits = ['id','tid','userid','jzattr','orders','member_id','comment_num','htmlurl','isshow','tags','title','body','description','keywords','tids','zan','molds','target','ownurl'];



        }else{
            if(defined('DB_TYPE') && DB_TYPE=='sqlite'){
                //sqlite
                $sql="pragma table_info(".DB_PREFIX.$excel_molds.")";
                $data = M($excel_molds)->findSql($sql);
                $allow = [];
                foreach($data as $v){
                    $allow[] = $v['name'];

                }
            }else{
                //$sql="select COLUMN_NAME from information_schema.COLUMNS where table_name = '".DB_PREFIX.$molds."' and table_schema = '".DB_PREFIX.$molds."';";
                $sql = "SHOW FULL COLUMNS FROM ".DB_PREFIX.$excel_molds;
                $data = M($excel_molds)->findSql($sql);
                $allow = [];
                foreach($data as $v){
                    $allow[] = $v['Field'];

                }
            }
            $this->allowfields = $allow;
        }

        $this->display('excel-index');



    }
	
	function importover(){
		$molds = $this->frparam('molds',1);
		$fields = $this->frparam('fields',2);
		$table = $this->frparam('title',2);
		$fieldstype = $this->frparam('fieldstype',2);
		$exceldata = getCache('excel_import_data');
		if($molds!='newmolds'){
			
			//$fields = getCache('excel_import_fields');
			//$table = getCache('excel_import_table');
			
			
			//循环输出每行数据
			foreach($exceldata as $k=>$v){
				//循环输出每个数据
				$insert = [];
				foreach($v as $kk=>$vv){
					$f = strtolower($fields[$kk]);
					if($f!='id'){
						switch($fieldstype[$kk]){
							case 3:
								$insert[$f] = format_param($vv,4);
							break;
							case 6:
								$insert[$f] =  stripos($vv,'-')!==false ? strtotime($vv) : ($vv - 25569) * 86400;
							break;
							default:
								$insert[$f] = $vv;
							break;
						}
						
					}
					if($f=='tid'){
						$insert['htmlurl'] = $this->classtypedata[$vv]['htmlurl'];
					}
				}
				M($molds)->add($insert);
				$insert = null;
				
				
			}
			
			
			$id = M('plugins')->getField(['filepath'=>'jzexcel'],'id');
			Success('导入成功！',U('plugins/setconf',['id'=>$id]));
			
		}else{
			$excel_molds_biaoshi = $this->frparam('excel_molds_biaoshi',1);
			//创建新模块字段
			$field_exits = ['id','tid','userid','jzattr','orders','member_id','comment_num','htmlurl','isshow','tags','title','body','description','keywords','tids','zan','molds','target','ownurl'];
			
			$sql='';
			$insertarray = [];
			
			foreach($fields as $k=>$v){
				$v = strtolower($v);
				if($v!='id'){
					
					if(!in_array($v,$field_exits)){
						
						switch($fieldstype[$k]){
							case 1:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." VARCHAR(255)   default NULL; ";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>1,'fieldlong'=>255,'ismust'=>0,'islist'=>1]);
							break;
							case 2:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." VARCHAR(500)   default NULL; ";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>2,'fieldlong'=>500,'ismust'=>0,'islist'=>1]);
							break;
							case 3:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." TEXT   default NULL; ";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>3,'fieldlong'=>255,'ismust'=>0,'islist'=>1]);
							break;
							case 4:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." INT(11)   default 0; ";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>4,'fieldlong'=>11,'ismust'=>0,'islist'=>1]);
							break;
							case 5:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." VARCHAR(255)   default NULL; ";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>5,'fieldlong'=>255,'ismust'=>0,'islist'=>1]);
							break;
							case 6:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." INT(11)   default 0 ;";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>11,'fieldlong'=>11,'ismust'=>0,'islist'=>1]);
							break;
							case 7:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." INT(11)   default 0 ;";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>11,'fieldlong'=>11,'ismust'=>0,'islist'=>1]);
							break;
							case 8:
							$sql .= "ALTER TABLE ".DB_PREFIX.$excel_molds_biaoshi." ADD ".$v." VARCHAR(255)   default NULL ;";
							M('fields')->add(['field'=>$v,'molds'=>$excel_molds_biaoshi,'fieldname'=>$table[$k],'fieldtype'=>9,'fieldlong'=>255,'ismust'=>0,'islist'=>1]);
							break;
						}
						
					}
				}
				
				
				
			}
			M()->runSql($sql);
			
		
			
			//循环输出每行数据
			foreach($exceldata as $k=>$v){
				//循环输出每个数据
				$insert = [];
				foreach($v as $kk=>$vv){
					$f = strtolower($fields[$kk]);
					if($f!='id'){
						switch($fieldstype[$kk]){
						case 6:
							$insert[$f] = strtotime($vv);
						break;
						default:
							$insert[$f] = $vv;
						break;
						}
						
					}
					if($f=='tid'){
						$insert['htmlurl'] = $this->classtypedata[$vv]['htmlurl'];
					}
				}
				M($excel_molds_biaoshi)->add($insert);
				$insert = null;
				
				
			}
			$id = M('plugins')->getField(['filepath'=>'jzexcel'],'id');
			Success('导入成功！',U('plugins/setconf',['id'=>$id]));
			
		}
		
		
	}
	
	//导出
	function output(){
		$output_molds = $this->frparam('output_molds',1);
		if(defined('DB_TYPE') && DB_TYPE=='sqlite'){
			//sqlite
			$sql="pragma table_info(".DB_PREFIX.$output_molds.")";
			$data = M($output_molds)->findSql($sql);
			$allow = [];
			foreach($data as $v){
				$allow[] = $v['name'];
				
			}
		}else{
			//$sql="select COLUMN_NAME from information_schema.COLUMNS where table_name = '".DB_PREFIX.$molds."' and table_schema = '".DB_PREFIX.$molds."';";
			$sql = "SHOW FULL COLUMNS FROM ".DB_PREFIX.$output_molds;
			$data = M($output_molds)->findSql($sql);
			$allow = [];
			foreach($data as $v){
				$allow[] = $v['Field'];
				
			}
		}
		$this->allowfields = $allow;
		$this->output_molds = $output_molds;
		
		$this->display('excel-output');
	}

    function outputover(){
        $molds = $this->frparam('molds',1);
        $fields = $this->frparam('fields',2);
        $table = $this->frparam('title',2);
        $fieldstype = $this->frparam('fieldstype',2);
        $f = implode(',',$fields);

        $count = count($fields);

        extendFile('excel/vendor/autoload.php');

        $spreadsheet = new Spreadsheet();
        //设置表头
        $spreadsheet->setActiveSheetIndex(0);
        //Excel表格式--根据你要到处的字段来定
        $letter_array = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        for($i=0;$i<$count;$i++){
            if($i<26){
                $letter[] = $letter_array[$i];
            }else if($i<52){
                $letter[] = 'A'.$letter_array[$i-26];
            }else{
                $letter[] = 'B'.$letter_array[$i-52];
            }

        }
        $classtypedata = classTypeData();
        foreach($classtypedata as $k=>$v){
            $classtypedata[$k]['children'] = get_children($v,$classtypedata);
        }
        //表头数组
        $tableheader = $table;
        //填充表头信息
        for($i = 0;$i < count($tableheader);$i++) {
            $spreadsheet->setActiveSheetIndex(0)->setCellValue("$letter[$i]1","$tableheader[$i]");
            $spreadsheet->setActiveSheetIndex(0)->getStyle("$letter[$i]1")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        }
        //查询数据
        $sql=" select ".$f." from ".DB_PREFIX.$molds." where 1=1 ;";
        $data=M($molds)->findSql($sql);//这个是系统的查询方法
        $sheet = $spreadsheet->getActiveSheet();
        $row = 2;
        for ($i = 2;$i <= count($data) + 1;$i++) {
            /**
            <option value="1">文本</option>
            <option value="2">图片</option>
            <option value="3">图集</option>
            <option value="13">栏目tid</option>
            <option value="4">时间(年/月/日)</option>
            <option value="14">时间(年/月/日 H:i:s)</option>
            <option value="5">时间戳(一串数字)</option>
            <option value="6">附件</option>
            <option value="7">单选</option>
            <option value="8">多选</option>
            <option value="9">1是0否</option>
            <option value="10">0是1否</option>
            <option value="11">1是2否</option>
            <option value="12">1否2是</option>


             */
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value) {

                $key1 = array_search($key,$fields);
                switch($fieldstype[$key1]){
                    case 1:
                    case 5:
                        //$excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                        // 设置普通单元格数据
                        $sheet->setCellValue("$letter[$j]$i", $value);
                        break;
                    case 3:
                        if($value){
                            $value = explode('||',$value);
                            $s = [];
                            foreach($value as $vv){
                                if(strpos($vv,'http')!==false){
                                    $s[]=$vv;
                                }else{
                                    $s[]=get_domain().$vv;
                                }
                            }
                            $value = implode(',',$s);
                        }
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;

                    case 2:
                        if($value){
                            if(strpos($value,'http')!==false){
                                $image = $value;
                            }else if(file_exists('.'.$value)){
                                $image = '.'.$value;

                            }

                            $drawing = new Drawing();
                            $drawing->setName('Image');
                            $drawing->setDescription('Image');
                            $drawing->setPath($image);
                            $drawing->setWidth(15);
                            $drawing->setHeight(50);
                            $drawing->setCoordinates($letter[$j] . $i); // 图片插入的单元格
                            $drawing->setWorksheet($sheet);

                        }

                        break;
                    case 15:
                        if($value){
                            $value = strpos($value,'http')!==false ? $value : get_domain().$value;
                        }

                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 4:
                        $value = date('Y年m月d日',$value);
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 14:
                        $value = date('Y年m月d日 H:i:s',$value);
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;

                    case 6:
                        if(strpos($value,'http')===false){
                            $value = get_domain().$value;
                        }
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 7:
                        $value = get_key_field_select($value,$molds,$key);
                        $$sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 8:
                        $value = get_key_field_select($value,$molds,$key);
                        $value = implode(',',$value);
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 9:
                        $value = $value==1?'是':'否';
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 9:
                    case 11:
                        $value = $value==1?'是':'否';
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 10:
                    case 12:
                        $value = $value==1?'否':'是';
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;
                    case 13:
                        $value = $classtypedata[$value]['classname'];
                        $sheet->setCellValue("$letter[$j]$i","$value");
                        break;

                }

                // 设置单元格宽度
                $sheet->getColumnDimensionByColumn($j)->setWidth(15);

                $j++;
            }
            $sheet->getRowDimension($i)->setRowHeight(50);
        }

        //创建Excel输入对象，这里指定生成Excel5
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $excelname=time();//设置导出的Excel表名
        $filename = APP_PATH.'cache/'.$excelname.'.xlsx';
        $writer->save($filename);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
        header('Cache-Control: max-age=0');
        header('Expires: 0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        readfile($filename);



    }






}