<?php
namespace app\admin\controller\csmtable;

use addons\csmtable\library\xcore\xcore\base\XcABackend;
use addons\csmtable\library\xapp\csmtable\utils\CsmTableUtils;
 

class Csmgenerate extends XcABackend
{
    
    public function _initialize()
    {
        parent::_initialize();
    }

    public function generate()
    {
        set_time_limit(0);
        $request = $this->request;
        $filesource = $request->request('csmtable_filesource');
        $indexurl = $request->request('csmtable_indexurl');

        $dao = new \app\admin\model\csmtable\Xlstask();
        // 限制下载
        if (true) {
            $userinfo = $this->auth->getUserInfo();
 
            $adminId = $userinfo["id"];
            $row = $dao->where("admin_id", "=", $adminId)
                ->where("progress", "<", "100")
                ->where("createtime", ">", time() - 1800)
                ->where("iserror", "<>", "Y")
                ->find();
            if ($row) {
                $this->error("当前有下载任务，请任务结束后再尝试下载。");
            }
        }

        // 生成任务记录
        $dao->where("admin_id", "=", $adminId)
            ->where("filesource", '=', $filesource)
            ->where("status", "=", "normal")
            ->update([
            "status" => "hidden"
        ]);

        // 触发异步生成Excel任务
        $route2 = CsmTableUtils::getInstanceAndMethod($indexurl);
        $classname = $route2[0];

        $getparams = [
            'search' => $request->request('search'),
            'filter' => $request->request('filter'),
            'op' => $request->request('op'),
            'sort' => $request->request('sort'),
            'order' => $request->request('order'),
            'offset' => $request->request('offset'),
            'limit' => $request->request('limit'),
            'csmtable_classname' => str_replace('\\', '/', $classname),
            'csmtable_methodname' => $route2[1],
            'csmtable_columns' => $request->request('csmtable_columns')
        ];

 
        $param = [
            'admin_id' => $adminId,
            'filesource' => $filesource,
            'param' => json_encode($getparams),
            'createtime' => time(),
 
        ];
        $dao->create($param);
        $this->success();
        
        // $id = $dao->getLastInsID();

        // $ret = $this->_index($id);
        // if($ret===true){
        //     $this->success();
        // }else{
        //     $this->error($ret);
        // }
    }

 
   
 
}
