<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\GuessAskType as GuessAskTypeModel;
use Exception;

/**
 * 猜你想问类别
 */
class GuessAskType extends BaseController
{

    /**
     */
    function list()
    {
        try {
            $params = $this->request->param();
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            $language_code = $params['language_code'] ?? $this->lang;
            $query = GuessAskTypeModel::where('language_code', $language_code); 
            if (!empty($params['name'])) {
                $query = $query->where('name', 'like', '%'.$params['name'].'%');
            }
            if (isset($params['status']) && $params['status'] != '') {
                $query = $query->where('status', $params['status']);
            }
            $count = $query->count();
            $list = $query->order('id','desc')
                        ->limit($limit)
                        ->page($page)
                        ->select();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }

    //新增/编辑
    public function update()
    { 
        try {
            $params = $this->request->param();
            if (empty($params['name'])) {
                return $this->error('请输入类别名称');
            }
            $id = $this->request->param('id',0);
            $language_code = $params['language_code'] ?? $this->lang;

            $exists = GuessAskTypeModel::where('name', $params['name'])->where('language_code', $language_code)->find();
            if ($exists ) {
                if (!$id || $id != $exists->id) {
                    return $this->error('类别已存在');
                }
            }
            if (empty($id)) {
                $type = new GuessAskTypeModel();
            } else {
                $type = GuessAskTypeModel::where('id', $id)->find();
                if (!$type) {
                    return $this->error('类别不存在');
                }
            }
            $type->name = $params['name'];
            $type->language_code = $language_code;
            $type->save();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    
        return $this->success([], '操作成功');
    }

    //删除
    public function delete()
    {
        try {
            $id = $this->request->param('id',0);
            $info = GuessAskTypeModel::where('id', $id)->find();
            if (!$info) {
                return $this->error('类别不存在');
            }
            $info->delete();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success([],'删除成功');
    }

}