<?php

namespace app\admin\controller\sys_manage;

use app\admin\service\sys_manage\FieldService;
use app\admin\validate\sys_manage\ContentValidate;
use app\controller\Curd;
use app\model\Content;
use app\model\SysField;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class QuestionController extends Curd
{
    public function __construct()
    {
        $this->model = new Content();
        $this->validate = true;
        $this->validateClass = new ContentValidate();
    }

    /** 列表
     * @Desc
     * @Author Gorden
     * @Date 2024/3/5 10:00
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['content_category'] = 'WELLNESSQUESTION';
        $order = $request->get('order', 'ASC');
        $field = $field ?? 'content_sort';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'category' => function ($query) {
                $query->select('category_id', 'category_name');
            }
        ]);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order)->orderBy('content_addtimes', 'DESC');
        }
        return $model;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->content_config_json)) {
                $contentConfigJson = json_decode($item->content_config_json, true);
//                $questionArray = [];
//                foreach ($contentConfigJson as $question) {
//                    $questionArray[] = [
//                        [
//                            'label' => '选项',
//                            'value' => $question['field'],
//                        ],
//                        [
//                            'label' => '题目',
//                            'value' => $question['question'],
//                        ]
//                    ];
//                }
                $item->content_config_json = array_values($contentConfigJson);
            } else {
                $item->content_config_json = [];
            }
        }

        return $items;
    }

    /**
     * @Desc 问卷列表
     * @Author Gorden
     * @Date 2024/12/4 8:53
     *
     * @return Response
     */
    public function selectList()
    {
        $questions = Content::where('content_category', 'WELLNESSQUESTION')
            ->select('content_title', 'content_config_json')
            ->orderBy('content_sort')
            ->get()
            ->toArray();
        foreach ($questions as &$question) {
            if (!empty($question['content_config_json'])) {
                $contentConfigJson = json_decode($question['content_config_json'], true);
                foreach ($contentConfigJson as $item) {
                    $fields = SysField::whereIn('field_id', $item['field'])
                        ->select('field_id','field_name', 'field_form_key', 'field_form_type', 'field_refer_json')
                        ->orderByDesc('field_sort')
                        ->get()
                        ->toArray();
                    $fieldData = [];
                    foreach ($fields as $field) {
                        if (!empty($field['field_refer_json'])) {
                            $fieldData[] = [
                                'form_type' => $field['field_form_type'],
                                'form_key' => $field['field_form_key'],
                                'field_name'=> $field['field_name'],
                                'field' => json_decode($field['field_refer_json'], true)
                            ];
                        }
                    }
                    $question['list'][] = [
                        'question' => $item['question'],
                        'fields' => $fieldData
                    ];
                }
            }
            unset($question['content_config_json']);
        }

        return json_success('success', $questions);
    }

    /**
     * @Desc 问卷详情
     * @Author Gorden
     * @Date 2024/12/2 10:09
     *
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        $contentId = $request->get('content_id');

        $question = Content::where('content_id', $contentId)->first();
        $questionContent = [];
        if (!empty($question->content_config_json)) {
            $contentConfigJson = json_decode($question->content_config_json, true);
            foreach ($contentConfigJson as $item) {
                $fields = SysField::whereIn('field_id', $item['field'])->select('field_name', 'field_form_type')->get()->toArray();
                $fieldName = '';
                foreach ($fields as $field) {
                    $formType = FieldService::$formType[$field['field_form_type']] ?? '';
                    $fieldName .= $field['field_name'] . '(' . $formType . ');';
                }
                $questionContent[] = [
                    'question' => $item['question'],
                    'fieldStr' => rtrim($fieldName, ';')
                ];
            }
            $question->content_question_content = $questionContent;
        }

        dump($question);

        return json_success('success', $question);
    }

    /**
     * @Desc insert 处理
     * @Author Gorden
     * @Date 2024/3/27 10:24
     *
     * @param Request $request
     * @return array
     * @throws \support\exception\BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $data['content_category'] = 'WELLNESSQUESTION';
        $data['content_config_json'] = json_encode($request->post('question'));

        return $data;
    }

    /**
     * @Desc update 处理
     * @Author Gorden
     * @Date 2024/12/2 9:22
     *
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        $data['content_config_json'] = json_encode($request->post('question'));
        unset($data[$primary_key]);
        return [$id, $data];
    }
}