<?php
namespace app\controller;

use app\model\diseasequestionanswer\Question;
use app\model\CdssXyDisease;
use app\model\diseasequestionanswer\QuestionDetail;
use app\model\diseasequestionanswer\QuestionHistory;
use think\facade\Db;
use think\facade\Request;
use Fukuball\Jieba\Jieba;
use Fukuball\Jieba\Finalseg;
use think\response\Json;

require_once root_path().'vendor/fukuball/jieba-php/src/vendor/multi-array/MultiArray.php';
require_once root_path().'vendor/fukuball/jieba-php/src/vendor/multi-array/Factory/MultiArrayFactory.php';
require_once root_path().'vendor/fukuball/jieba-php/src/class/Jieba.php';
require_once root_path().'vendor/fukuball/jieba-php/src/class/Finalseg.php';

Jieba::init();
Finalseg::init();


/**
 * 智能问答
 */
class QuestionAnswer extends CommonTwoController
{

    /**
     * @param  $question string  问题121212
     *
     * @return Json
     */
    public function index()
    {

        ini_set('memory_limit','1500M');

        /**
         * 123
         * 提问者手机号以及提问问题
         */
        $phone    = Request::param('phone') ?? '';
        $question = Request::param('question') ?? '';

        /**
         * 分词
         */
        $stringArr = Jieba::cut($question);

        /**
         * 疾病
         */
        $disease = '';
        foreach ($stringArr as $vv) {
            $result = CdssXyDisease::where('name' , $vv)->find();
            if($result) {
                $disease = $vv;
            }
        }

        /**
         * 检测不到疾病时
         */
        if ( ! $disease ) {
            $id  = Request::param('id')     ?? '';
            $val = Request::param('value')  ?? '';
            $current_field = Request::param('current_field')  ?? 'pathogenesis';
            $selectField   = Request::param('select_field')   ?? 'pathogenesis';
            return $this->_json_succ(
                $this->questionDetail($id , $question , $val , $current_field , $selectField , $phone)
            );
        }

        if ( $disease ) {
            $field   = Request::param('field')  ?? '';
            $comment = Request::param('comment') ?? '';
            $table   = "jm_cdss_xy_disease";
            $sql     = "show full columns from {$table}";
            $res     = Db::query($sql);

            /**
             * 字段
             */
            foreach ($res as  $key => $value) {
                if('id' === $value['Field']) {
                    unset($res[$key]);
                }
                if('department_1' === $value['Field']) {
                    unset($res[$key]);
                }
                if('department_2' === $value['Field']) {
                    unset($res[$key]);
                }
                if('alias' === $value['Field']) {
                    unset($res[$key]);
                }
                foreach ($stringArr as $v) {
                    if($value['Comment'] === $v) {
                        $field = $value['Field'];
                    }
                }
            }

            if($disease &&  ! $field) {
                $newArray = array_combine(array_column($res , 'Field') , array_column($res , 'Comment'));
                foreach ($newArray as $kkk => $vvv) {
                    $new[] = [
                        'field_name'    => $kkk ,
                        'filed_comment' => $vvv
                    ];
                }

                if($new) {
                    QuestionHistory::questionAnswerRecord($question , array_column($new , 'filed_comment') , $phone);
                }

                return $this->_json_succ(
                    [
                        'question'    => $question,
                        'answer'      => '请选择提问属性！' ,
                        'button_list' => $new ,
                        'type'        => 'disease'
                    ]
                );
            }

            if($disease &&  $field) {
                $answer = CdssXyDisease::where('name' , $disease)->value($field) ?? '';
                if($answer) {
                    return $this->_json_succ(
                        [
                            'question'    => $question,
                            'answer'      => $answer ,
                            'button_list' => [],
                            'type'        => 'disease'
                        ]
                    );
                }
                QuestionHistory::questionAnswerRecord($question , $answer , $phone);
                return $this->_json_succ(
                    [
                        'question'    => $question.$comment,
                        'type'        => 'chatgpt'
                    ]
                );
            }
        }
    }


    /**
     * chatGpt调用
     */
    protected function getAnswerByChatGpt($question)
    {
        $url    = "http://18.221.12.198:5001/chatgpt?content=".$question;
        $result = file_get_contents($url);
        return [
            'type'   => 'chatgpt' ,
            'result' => $result
        ];
    }


    /**
     * 问题
     */
    public function questionList()
    {
        ini_set('memory_limit','1500M');
        $page     = Request::param('page') ?? 1;
        $pagesize = 30;
        $limit    = ($page - 1) * $pagesize;
        $questionList = Question::field('id , question')->where('status' , 1)->limit($limit , $pagesize)->select()->toArray();
        return $this->_json_succ(
            [
                'question_list' => $questionList ,
            ]
        );
    }



    /**
     * 问题详情
     */
    protected function questionDetail($id , $question = '' , $val = '' , $current_field = '' , $selectField = '' , $phone = '')
    {
        if( ! $val) {
            $result = QuestionDetail::field($selectField)->where(
                [
                    'question_id' => $id ,
                    'status'      => 1
                ]
            )->select()->toArray();
            $result = array_values(array_filter(array_column($result , $selectField)));
        } else {
            $result = QuestionDetail::field($selectField)->where(
                [
                    'question_id'  => $id ,
                    'status'       => 1,
                    $current_field => $val
                ]
            )->find();
        }

        $fields = $this->getTabelFieldsAndComments('jm_question_detail');
        $key    = $this->getNextFieldKey($selectField);

        /**
         * 查询不到的情况前端调用chatGpt
         */
        if( ! $selectField || ! $result || 'product_name' === $current_field) {
            return [
                'question' => $question,
                'type'    => 'chatgpt'
            ];
        }

        QuestionHistory::questionAnswerRecord($question , $result , $phone);

        return [
                'current_field'   => $selectField,
                'comment'         => $this->getNextFieldKey($selectField , 'comment'),
                'result'          => $result,
                'next_field_info' => $fields[$key+1] ?? '',
                'type'            => 'stage',
                'id'              => $id
            ];
    }


    protected function getNextFieldKey($selectField , $type = 'key')
    {
        $fields = $this->getTabelFieldsAndComments('jm_question_detail');
        foreach ($fields as $key => $value) {
            if($selectField === $value['field_name']) {
                if('key' === $type) {
                    return $key ?? '';
                }

                if('comment' === $type) {
                    return $value['filed_comment'] ?? '';
                }
            }
        }
    }


    /**
     * 数据表字段结构
     */
    protected function getTabelFieldsAndComments($table)
    {
        $sql   = "show full columns from {$table}";
        $res   = Db::query($sql);
        $newArray = array_combine(array_column($res , 'Field') , array_column($res , 'Comment'));
        foreach ($newArray as $kkk => $vvv) {
            if(in_array($kkk , ['id' , 'question_id' , 'status' , 'createtime' , 'updatetime'])) {
                unset($newArray[$kkk]);
            }
        }

        foreach ($newArray as $k => $v) {
            $new[] = [
                'field_name'    => $k ,
                'filed_comment' => $v
            ];
        }
        return $new;
    }

}
