<?php
/**
 * ===========================================================================
 * Veitool 快捷开发框架系统
 * Author: Niaho 26843818@qq.com
 * Copyright (c)2020-2022 www.veitool.com All rights reserved.
 * Licensed: 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
 * ---------------------------------------------------------------------------
 */
namespace addons\build\controller;

use addons\build\tool\Build;
use think\facade\Db;
use think\Exception;
use app\admin\controller\AdminBase;

/**
 * 构建工控制器
 */
class Index extends AdminBase
{
    /**
     * 构建类型
     * @var array
     */
    private $Types = ['controller'=>"控制器类",'model'=>"模型类",'command'=>"指令类",'validate'=>"验证器类",'middleware'=>"中间件类",'event'=>"事件类",'listener'=>"监听器类",'subscribe'=>"订阅者类",'service'=>"系统服务类"];

    /**
     * 构建记录
     * @param  string  $do  异步数据
     * @return mixed
     */
    public function index(string $do = '')
    {
        if($do=='json'){
            $where = [];
            $d = $this->request->get('','','strip_sql');
            $kw = $d['kw'] ?? '';
            $fds = ['note','username','ip'];
            $field = isset($d['fields']) && isset($fds[$d['fields']]) ? $d['fields'] : -1;
            $sotime = $d['sotime'] ?? '';
            $type  = $d['type'] ?? '';
            $state = $d['state'] ?? '';
            $limit = isset($d['limit']) ? intval($d['limit']) : 10;
            if($kw!=''){
                if($field>-1){
                    $where[] = $field>1 ? [$fds[$field],'LIKE', '%'.$kw.'%'] : [$fds[$field],'=',$kw];
                }else{
                    $where[] = [implode('|',$fds),'LIKE', '%'.$kw.'%'];
                }
            }
            if(strpos($sotime,' - ')!==false){
                $t = explode(' - ',$sotime);
                $where[] = ['logtime','>=',strtotime($t[0]." 00:00:00")];
                $where[] = ['logtime','<=',strtotime($t[1]." 23:59:59")];
            }
            if($type) $where[] = ['type','=',$type];
            if(is_numeric($state)) $where[] = ['state','=',$state];
            return $this->returnMsg(Db::name("build_local")->where($where)->order(['id'=>'desc'])->field("*")->paginate($limit));
        }
        $this->assign([
            'limit'=>10,
            'Types'=> json_encode($this->Types)
        ]);
        return $this->fetch();
    }

    /**
     * 在线构建 php think make:controller admin@Veitool --admin
     * @return mixed
     */
    public function add()
    {
        $d = $this->request->post();
        $content = $d['content'] ?? '';
        if(!$content) return $this->returnMsg("请选择构建命令");
        $cou = [0,0];
        //$make = new \think\Console($this->app);
        try{
            $darr = explode("\n", $content);
            foreach($darr as $str){
                // 多空格替换为1个空格
                $str = preg_replace("/\s+/",' ',$str);
                $rs = explode(' ', $str);
                $type = substr($rs[2],5);
                $arr = [];
                $arr[0] = $rs[3] ?? '';
                if(isset($rs[4]) && $rs[4]){$arr[1] = $rs[4];}
                if(in_array($type,['controller','model'])){$arr['remarks'] = $d['note'] ?? '';}
                // 开始构建
                //$info  = $make->call($rs[2], $arr)->fetch();
                $info  = $this->app->console->call($rs[2], $arr)->fetch();
                $state = strstr($info,'<error>')===false ? 1 : 0;
                $cou[$state] ++;
                // 创建日志
                Db::name('build_local')->insert([
                    "username" => $this->manUser['username'],
                    "type"     => $type,
                    "note"     => $info,
                    "state"    => $state,
                    "ip"       => $this->request->ip(),
                    "logtime"  => time()
                ]);
            }
        }catch(Exception $e){
            return $this->returnMsg($e->getMessage());
        }
        return $this->returnMsg('构建完成（成功：'.$cou[1].' 失败：'.$cou[0].'）',1);
    }

    /**
     * 删除记录
     * @return mixed
     */
    public function del(){
        $id = $this->request->post('id/a','','intval');
        if(!$id) return $this->returnMsg('参数错误');
        if(Db::name('build_local')->delete($id)){
            return $this->returnMsg("删除成功！", 1);
        }else{
            return $this->returnMsg("删除失败！");
        }
    }

    /**
     * 微库构建记录
     * @param  string  $do  异步数据
     * @return mixed
     */
    public function veitool(string $do = '')
    {
        if($do == 'json'){
            $where = [];
            $d = $this->request->get('','','strip_sql');
            $kw = $d['kw'] ?? '';
            $fds = ['note','username','ip'];
            $field = isset($d['fields']) && isset($fds[$d['fields']]) ? $d['fields'] : -1;
            $sotime = $d['sotime'] ?? '';
            $type  = $d['type'] ?? '';
            $state = $d['state'] ?? '';
            $limit = isset($d['limit']) ? intval($d['limit']) : 10;
            if($kw!=''){
                if($field>-1){
                    $where[] = $field>1 ? [$fds[$field],'LIKE', '%'.$kw.'%'] : [$fds[$field],'=',$kw];
                }else{
                    $where[] = [implode('|',$fds),'LIKE', '%'.$kw.'%'];
                }
            }
            if(strpos($sotime,' - ')!==false){
                $t = explode(' - ',$sotime);
                $where[] = ['logtime','>=',strtotime($t[0]." 00:00:00")];
                $where[] = ['logtime','<=',strtotime($t[1]." 23:59:59")];
            }
            if($type) $where[] = ['type','=',$type];
            if(is_numeric($state)) $where[] = ['state','=',$state];
            return $this->returnMsg(Db::name("build_veitool")->where($where)->order(['id'=>'desc'])->field("*")->paginate($limit));
        }
        $this->assign([
            'limit' => 10
        ]);
        return $this->fetch();
    }

    /**
     * 微库构建
     */
    public function build(){
        $d = $this->only(['type/s','uid/d','repeat/d','reback/d','name/*/{2,20}/标识名称/1,2/','token','title/h','db_table/*/{2,20}/数据表名/1,2/_','app_dir','sub_dir','parent_id/d']);
        if(Db::name('build_veitool')->where("name = '$d[name]'")->find()) return $this->returnMsg('构建标识名称已经存在，请更换为其他标识！');
        try{
            $d['version'] = VT_VERSION;
            //获取模板后缀
            $d['suffix'] = config('view.view_suffix');
            Build::build($d['name'], $d);
            Db::name('build_veitool')->insert([
                'name'     => $d['name'],
                "type"     => $d['type'],
                "db_table" => $d['db_table'],
                "app_dir"  => $d['app_dir'],
                "sub_dir"  => $d['sub_dir'],
                "ip"       => $this->request->ip(),
                "logtime"  => time(),
                "username" => $this->manUser['username']
            ]);
            return $this->returnMsg('构建成功', 1);
        }catch(Exception $e){
            return $this->returnMsg($e->getMessage(),$e->getCode());
        }
    }

    /**
     * 卸载构建
     * @return json
     */
    public function uninstall()
    {
        $d = $this->only(['@token'=>'','name/*/a']); 
        try{
            Build::uninstall($d['name']);
            Db::name('build_veitool')->where("name = '$d[name]'")->delete();
            return $this->returnMsg('卸载成功', 1);
        }catch(Exception $e){
            return $this->returnMsg($e->getMessage(),$e->getCode());
        }
    }

    /**
     * 删除记录
     * @return mixed
     */
    public function vdel(){
        $id = $this->only(['@token'=>'','id'])['id'];
        $id = is_array($id) ? implode(',',$id) : $id;
        if(!$id) return $this->returnMsg('参数错误');
        $rs = Db::name('build_veitool')->where("id IN($id)")->column('name');
        if(Db::name('build_veitool')->where("id IN($id)")->delete()){
            foreach ($rs as $v){
                @rmdirs(ADDON_PATH . '/build/data/' . $v);
            }
            return $this->returnMsg("删除成功！", 1);
        }else{
            return $this->returnMsg("删除失败！");
        }
    }

}