QAndAForm.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace app\modules\client\models\v1;
  3. use app\models\QAndAQa;
  4. use app\models\QAndASetting;
  5. use app\utils\DeepSeek\DeepSeekAiTools;
  6. use Exception;
  7. use yii\base\Model;
  8. class QAndAForm extends Model
  9. {
  10. public $question;
  11. public $user;
  12. /**
  13. * @return array
  14. */
  15. public function rules()
  16. {
  17. return [
  18. [['question', 'user'], 'required'],
  19. ];
  20. }
  21. public function save()
  22. {
  23. if (!$this->validate())
  24. return [
  25. 'code' => 1,
  26. 'msg' => $this->getErrorSummary(false)[0]
  27. ];
  28. try {
  29. $user = $this->user;
  30. $setting = QAndASetting::find()->where(['store_id' => get_store_id()])->one();
  31. if ($setting && $setting->q_integral > 0) {
  32. if ($user->integral < $setting->q_integral) {
  33. throw new Exception('积分不足, 请先充值后再提问!');
  34. }
  35. }
  36. try {
  37. $daan = DeepSeekAiTools::send($setting->key, $this->question);
  38. if ($daan['code'] != 0) {
  39. throw new Exception($daan['msg']);
  40. }
  41. } catch (\Throwable $e) {
  42. return [
  43. 'code' => 0,
  44. 'data' => [
  45. 'text' => '请求失败,请检查配置是否正确',
  46. 'time' => date("Y-m-d H:i:s"),
  47. ]
  48. ];
  49. }
  50. $time = time();
  51. $answer = $daan['data'];
  52. $q = new QAndAQa();
  53. $q->store_id = get_store_id();
  54. $q->user_id = $user->id;
  55. $q->question = $this->question;
  56. $q->answer = $answer;
  57. $q->created_at = $time;
  58. $q->answer_time = $time;
  59. $q->use_integral = $setting ? $setting->q_integral : 0;
  60. if ($q->save()) {
  61. return [
  62. 'code' => 0,
  63. 'data' => [
  64. 'text' => $answer,
  65. 'time' => date("Y-m-d H:i:s", $q->answer_time),
  66. ]
  67. ];
  68. } else {
  69. throw new Exception($q->getErrorSummary(false)[0]);
  70. }
  71. } catch (\Exception $e) {
  72. return [
  73. 'code' => 0,
  74. 'data' => [
  75. 'text' => $e->getMessage(),
  76. 'time' => date("Y-m-d H:i:s"),
  77. ],
  78. ];
  79. }
  80. }
  81. }