<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Keyword as KeywordModel;
use app\admin\model\KeywordLanguages;
use app\admin\model\QuestionLanguages;
use app\admin\validate\KeywordValidate;
use Exception;
use think\facade\Cache;

/**
 * 关键词管理
 */
class Keyword extends BaseController
{

    /**
     * @api {get} /keyword/list 列表
     */
    function list()
    {
        try {
            $params = $this->request->param();
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            $language_code = $params['language_code'] ?? $this->lang;

            $query = KeywordLanguages::where('language_code', $language_code);   
            if (!empty($params['name'])) {
                $query = $query->where('name', 'like', '%'.$params['name'].'%');
            }
            $field = !empty($params['field']) ? $params['field'] : 'weight';
            $order = !empty($params['order']) ? $params['order'] : 'desc';
            $count = $query->count();
            $list = $query->where('language_code', $language_code)
                        ->order($field,$order)
                        ->limit($limit)
                        ->page($page)
                        ->select();
            foreach($list as &$item) {
                $item['question_num'] = QuestionLanguages::where('keyword_id', $item['keyword_id'])->count();
            }
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }

    //新增/编辑
    public function update()
    { 
        try {
            $params = (new KeywordValidate)->post()->goCheck('edit');
            $id = $this->request->param('id',0);
            $status = $params['status'] ?? 1;
            $keyword_id = $params['keyword_id'] ?? 0;
            $language_code = $params['language_code'] ?? $this->lang;

            $exists = KeywordLanguages::where('name', $params['name'])->where('language_code', $language_code)->find();
            if ($exists ) {
                if (!$id || $id != $exists->id) {
                    return $this->error('关键词已存在');
                }
            }
            if (!$keyword_id) {
                $keyword = KeywordModel::create([
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
                $keyword_id = $keyword->id;
            }
            if (!$id) {
                $keywordLanguages = new KeywordLanguages();
            } else {
                $keywordLanguages = KeywordLanguages::where('id', $id)->find();
                if (!$keywordLanguages) {
                    return $this->error('关键词不存在');
                }
            }
            $keywordLanguages->keyword_id = $keyword_id;
            $keywordLanguages->name = $params['name'];
            $keywordLanguages->weight = $params['weight'] ?? 1;
            $keywordLanguages->status = $status;
            $keywordLanguages->language_code = $language_code;
            $keywordLanguages->save();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('keywordList');
        return $this->success([], '操作成功');
    }

    //设置状态
    public function setStatus()
    {
        try {
            $params = (new KeywordValidate)->goCheck('id');
            $info = KeywordLanguages::where('id', $params['id'])->find();
            if (!$info) {
                return $this->error('关键词不存在');
            }
            $info->status = $info->status == 0 ? 1 : 0;
            $info->save();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('keywordList');
        return $this->success([], '操作成功');
    }

    //删除
    public function delete()
    {
        try {
            $params = (new KeywordValidate)->goCheck('id');
            $info = KeywordLanguages::where('id', $params['id'])->find();
            if (!$info) {
                return $this->error('关键词不存在');
            }
            $keyword_id = $info->keyword_id;
            $info->delete();
            if (KeywordLanguages::where('keyword_id', $keyword_id)->count() == 0) {
                KeywordModel::where('id', $keyword_id)->delete();
            }
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('keywordList');
        return $this->success([],'删除成功');
    }

}