<?php

namespace app\admin\controller;

use app\model\Qas;
use support\Request;

class QaController extends base
{
    public function getQaList(Request $request)
    {
        $cityId = $request->get('city_id');
        $limit = $request->get('limit', 10);

        if (empty($cityId)) return $this->error(2001, 'city_id cannot be empty!');

        $list = Qas::fieldRaw('city_id,title,content')->where('city_id', $cityId)->paginate($limit);

        return $this->success($list);
    }

    public function getQaDetail(Request $request)
    {
        $cityId = $request->get('city_id');
//        $id = $request->get('id');

        if (empty($cityId)) return $this->error(2001, 'city_id cannot be empty!');

        $data = Qas::fieldRaw('city_id,title,content')->where([/*'id' => $id, */'city_id' => $cityId])->find();

        return $this->success($data);
    }

    public function addQa(Request $request)
    {
        $post = $request->post();
        if (empty($post['city_id'])) return $this->error(2001, 'city_id data cannot be empty!');
        if (empty($post['title'])) return $this->error(2001, 'title data cannot be empty!');
        if (empty($post['content'])) return $this->error(2001, 'content data cannot be empty!');

        try {
            $data = Qas::create($post);
        } catch (\Exception $e) {
            return $this->error(2002, $e->getMessage());
        }
        return $this->success($data);
    }

    public function editQa(Request $request)
    {
        $post = $request->post();
        if (empty($post['id'])) return $this->error(2001, 'id data cannot be empty!');

        try {
            $data = Qas::update($post);
        } catch (\Exception $e) {
            return $this->error(2002, $e->getMessage());
        }
        return $this->success($data);
    }

    public function delQa(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) return $this->error(2001, 'id data cannot be empty!');
        try {
            $data = Qas::destroy($id);
        } catch (\Exception $e) {
            return $this->error(2002, $e->getMessage());
        }
        return $this->success($data);
    }
}