<?php

namespace App\Http\Controllers\API\Admin\YeWu;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class QuestionController extends Controller
{
  public function GetList()
  {
    $searchInfo = request('searchInfo');
    if (!isset($searchInfo['hospital_id'])) return \Yz::echoError1("医院id不能为空");
    if (!isset($searchInfo['q_type'])) return \Yz::echoError1("问卷类型不能为空");
    $list = DB::table('questions')
      ->where(['hospital_id'=>$searchInfo['hospital_id'],
        'q_type'=>$searchInfo['q_type'],
        'is_del'=>0,
      ])->orderBy('order','asc')->get();
    return \Yz::Return(true,"查询成功",['list'=>$list]);
  }
  public function Save()
  {
    $QuestionInfo = request('QuestionInfo');
    $params = [
      'hospital_id'=>isset($QuestionInfo['hospital_id'])?$QuestionInfo['hospital_id']:null,
      'question'=>isset($QuestionInfo['question'])?$QuestionInfo['question']:null,
      'content'=>(isset($QuestionInfo['content']) and !empty($QuestionInfo['content']))?json_encode($QuestionInfo['content'],JSON_UNESCAPED_UNICODE):null,
      'type'=>isset($QuestionInfo['type'])?$QuestionInfo['type']:null,
      'status'=>isset($QuestionInfo['status'])?$QuestionInfo['status']:null,
      'order'=>isset($QuestionInfo['order'])?$QuestionInfo['order']:null,
      'q_type'=>isset($QuestionInfo['q_type'])?$QuestionInfo['q_type']:null,
    ];
    $requiredFields = [
      'hospital_id','question','content','type','status','order','q_type'
    ];
    // 判断是否为空
    foreach ($requiredFields as $field) {
      if (!isset($params[$field]) || $params[$field] === null) {
            return \Yz::echoError1('参数' . $field . '不能为空');
      }
    }
    if(isset($QuestionInfo['id']) and $QuestionInfo['id']<>0){
      $insert=DB::table('questions')->where(['id'=>$QuestionInfo['id'],'is_del'=>0])->update($params);
    }else{
      $insert=DB::table('questions')->insert($params);
    }

    if($insert){
      return \Yz::Return(true,'操作成功',[]);
    }else{
      return \Yz::echoError1('操作失败');
    }

  }
  public function GetDetail()
  {
    $id = request('id');
    $info=DB::table('questions')->where(['id'=>$id,'is_del'=>0])->first();
    if(!!$info){
      $info->content=json_decode($info->content,true);
    }
    return \Yz::Return(true,'查询完成',$info);
  }
  public function Del()
  {
    $id = request('id');
    $del=DB::table('questions')->where(['id'=>$id])->update([
      'is_del'=>1
    ]);
    if($del){
      return \Yz::Return(true,'操作成功',[]);
    }else{
      return \Yz::echoError1('操作失败');
    }
  }
}
