<?php

namespace App\Http\Controllers\admin;

use App\Constants\Util;
use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;
use App\Models\Banner as BannerModel;

class Banner extends Controller
{

    /**
     * @api {get} /admin/banner 轮播图列表
     * @apiGroup 轮播图管理
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     *
     */
    function index()
    {
        try {
            $page = request()->input('page', 1);
            $limit = request()->input('limit', 15);
            $type = request()->input('type', '');
            
            $query = new BannerModel();

            if (!empty($type)) {
                $query->where('type', $type);
            }
            $count = $query->count();
            $list = $query
                 ->forPage($page, $limit)
                ->orderByDesc("sort")
                ->get()->toArray();
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success(['total' => $count, 'data' => $list]);
    }

    /**
     * @api {post} /admin/banner/update 修改
     * @apiDescription 更新或者新增都用这个接口
     * @apiGroup 轮播图管理
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     */
    public function update()
    {
        DB::beginTransaction();
        try {
            $params = request()->validate([
                'id' => ['nullable'],
                'title' => ['required'],
                'image' => ['required'],
                'link' => ['nullable'],
                'type' => ['required'],
                'sort' => ['nullable'],
                'lang' => ['required'],
            ]);
            $id = $params['id'] ?? null;

            BannerModel::updateOrCreate(
                ['id' => $id],
                [
                    'title' => $params['title'],
                    'image' => Util::replacePartInUrl($params['image']),
                    'link' => $params['link'],
                    'type' => $params['type'],
                    'sort' => $params['sort'],
                    'lang' => $params['lang'],
                ],
            );
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(intval($e->getCode()), $e->getMessage());
        }
        return $this->success();
    }


    /**
     * @api {post} /admin/banner/delete 删除
     * @apiGroup 轮播图管理
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} id 要删除的ID
     *
     */
    function delete()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'id' => ['required', 'integer', 'min:1', 'max:99999999'],
            ]);
            $id = request()->input('id', 0);
            $info = BannerModel::where('id', $id)->first();
            if (!$info) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
            $info->delete();
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(intval($e->getCode()));
        }
        return $this->success();
    }


}
