<?php
class commonModule extends Model
{
    /**
     * Notice: uedit 上传入口
     * Date: 2019/4/15
     * Time: 19:57
     * @author dongdong
     */
        public function upload()
        {
            //header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
            //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
            date_default_timezone_set("Asia/chongqing");
            error_reporting(E_ERROR);
            header("Content-Type: text/html; charset=utf-8");

            $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(LIB_PATH."Uedit/config.json")), true);
            $action = $_GET['action'];

            switch ($action) {
                case 'config':
                    $result =  json_encode($CONFIG);
                    break;

                /* 上传图片 */
                case 'uploadimage':
                    /* 上传涂鸦 */
                case 'uploadscrawl':
                    /* 上传视频 */
                case 'uploadvideo':
                    /* 上传文件 */
                case 'uploadfile':
                    $result = include(LIB_PATH."Uedit/action_upload.php");
                    break;

                /* 列出图片 */
                case 'listimage':
                    $result = include(LIB_PATH."Uedit/action_list.php");
                    break;
                /* 列出文件 */
                case 'listfile':
                    $result = include(LIB_PATH."Uedit/action_list.php");
                    break;

                /* 抓取远程文件 */
                case 'catchimage':
                    $result = include(LIB_PATH."Uedit/action_crawler.php");
                    break;

                default:
                    $result = json_encode(array(
                        'state'=> '请求地址出错'
                    ));
                    break;
            }

            /* 输出结果 */
            if (isset($_GET["callback"])) {
                if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                    echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
                } else {
                    echo json_encode(array(
                        'state'=> 'callback参数不合法'
                    ));
                }
            } else {
                echo $result;
            }
        }


    //导出excel old
    public function exportexcelBytableidAction(){
        $table_id= $this->common->Get("table_id");
        $type= $this->common->Get("type");
        if($table_id=="")
        {
            echo "table_id不能为空";die();
        }
        //引用导出excel文件的类
        $this->library("Excel");
        $excel = new Excel();
        $filedModel = new filedModel();
        $tableModel = new tableModel();

        $table_detail = $tableModel->findOne($table_id);
        $excelName = $table_detail["u2"];
        $exceltabName = $table_detail["u1"];
        $excelData=array();
        $excelHeaderstr=["编号"];

        $_tableModel = new Model($exceltabName);//具体的某一张表

        $filedexprotList = $filedModel->getexportfiledByTableid($table_id);
        $filedexprotstr="id";
        $excelHeaderstr_muban=[];
        foreach ($filedexprotList as $k=>$v){
            $excelHeaderstr[$k+1] =$v["u2"];
            $filedexprotstr .=",".$v["u1"];
            $excelHeaderstr_muban[] = $v["u2"];
        }
        if($type=="muban"){

            $excel->export($excelName."导入模版",'',$excelHeaderstr_muban, [], "");
        }



        //var_dump($excelHeaderstr);die();
        $excelData = $_tableModel->find($filedexprotstr)->all();

        //处理每一行数据的控件数据
        //挂载控件类
        $this->library("Component");
        $ComponentClass = new Component();
        foreach ($filedexprotList as $v)
        {
            //处理不同字段的显示数据
            foreach ($excelData as $k1=>$v1) {
                $v1[$v['u1']] =$ComponentClass->showKj($v['u7'],$v['u2'],$v['u1'] ,$v1[$v['u1']],$v['u3'] ,$v['id']) ;
                $excelData[$k1]=$v1;
            }
        }


        $excel->export($exceltabName,$excelName,$excelHeaderstr, $excelData, "");


    }

    /**
     * Notice: uedit 上传入口
     * Date: 2019年9月12日16:06:06
     * param:$limit:每次多少条,head:表头【】array:
     * @author dyj
     */
    /**
     * Notice: uedit 上传入口
     * Date: 2019年9月12日16:06:06
     * param:$limit:每次多少条,head:表头【】array:
     * @author dyj
     */
    public function export($head=[],$filed="",$total=0,$table_name="",$limit=50000){
        header("Content-type: text/html; charset=utf-8");

        header('Content-Type: application/vnd.ms-excel');

        header('Cache-Control: max-age=0');
        $this->library("ExcelExport");
        $table= new Model($table_name);
        // $ExcelExport=new ExcelExport();
        $filename = $table_name;
        $filter = [];
        $dir=PUBLIC_PATH."/tmpdir/";

        $excelObj = (new ExcelExport())->tmpdir($dir)->filename($filename)->title($head)->filter($filter);

        for ($i=1; $i <= ceil($total/$limit); $i++) { //分段查询
            $offset = ($i-1) * $limit;
            $list = $table->limit($offset,$limit)->find($filed)->all();
            $res = $excelObj->excel($list, $i); //生成多个文件时的文件名后面会标注'（$i+1）'

        }

        $excelObj->fileload();


    }

    //获取所有需要导出得字段 组装表头和查询字段；
    public function getFieled($tableid=0){
        $field =(new filedModule())->where(" model_id={$tableid} and u16='是'")->all();
        $table= new Model("table");
        $table_name=$table->where("id={$tableid}")->find("u1")->one();
        $table_name=$table_name['u1'];

        $head=[];
        $filed=[];
        foreach ($field as $key=>$val){
            $head[$val['u1']]=$val['u2'];
            $filed[]=$val['u1'];
        }
        $str=implode(',',$filed);
        $data['head']=$head;
        $data['filed']=$str;
        $sql="SELECT COUNT(*) as num FROM {$table_name} ";
        $num=$this->findBySql($sql);
        $data['total']=$num[0]['num'];
        $table_name= substr($table_name, 3);
        $data['table_name']=$table_name;

        return $data;

    }
    //引入工具类模型方法
    public function library($lib){
        include_once LIB_PATH . "{$lib}.class.php";
    }

    //根据token获取用户信息
    public function getUserInfoByToken(){
        $token = GetHeader();
        $tokenArray = unserialize($this->common->decryptByqingmiphp($token));
        $user_info = (new userModule())->getUserInfoByNumber($tokenArray["user_info"]["number"]);
        return $user_info;
    }

    //获取所有信息
    public function getAllBySort($where = ""){
        $data = $this->where($where)->orderBy("sort desc,id desc")->all();
        return $data;
    }

    //根据条件查询某条信息
    public function getOneByWhere($where){
        $data = $this->where($where)->one();
        return $data;
    }

}