<template>
  <div class="config-box">
    <div class="mb-2 flex justify-between items-center">
      <div>AI帮我写</div>
      <a-button key="submit" type="primary" @click="sendAi" :disabled="loading">生成代码</a-button>
    </div>
    <a-textarea
      v-model:value="question"
      placeholder="请填写问题"
      :auto-size="{ minRows: 4 }"
      class="!mb-2"
    />
    <div class="box-top" v-if="showTitle">
      <NodeHead nodeName="组件代码" />
    </div>
    <div style="height: calc(100% - 51px)">
      <CodeEditor v-model:value="definedScript" language="js" :readonly="disabled" />
    </div>
    <div
      style="
        width: 100%;
        background: rgb(255 255 255 / 70%);
        height: 100%;
        position: absolute;
        inset: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
      "
      v-if="loading"
    >
      <a-spin tip="代码生成中，请稍等......" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { CodeEditor } from '/@/components/CodeEditor';
  import { NodeHead } from '/@/components/ModalPanel/index';

  const props = defineProps({
    script: { type: String },
    disabled: { type: Boolean },
    showTitle: { type: Boolean },
  });

  const question = ref('');
  const loading = ref(false);
  const definedScript = ref(props.script);

  onMounted(async () => {});

  const sendAi = async () => {
    if (!question.value) {
      return;
    }
    // 调用kimi接口
    loading.value = true;
    const res = await fetch('https://api.moonshot.cn/v1/chat/completions', {
      method: 'POST',
      headers: {
        Authorization: 'Bearer sk-k87qpxN3WIsf2gPWLkZEuWPZsvcslg3WkNjsFURpkff7wXEV',
      },
      body: JSON.stringify({
        model: 'moonshot-v1-32k',
        messages: [
          {
            role: 'system',
            content: `请根据描述，只输出vue3或者html代码格式,不需要解释语言`,
          },
          { role: 'user', content: question.value },
        ],
      }),
    });

    const result = await res.json();

    let code = result.choices[0].message.content.replace(/^```html\s*|\s*```/g, '');
    code = code.replace(/^```vue\s*|\s*```/g, '');
    definedScript.value = code;
    loading.value = false;
  };
</script>

<style lang="less" scoped>
  .config-box {
    height: 400px;

    .box-top {
      display: flex;
      justify-content: space-between;
      height: 30px;
      border-bottom: 1px solid #f0f0f0;
      padding: 25px 20px;
    }

    .script-name {
      cursor: pointer;
      padding: 10px 0 10px 15px;

      &:hover {
        background: #f7fbff;
      }
    }

    .active-name {
      background: #f7fbff;
      border-right: 4px solid #1c8dff;
    }
  }
</style>
