<?php
/*
|--------------------------------------------------------------------------
| FAQ知识管理
|--------------------------------------------------------------------------
|
| 平台增删改查
|  @author liXiaoLin
|  @Date: 2021/7/28
|  @Time: 11:35
|  @Email: lixiaolin@bluearp.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Helps;

use App\Models\AnswersBase;
use App\Models\SubjectsBase;
use App\Services\FAQService;
use App\Services\PlatformService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Traits\CurdControllerMethod;
use Illuminate\Http\Request;
use BlueCity\Core\Controllers\CoreController as Controller;
use Illuminate\Support\Facades\DB;

class AnswerController extends Controller
{
    public $dataService = null;  // CurdControllerMethod 必备参数
    protected $fields = ['d_id', 'd_title', 'd_name', 'd_product', 'd_keywords', 'd_content', 'd_sord', 'd_creatime', 'pt_name', 'dt_name', 'd_status'];
    protected $validateRules = [
        'rules' => [
            'dt_id' => 'required|alpha',//分类id
            'p_id' => 'required|alpha',//平台id
            'd_status' => 'required|alpha',//状态
            'd_sord' => 'required|alpha',//排序
            'd_title' => 'required|max:50',//标题  问题
            'd_name' => 'required|max:30',//项目
            'd_product' => 'required',//产品
            'd_keywords' => 'required',//关键字
            'd_content' => 'required' //描述
        ],
        'messages' => [
            'in' => ':attribute 选择错误'
        ],
        'attributes' => [
            'dt_id' => '分类id',
            'p_id' => '平台id',
            'd_status' => '状态',
            'd_sord' => '排序',
            'd_title' => '标题',
            'd_name' => '项目',
            'd_product' => '产品',
            'd_keywords' => '关键字',
            'd_content' => '描述'
        ]
    ];

    public function __construct()
    {
        $service = new FAQService();
        $this->bootWithService($service);
    }

    //列表

    /**|---------------------------------------------------------------------------------
     * @name  列表页
     * @param d_id        从资料库传来的id
     * @param d_title     问题
     * @param p_id        平台id
     * @param dt_id       所属分类id
     * @param dc_content  答案
     * @param dc_status   状态 0:不限  1:正常  2:隐藏
     * @return \Illuminate\Http\JsonResponse
     * @author <2019>
     * |---------------------------------------------------------------------------------
     */
    public function index(Request $request)
    {
        //页码数据
        $page_size = (int)$request->input('page_size', 10);
        $page = (int)$request->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        //检索出数据
        $data = FAQService::searchAnswer($request->all(), ['*'], $page, $page_size);
        //根据权限格式化页面button
        $token = $request->input('token');
        $privId = $request->input('Pri_id');
        $data = FAQService::formatAnswerContents($token, $privId, $data);
        //问答类型
        $types = FAQService::getTypes();
        $data['types'] = $types;

        if (empty($data['list'])) {
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $data);
        } else {
            return $this->success('获取成功', $data);
        }
    }

    /**
     * @api {put} /api/helps/answer/{id} 保存答案修改内容
     * @apiGroup faq
     * @apiName FAQ管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 保存答案修改内容到数据库
     *
     * @apiParam p_id  平台id
     * @apiParam dt_id 分类id
     * @apiParam d_id   问题id
     * @apiParam answer 答案
     * @apiParam dc_status 状态 1:正常 2:隐藏
     * @apiParam dc_sord   是否推荐 0:不推荐 1:推荐
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function store(Request $request)
    {
        $type = (int)$request->input('type', 1);
        if ($type == 1) {
            $pt_id = (int)$request->input('p_id', 0);//平台id
            $dt_id = (int)$request->input('dt_id', 0);//分类id
            //更加 类型id 和平台id获取 问题列表
            $list = Db::table('databasestitle')->where(['d_pid' => $pt_id, 'd_dtid' => $dt_id])->orderBy('d_sord', 'DESC')->select('d_id', 'd_title')->get();

            return response()->json(['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $list]);

        } else {
            //执行添加答案
            $id = (int)$request->input('d_id');
            $data = Db::table('databasestitle')->leftjoin('pt', 'id', '=', 'd_pid')->join('databasestype', 'd_dtid', '=', 'dt_id')->select('d_title', 'dt_name', 'pt_name', 'd_dtid', 'd_pid')->first();
            if (!$data) {
                return response()->json(['ErrorCode' => 3, 'ErrorMessage' => '未找到数据', 'Data' => '']);
                exit;
            }

            if ($request->filled('answer')) {
                $answer = $request->input('answer');
                $res = Db::table('databasescontent')->where(['dc_did' => $id, 'dc_content' => $answer])->value('dc_id');
                if ($res) {
                    return response()->json(['ErrorCode' => 3, 'ErrorMessage' => '答案重复', 'Data' => '']);
                    exit;
                }
                $dc_arr = [];
                $dc_arr['dc_content'] = $answer;
                $dc_arr['dc_did'] = $id;
                $dc_arr['dc_type'] = $data['d_dtid'];
                $dc_arr['dc_pid'] = $data['d_pid'];
                $dc_arr['dc_status'] = (int)$request->input('dc_status', 1);
                $dc_arr['dc_sord'] = (int)$request->input('dc_sord', 0);
                $dc_arr['dc_creatime'] = date("Y-m-d H:i:s");
                $dc_arr['dc_admin'] = $request->get('session_token')['id'];
                $ress = Db::table("databasescontent")->insert($dc_arr);
                if ($ress) {
                    $this->inserting_log("添加，", "", "添加答案：" . $answer, "答案库", $request->ip(), $request->get('session_token')['admin_acc']);
                    return response()->json(['ErrorCode' => 1, 'ErrorMessage' => '添加答案成功', 'Data' => '']);
                    exit;
                } else {
                    return response()->json(['ErrorCode' => 3, 'ErrorMessage' => '添加答案失败', 'Data' => '']);
                    exit;
                }

            } else {
                return response()->json(['ErrorCode' => 3, 'ErrorMessage' => '缺少答案', 'Data' => '']);
            }

        }
    }

    public function edit(int $id)
    {
        $entity = FAQService::findAnswerByID($id);
        if (!$entity) {
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
        }
        $types = FAQService::getTypes();
        $platforms = PlatformService::getAll();
        $states = FAQService::getStates();

        return $this->success('获取成功', ['entity' => $entity, 'platforms' => $platforms, 'types' => $types, 'states' => $states]);
    }

    /**
     * @api {put} /api/helps/answer/{id} 保存答案修改内容
     * @apiGroup faq
     * @apiName FAQ管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 保存答案修改内容到数据库
     *
     * @apiParam dc_id  答案id
     * @apiParam answer 答案
     * @apiParam dc_status  状态 1:正常; 2:隐藏
     * @apiParam dc_sord    是否推荐 0:不推荐 1:推荐
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */
    public function update(int $id, Request $request)
    {
        if ($request->filled('answer')) {
            $answer = $request->input('answer');
            $entity = FAQService::findAnswerByID($id);
            $dc_did = $entity->dc_did;
            //检查重复
            $res = FAQService::checkAnswerExist($dc_did, $answer, $id);
            if ($res) {
                return $this->error('答案重复', ErrorInc::REPEAT_SUBMIT);
            }
            //更新
            $dc_arr = [];
            $dc_arr['dc_content'] = $answer;
            $dc_arr['dc_status'] = (int)$request->input('dc_status', 1);
            $dc_arr['dc_sord'] = (int)$request->input('dc_sord', 0);
            $res = FAQService::updateAnswer($id, $dc_arr);
            if ($res) {
//                $this->inserting_log("编辑，", "", "编辑答案（id）：" . $id, "答案库", $request->ip(), $request->get('session_token')['admin_acc']);

                return $this->success('编辑答案成功');
            } else {
                return $this->error('编辑答案失败', ErrorInc::MYSQL_FAILED);
            }
        } else {
            return $this->error('缺少答案', ErrorInc::INVALID_PARAM);
        }
    }

    /**
     * @api {delete} /api/helps/answer/{id} 删除答案
     * @apiGroup faq
     * @apiName FAQ管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 删除指定答案
     *
     * @apiSuccess {Number} ErrorCode    状态码，1：请求成功
     * @apiSuccess {String} ErrorMessage   提示信息
     * @apiSuccess {Object} Data    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"ErrorCode":1,"ErrorMessage":"","Data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"ErrorCode":5001,"ErrorMessage":"接口异常","Data":[]}
     *
     */

    public function destroy(int $id)
    {
        $entity = FAQService::findAnswerByID($id);
        if ($entity) {
            FAQService::deleteAnswer($id);

            return $this->success('删除成功');
        } else {
            return $this->error('该内容不存在', ErrorInc::DATA_EMPTY);
        }
    }
}
