<?php


namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BaseService;
use App\Services\KeyboardService;
use Exception;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class Keyboard extends Controller
{


    /**
     * @api {get} /admin/keyboard 回复列表
     * @apiGroup 回复管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     * @apiParam {string} [button] 关键字
     *
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.total 数量
     * @apiSuccess (data) {Object[]} data.data 列表
     * @apiSuccess (data) {int} data.data.id
     * @apiSuccess (data) {string} data.data.button 回复关键字
     * @apiSuccess (data) {string} data.data.replay 回复内容
     * @apiSuccess (data) {string} data.data.updated_at
     * @apiSuccess (data) {string} data.data.created_at
     */
    public function index()
    {
        try {
            $search = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1'],
                'button' => ['nullable', 'string'],
                'language' => ['nullable', 'string', 'in:zh,vi,en'],
                'explain' => ['nullable', 'string'],
                'group_id' => ['nullable', 'integer', 'in:0,1'],
            ]);
            $result = KeyboardService::paginate($search);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode(), $e->getMessage());
        }
        return $this->success($result);
    }


    /**
     * @api {post} /admin/keyboard/submit 修改回复
     * @apiGroup 回复管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} id 回复ID
     * @apiParam {string} button 关键字
     * @apiParam {string} reply 回复内容
     * @apiParam {array} buttons 操作按钮组
     */
    public function store(): JsonResponse
    {
        try {
            $id = request()->input('id');
            $validator = [
                'id' => ['required', 'integer'],
                'reply' => ['required', 'string'],
                'explain' => ['nullable', 'string', 'max:28'],
                'language' => ['required', 'string', 'in:zh,vi,en'],
                'image' => ['nullable', 'url'],
                'button' => ['nullable', 'string', 'max:100'],
                'buttons' => ['array'],
                'buttons.*' => ['array', 'min:1'],
                'buttons.*.*.text' => ['required', 'string', 'min:1'],
                'buttons.*.*.url' => ['required', 'string', 'min:1'],
            ];
            if (empty($id)) {
                unset($validator['id']);
                $validator['button'] = ['required', 'string', 'min:1', 'max:100'];
            }
            $params = request()->validate($validator);
            $ret = KeyboardService::submit($params);
            if ($ret['code'] == BaseService::NOT) {
                throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
            }
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            if ($e->getCode() == HttpStatus::CUSTOM_ERROR) {
                return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
            }
            return $this->error(intval($e->getCode()));
        }
        return $this->success([], $ret['msg']);

    }

    /**
     * @api {post} /admin/keyboard/delete 删除回复
     * @apiGroup 回复管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} id 回复ID
     */
    public function destroy(): JsonResponse
    {
        $id = request()->post('id');
        // 示例：通过 ID 删除回复
        $info = KeyboardService::findOne(['id' => $id]);
        if (!$info) {
            return $this->error(HttpStatus::CUSTOM_ERROR, '数据不存在');
        }
        if ($info->group_id != 1) return $this->error(HttpStatus::CUSTOM_ERROR, '系统配置禁止删除');
        $info->delete();
        return $this->success([], '删除成功');
    }

}