<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Question as QuestionModel;
use app\admin\model\QuestionLanguages;
use app\admin\validate\QuestionValidate;
use Exception;
use think\facade\Cache;

/**
 * 问题管理
 */
class Question extends BaseController
{

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

            $query = QuestionLanguages::alias('question_languages')
                        ->join('keyword_languages', 'keyword_languages.keyword_id = question_languages.keyword_id', 'left')
                        ->where('question_languages.language_code', $language_code);
                        
            if (!empty($question)) {
                $query = $query->where(function ($query) use ($question) {
                    $query->where('question_languages.question', 'like', "%{$question}%")
                        ->whereOr('keyword_languages.name', 'like', "%{$question}%");
                });
            }
            if (!empty($params['category_id'])) {
                $query = $query->where('question_languages.category_id', $params['category_id']);
            }
            if (!empty($params['question_type'])) {
                $query = $query->where('question_languages.question_type', $params['question_type']);
            }
            if (!empty($params['start_time'])) {
                $query = $query->where('question_languages.created_at', '>=', $params['start_time'].' 00:00:00');
            }
            if (!empty($params['end_time'])) {
                $query = $query->where('question_languages.created_at', '<=', $params['end_time'].' 23:59:59');
            }

            $count = $query->count();
            $list = $query->join('category_languages', 'question_languages.category_id = category_languages.category_id', 'left')
                        ->field(['question_languages.*', 'question_languages.category_id', 'category_languages.name as category_name', 'keyword_languages.name as keyword_name'])
                        // ->where('category_languages.language_code', $language_code)
                        ->order('weight','desc')
                        ->limit($limit)
                        ->page($page)
                        ->select();
            $questionTypeList = QuestionModel::questionTypeList($language_code, false);
            foreach($list as &$item) {
                $item['question_type_text'] = $questionTypeList[$item['question_type']] ?? '';
            }
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['questionTypeList' => QuestionModel::questionTypeList($language_code), 'count' => $count, 'list' => $list]);
    }

    //新增/编辑
    public function update()
    { 
        try {
            $params = (new QuestionValidate)->post()->goCheck('edit');
            $id = $this->request->param('id',0);
            $language_code = $params['language_code'] ?? $this->lang;
            
            if (!$id) {
                $questionLanguage = new QuestionLanguages();
            } else {
                $questionLanguage = QuestionLanguages::where('id', $id)->find();
                if (!$questionLanguage) {
                    return $this->error('问题不存在');
                }
            }

            $questionLanguage->category_id = $params['category_id'];
            $questionLanguage->question_type = $params['question_type'];
            $questionLanguage->question = $params['question'];
            $questionLanguage->answer = $params['answer'];
            $questionLanguage->keyword_id = $params['keyword_id']??0;
            $questionLanguage->weight = $params['weight'];
            $questionLanguage->language_code = $language_code;
            $questionLanguage->save();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('questionList');
        return $this->success([],'保存成功');
    }

    //设置状态
    public function setStatus()
    {
        try {
            $params = (new QuestionValidate)->goCheck('id');
            $info = QuestionLanguages::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('questionList');
        return $this->success([], '操作成功');
    }

    //批量修改权重
    public function setWeight()
    {
        try {
            $id = request()->post('id');
            $weight = request()->post('weight');
            if (empty($id) || empty($weight) || !is_array($id)) {
                return $this->error('参数错误');
            }
            QuestionLanguages::whereIn('id', $id)->update(['weight' => $weight]);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('questionList');
        return $this->success([], '操作成功');
    }

    //批量修改问题类别
    public function setQuestionType()
    {
        try {
            $id = request()->post('id');
            $question_type = request()->post('question_type');
            if (empty($id) || empty($question_type) || !is_array($id)) {
                return $this->error('参数错误');
            }
            QuestionLanguages::whereIn('id', $id)->update(['question_type' => $question_type]);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('questionList');
        return $this->success([], '操作成功');
    }

    //删除
    public function delete()
    {
        try {
            $params = (new QuestionValidate)->goCheck('id');
            $info = QuestionLanguages::where('id', $params['id'])->find();
            if (!$info) {
                return $this->error('问题不存在');
            }
            $question_id = $info->question_id;
            $info->delete();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('questionList');
        return $this->success([], '删除成功');
    }

}