<?php

namespace App\Admin\Actions\Grid;

use App\Admin\Forms\InquiryAssignment as InquiryAssignmentForm;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Widgets\Modal;
use Illuminate\Http\Request;
use App\Admin\Repositories\DistAppearance;
use App\Admin\Repositories\DistAppearanceTemplate;

class AppearanceImport extends RowAction
{
    public $sourcePath;
    public $appearanceId;
    /**
     * 返回字段标题
     *
     * @return string
     */
    public function title()
    {
        return admin_trans_label('import_tmpl');
    }

    public function confirm()
    {
        return [
            "Are you sure you want to import?",
            $this->row->title,
        ];
    }
    /*
     * 处理请求
     */
    public function handle(Request $request)
    {
        $appearanceId = $this->getKey();
        $folder = $request->get('folder');
        //导入模板
        $path = resource_path().'/appearance/'.$folder;
        if (!is_dir($path)) {
            return $this->response()->error("The directory does not exist")->refresh();
        }
        $this->sourcePath = $path;
        $this->appearanceId = $appearanceId;
        // 清空旧的
        DistAppearanceTemplate::deleteTemplates($appearanceId, config('dictionary.base_dist_id'));
        // 导入模板
        $this->readDirectory($path);
        // 更新状态
        DistAppearance::setStatusToImported($appearanceId);
        // 返回响应结果并刷新页面
        return $this->response()->success("Successfully imported")->refresh();
    }
    /**
     * 设置要POST到接口的数据
     *
     * @return array
     */
    public function parameters()
    {
        return [
            // 发送当前行 username 字段数据到接口
            'title' => $this->row->title,
            'folder' => $this->row->folder
        ];
    }

    private function readDirectory($dirPath) {
        // 检查目录是否存在
        if (!is_dir($dirPath)) {
            return;
        }

        // 打开目录
        $dir = opendir($dirPath);

        // 读取目录内容
        while (($file = readdir($dir)) !== false) {
            // 忽略当前目录和上级目录
            if ($file == '.' || $file == '..') {
                continue;
            }

            // 获取文件或文件夹的完整路径
            $fullPath = $dirPath . '/' . $file;

            // 如果是文件夹，递归读取
            if (is_dir($fullPath)) {
                $this->readDirectory($fullPath); // 递归调用
            } else {
                // 如果是文件，读取文件内容
                $content = file_get_contents($fullPath);
                $filePath = str_replace($this->sourcePath, '', $dirPath);
                $fileName = basename($fullPath);
                // 插入数据库
                DistAppearanceTemplate::insertTemplateContent(config('dictionary.base_dist_id'), $this->appearanceId, $filePath,$fileName, $content);
            }
        }

        // 关闭目录
        closedir($dir);
    }
}
