<?php

namespace App\Http\Controllers;


/*
 * 用户认证控制器
 */

use App\Models\SiteAlbum;
use App\Models\SiteAlbumFolder;
use App\Models\SiteAlbumLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use ZipArchive;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;

class HomeController extends Controller
{
    /*
     * 首页
     */
    public function index(Request $request)
    {
        return view('index',['foldersTree' => $this->foldersTree]);
    }

    public function main(Request $request)
    {

        return view('main',['foldersTree' => $this->foldersTree]);
    }

    /*
     * 分类列表
     */
    public function gallery(Request $request)
    {
        $search = $request->input('search', '');
        if ($search) {
            $search = trim($search);
            $searchLike = '%' . $search . '%';
            $albums = SiteAlbum::where('model', 'like', $searchLike)->orderBy('id', 'desc')->get();
            $title = '搜索'.$search.'结果:';
            $folder_id = 0;
            $father_id = 0;
            if ($albums) {
                $albums = $albums->toArray();
            }
        } else {
            $folder_id = $request->input('fid',$this->getFoldersTreeFirstId());
            $father_id = $this->getFoldersTreeFatherId($folder_id);
            $folder = SiteAlbumFolder::find($folder_id);
            $albums = SiteAlbum::where('folder_id', $folder_id)->orderBy('id', 'desc')->get();
            $albums = $albums->toArray();
            $title = $folder->title;
        }

        foreach ($albums as $key => $album) {
            $cover = json_decode($album['cover']);
            foreach ($cover as $k => $v) {
                if (strpos($v, 'http') === false && strpos($v, 'https') === false) {
                    unset($cover[$k]);
                }
            }
            $cover = empty($cover) ? ['/static/images/noimg.jpg'] : $cover;
            $albums[$key]['cover'] = $cover;
        }
        // 面包屑导航
        $breadcrumb = getBreadcrumb($folder_id, $this->foldersTree);
        if ($breadcrumb) {
            $breadcrumb = implode('<span>/</span>', $breadcrumb) . '<span>/</span>';
        } else {
            $breadcrumb = '';
        }

        return view('gallery',
            [
                'foldersTree' => $this->foldersTree,
                'folderName'=> $title,
                'folder_id' => $folder_id,
                'father_id' => $father_id,
                'albums' => $albums,
                'breadcrumb' => $breadcrumb,
            ]
        );
    }

    public function detail(Request $request) {
        $id = $request->input('id',0);
        $album = SiteAlbum::find($id);
        $bumFolder = SiteAlbumFolder::where('id', $album->folder_id)->first();
        $showTabs = [];
        if ($bumFolder) {
            $row = json_decode($bumFolder->show_tabs);
            $row[7] = '7';
            foreach ($row as $key => $value) {
                $column = '';
                $title = '';
                switch ($value) {
                    case '0':
                        $column = 'cover';
                        $title = '主图';
                        break;
                    case '1':
                        $column = 'en_detail';
                        $title = '英文详情';
                        break;
                    case '2':
                        $column = 'cn_detail';
                        $title = '中文详情';
                        break;
                    case '3':
                        $column = 'video';
                        $title = '视频';
                        break;
                    case '4':
                        $column = 'poster';
                        $title = '海报';
                        break;
                    case '5':
                        $column = 'cert';
                        $title = '证书';
                        break;
                    case '6':
                        $column = 'pdf';
                        $title = 'PDF';
                        break;
                    case '7':
                        $column = 'parameters';
                        $title = '属性';
                        break;
                }
                $content = json_decode($album[$column], true);
                if (empty($content) == false) {
                    $showTabs[$key] = ['value'=>$value,'column'=>$column, 'title'=>$title];
                }
            }
        }
       // dd(json_decode($album['parameters'], true));
        return view('gallery-detail',[
            'foldersTree' => $this->foldersTree,
            'album' => $album->toArray(),
            'showTabs' => $showTabs
        ]);
    }

    public function updateLog(Request $request)
    {
        $losgs = SiteAlbumLog::getFormattedLogs();
        return view('update_log',[
            'foldersTree' => $this->foldersTree,
            'logs' => $losgs
        ]);
    }

    /*
     * 下载全部
     */

    public function downloadAll(Request $request)
    {
        Session::put('downloadAllStatus', '1');

        $id = $request->input('id', 0);
        $tab = $request->input('tab', 'cover');
        $album = SiteAlbum::find($id);

        if ($album) {
            $album = $album->toArray();

            if (isset($album[$tab])) {
                $files = json_decode($album[$tab]);
                $fileUrls = [];

                // 获取所有图片的 URL
                foreach ($files as $key => $value) {
                    $fileUrl = ossUrl($value); // 获取完整的图片 URL
                    $fileUrls[] = $fileUrl; // 将图片 URL 存入数组
                }

                // 创建一个临时 ZIP 文件
                $zipFileName = 'album_' . $id . '_' . $tab . '.zip';
                $zipPath = storage_path('app/' . $zipFileName);
                $zip = new ZipArchive;

                if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
                    foreach ($fileUrls as $fileUrl) {
                        $fileContent = file_get_contents($fileUrl); // 下载图片内容
                        $fileName = basename($fileUrl); // 获取文件名
                        $zip->addFromString($fileName, $fileContent); // 将图片添加到 ZIP 文件中
                    }

                    $zip->close();

                    // 提供 ZIP 文件下载
                    Session::put('downloadAllStatus', '2');
                    return response()->download($zipPath, $zipFileName)->deleteFileAfterSend(true);
                } else {
                    Session::put('downloadAllStatus', '2');
                    return response()->json(['error' => '系统正在下载中，请稍后再试','status'=> 500]);
                }
            } else {
                Session::put('downloadAllStatus', '2');
                return response()->json(['error' => '未找到指定的 Tab 数据','status'=> 404]);
            }
        } else {
            Session::put('downloadAllStatus', '2');
            return response()->json(['error' => '未找到相册','status'=> 404]);
        }
    }




    public function downloadImage(Request $request)
    {
        Session::put('downloadAllStatus', '1');

        // Get the URL from the request parameter
        $imageUrl = $request->input('url');

        // Validate the URL
        if (filter_var($imageUrl, FILTER_VALIDATE_URL) === false) {
            Session::put('downloadAllStatus', '2');
            return response()->json(['error' => 'Invalid URL'], 400);
        }

        try {
            // Initialize cURL
            $ch = curl_init($imageUrl);

            // Set cURL options
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Allow HTTPS (disable SSL peer verification)
            curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Set timeout to prevent hanging

            // Execute cURL request
            $imageContent = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            if ($httpCode !== 200) {
                Session::put('downloadAllStatus', '2');
                return response()->json(['error' => 'Failed to download image'], 500);
            }

            curl_close($ch);

            // Generate a random filename
            $fileName = Str::random(32) . '.jpg';

            Session::put('downloadAllStatus', '2');
            // Return the image as a download
            return response($imageContent)
                ->header('Content-Type', 'image/jpeg')
                ->header('Content-Disposition', 'attachment; filename="' . $fileName . '"');
        } catch (\Exception $e) {
            Session::put('downloadAllStatus', '2');
            return response()->json(['error' => 'Error downloading image: ' . $e->getMessage()], 500);
        }
    }


    public function getDownloadAllStatus(Request $request)
    {
        $reset = $request->input('reset', 0);
        if ($reset) {
            Session::put('downloadAllStatus', '0');
        }
        $status = Session::get('downloadAllStatus',0);
        return response()->json(['status' => $status]);
    }

    /*
     * 更新日志
     */
    public function nextLog(Request $request)
    {
        $id = $request->input('id', 0);
        $log = SiteAlbumLog::getNextLogEntry($id);
        if ($log) {
            return response()->json(['status' => 'success', 'data' => $log]);
        } else {
            return response()->json(['status' => 'error', 'data' => []]);
        }
    }

    //获取分类树父ID
    private function getFoldersTreeFatherId($folder_id)
    {
        foreach ($this->foldersTree as $key => $value) {
            $father_id  = $value['id'];
            if ($folder_id == $value['id']) {
                return $father_id;
            }
            foreach ($value['children'] as $k => $v) {
                if ($folder_id == $v['id']) {
                    return $father_id;
                }
                foreach ($v['children'] as $kk => $vv) {
                    if ($folder_id == $vv['id']) {
                        return $father_id;
                    }
                }
            }
        }
        return 0;
    }

    //返回分类树第一个无子节点的ID
    private function getFoldersTreeFirstId()
    {
        foreach ($this->foldersTree as $key => $value) {
            if (isset($value['children'])) {
                foreach ($value['children'] as $k => $v) {
                    return $v['id'];
                }
            } else {
                return $value['id'];
            }
        }
        return 0;
    }

}
