<?php
/*
|--------------------------------------------------------------------------
| 常见问题管理
|--------------------------------------------------------------------------
|
| 问题增删改查
|  @author liXiaoLin
|  @Date: 2021/7/28
|  @Time: 9:33
|  @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 SubjectsController 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);
    }

    /**
     * @api {get} /api/helps/subject/create 问题管理列表
     * @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":[]}
     *
     */
    public function index(Request $request)
    {
        //页码数据
        $page_size = (int)$request->input('page_size', 20);
        $page = (int)$request->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        //检索出数据
        $data = $this->dataService->search($request->all(), ['*'], $page, $page_size);

        //根据权限格式化页面button
        $token = $request->input('token');
        $privId = $request->input('Pri_id');
        $data = $this->dataService->formatSubjectContents($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 {get} /api/helps/subject/create 问题添加界面数据
     * @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":[]}
     *
     */
    public function create()
    {
        $types = FAQService::getTypes();
        $platforms = PlatformService::getAll();
        $states = FAQService::getStates();

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

    /**
     * @api {post} /api/helps/subject 问题及答案保存
     * @apiGroup faq
     * @apiName FAQ管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 保存问题及答案数据到数据库
     *
     * @apiParam {String} dt_id  参数说明
     * @apiParam {String} d_title  参数说明
     * @apiParam {String} d_name  参数说明
     * @apiParam {String} d_content  参数说明
     * @apiParam {String} d_status  参数说明
     * @apiParam {String} d_keywords  参数说明
     *
     * @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)
    {
        $data = $request->filled(['dt_id', 'p_id', 'd_title', 'd_sord', 'answer', 'd_name', 'd_product', 'd_keywords', 'd_content', 'd_status']);
        if ($this->validateRules) {
            $validate = validator()
                ->make(
                    $data,
                    $this->validateRules['rules'],
                    $this->validateRules['messages'],
                    $this->validateRules['attributes']
                );
            if ($validate->fails()) {
                $messages = $validate->messages();

                return $this->error('参数错误', ErrorInc::INVALID_PARAM, $messages);
            }
        }
        if ($data) {
            Db::beginTransaction();
            $entity = [];
            $entity['d_dtid'] = (int)$request->input('dt_id');     //分类id
            $entity['d_pid'] = (int)$request->input('p_id');      //平台id
            $entity['d_title'] = $request->input('d_title');        //标题  问题
            $entity['d_sord'] = (int)$request->input('d_sord', 0);  //排序
            $entity['d_name'] = $request->input('d_name');         //项目
            $entity['d_product'] = $request->input('d_product');      //产品
            $entity['d_keywords'] = $request->input('d_keywords');     //关键字
            $entity['d_content'] = $request->input('d_content');      //描述
            $entity['d_admin'] = $request->get('session_token')['id'];//添加人
            $entity['d_status'] = (int)$request->input('d_status', 1);//状态
            $entity['d_creatime'] = date('Y-m-d H:i:s');                 //添加时间

            $subjectID = FAQService::insertGetId($entity);
            if ($subjectID) {
                $dc_arr = [];
                $dc_arr['dc_content'] = $request->input('answer');//答案
                $dc_arr['dc_did'] = $subjectID;
                $dc_arr['dc_type'] = $entity['d_dtid'];
                $dc_arr['dc_pid'] = $entity['d_pid'];
                $dc_arr['dc_creatime'] = date("Y-m-d H:i:s");
                $dc_arr['dc_admin'] = $entity['d_admin'];

                $res = FAQService::insertAnswer($dc_arr);
                if ($res) {
                    Db::commit();
                    return $this->success('操作成功');
                }
                Db::rollBack();
                return $this->error('添加答案失败', ErrorInc::MYSQL_STEP_FAILED);
            } else {
                return $this->error('添加失败', ErrorInc::MYSQL_FAILED);
            }
        } else {
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);
        }
    }

    /**
     * @api {get} /api/helps/subject/{id} 问题修改
     * @apiGroup faq
     * @apiName FAQ管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 问题修改界面数据信息
     *
     * @apiParam {String} dt_id  参数说明
     * @apiParam {String} d_title  参数说明
     * @apiParam {String} d_name  参数说明
     * @apiParam {String} d_content  参数说明
     * @apiParam {String} d_status  参数说明
     * @apiParam {String} d_keywords  参数说明
     *
     * @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 edit(int $id)
    {
        $entity = $this->dataService->find($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/subject/{id} 问题及答案保存
     * @apiGroup faq
     * @apiName FAQ管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 保存问题及答案数据到数据库
     *
     * @apiParam {String} dt_id  参数说明
     * @apiParam {String} d_title  参数说明
     * @apiParam {String} d_name  参数说明
     * @apiParam {String} d_content  参数说明
     * @apiParam {String} d_status  参数说明
     * @apiParam {String} d_keywords  参数说明
     *
     * @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)
    {
        $data = $request->filled(['dt_id', 'p_id', 'd_title', 'd_sord', 'answer', 'd_name', 'd_product', 'd_keywords', 'd_content', 'd_status']);
        if ($this->validateRules) {
            $validate = validator()
                ->make(
                    $data,
                    $this->validateRules['rules'],
                    $this->validateRules['messages'],
                    $this->validateRules['attributes']
                );
            if ($validate->fails()) {
                $messages = $validate->messages();

                return $this->error('参数错误', ErrorInc::INVALID_PARAM, $messages);
            }
        }
        if ($data) {
            $entity = [];
            $entity['d_dtid'] = $request->input('dt_id');     //分类id
            $entity['d_pid'] = $request->input('p_id');      //平台id
            $entity['d_status'] = $request->input('d_status', 1);//状态
            $entity['d_sord'] = $request->input('d_sord', 0);  //排序
            $entity['d_title'] = $request->input('d_title');        //标题  问题
            $entity['d_name'] = $request->input('d_name');         //项目
            $entity['d_product'] = $request->input('d_product');      //产品
            $entity['d_keywords'] = $request->input('d_keywords');     //关键字
            $entity['d_content'] = $request->input('d_content');      //描述

            $d_title = Db::table('databasestitle')
                ->where('d_id', '!=', $id)
                ->where(["d_title" => $entity['d_title'], "d_dtid" => $data['d_dtid'], "d_pid" => $data['d_pid']])
                ->value("d_id");
            if ($d_title) {
                return response()->json(['ErrorCode' => 3, 'ErrorMessage' => '操作失败,该平台的分类下标题已存在', 'Data' => '']);
                exit;
            }
            $res = Db::table('databasestitle')->where('d_id', $id)->update($data);
            if ($res) {
                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 append(Request $request)
    {
        $id = intval($request->get('id'));
        $entity = $this->dataService->find($id);
        if (!$entity) {
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
        }
        $types = FAQService::getTypes([$entity['d_dtid']]);
        $platforms = PlatformService::getAll(true,'id');
        $platforms = $platforms[$entity['p_id']]??[];
        $states = FAQService::getStates();

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

    /**
     * @api {post} /api/helps/subject/appendAnswer 追加答案
     * @apiGroup faq
     * @apiName FAQ管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 追加答案到问题里
     *
     * @apiParam {String} dt_id  参数说明
     * @apiParam {String} d_title  参数说明
     * @apiParam {String} d_name  参数说明
     * @apiParam {String} d_content  参数说明
     * @apiParam {String} d_status  参数说明
     * @apiParam {String} d_keywords  参数说明
     *
     * @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 appendAnswer(Request $request)
    {
        $id = (int)$request->input('d_id');
        $entity = $this->dataService->find($id);
        //执行追加答案
        if ($request->filled('answer')) {
            $answer = $request->input('answer');
            $res = FAQService::checkAnswerExist($id, $answer);
            if ($res) {
                return $this->error('答案重复', ErrorInc::REPEAT_SUBMIT);
            }
            $dc_arr = [];
            $dc_arr['dc_content'] = $answer;
            $dc_arr['dc_did'] = $id;
            $dc_arr['dc_type'] = $entity['d_dtid'];
            $dc_arr['dc_pid'] = $entity['d_pid'];
            $dc_arr['dc_status'] = (int)$request->input('d_status', 1);
            $dc_arr['dc_sord'] = (int)$request->input('d_sord', 0);
            $dc_arr['dc_creatime'] = date("Y-m-d H:i:s");
            $dc_arr['dc_admin'] = $request->get('session_token')['id'];

            $res = FAQService::appendAnswer($dc_arr);
            if ($res) {
                return response()->json(['ErrorCode' => 1, 'ErrorMessage' => '追加答案成功', 'Data' => '']);
            } else {
                return response()->json(['ErrorCode' => 3, 'ErrorMessage' => '追加答案失败', 'Data' => '']);
            }
        } else {
            return $this->error('缺少答案', ErrorInc::INVALID_PARAM);
        }
    }

    /**
     * @api {delete} /api/helps/subject/{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 = $this->dataService->find($id);
        if ($entity)
        {
            $entity->delete($id);

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