<template>
  <a-modal
    v-bind="$attrs"
    v-model:visible="visible"
    width="1200px"
    title="组件配置"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <a-row class="config-box">
      <a-col :span="12" class="h-full" style="border-right: 1px solid #ddd">
        <a-tabs
          v-model:activeKey="activeKey"
          :tabBarStyle="{ background: '#eaf4ff', height: '50px', margin: 0 }"
        >
          <a-tab-pane key="1" tab="自定义属性">
            <div class="flex items-center p-4 pt-3">
              <div class="pr-4">选择已有组件</div>
              <a-select
                v-model:value="comphased"
                :showSearch="true"
                class="flex-1"
                :disabled="disabled"
              >
                <a-select-option v-for="item in complist" :value="item.value">{{
                  item.label
                }}</a-select-option>
              </a-select>
            </div>
          </a-tab-pane>
          <a-tab-pane key="2" tab="AI帮我写" force-render>
            <div class="p-4">
              <a-textarea
                v-model:value="question"
                placeholder="请填写问题"
                :auto-size="{ minRows: 4 }"
                :disabled="disabled"
              />
              <div class="mt-2 text-right">
                <a-button
                  key="submit"
                  type="primary"
                  @click="sendAi"
                  :disabled="disabled || loading"
                  >生成代码</a-button
                >
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
        <div
          :style="`height: calc(100% - ${
            activeKey == '1' ? '120px' : '230px'
          }); border: 1px solid #ddd; margin: 0 16px 10px;overflow: hidden`"
        >
          <CodeEditor :value="readScript" language="js" :readonly="true" />
        </div>
      </a-col>
      <a-col :span="12" class="h-full">
        <div class="box-top">
          <NodeHead nodeName="编写区" />
        </div>
        <div style="height: calc(100% - 51px); overflow: hidden">
          <CodeEditor
            v-model:value="definedScript"
            language="js"
            v-if="show"
            :readonly="disabled"
          />
        </div>
      </a-col>
    </a-row>
    <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>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { CodeEditor } from "/@/components/CodeEditor";
import { NodeHead } from "/@/components/ModalPanel/index";
import { getCustomComp } from "/@/api/system/customcomp";
import { componentListProps } from "../../../types";

const props = defineProps({
  customDia: { type: Boolean },
  script: { type: String },
  id: { type: String },
  disabled: { type: Boolean, default: false },
  customComponentList: { type: Array },
});
const loading = ref(false);
const activeKey = ref("1");
const visible = ref<boolean>(props.customDia);
const question = ref("");
const comphased = ref();
const readScript = ref();
const definedScript = ref(props.script);
const complist = ref<any>([]);
const emit = defineEmits(["update:script", "update:customDia"]);
const show = ref(false);
setTimeout(() => {
  show.value = true;
}, 200);
watch(
  () => props.customComponentList,
  (list) => {
    complist.value = [];
    if (!list || list?.length <= 0) return;
    list.forEach((o: componentListProps) => {
      if (o.list) {
        o.list.forEach((k: any) => {
          if (["html", "vue"].includes(k.options.type)) {
            complist.value.push({
              value: k.options.id,
              label: k.label,
            });
          }
        });
      }
    });
  },
  { deep: true, immediate: true }
);
watch(
  () => comphased.value,
  async (val) => {
    if (val) {
      let res = await getCustomComp(val);
      readScript.value = res.bianXieQu9373;
    }
  }
);
onMounted(async () => {
  if (!props.script && props.id) {
    let res = await getCustomComp(props.id);
    definedScript.value = res.bianXieQu9373 || "";
    emit("update:script", definedScript);
  }
});
const handleClose = () => {
  emit("update:customDia", false);
};

const handleSubmit = () => {
  emit("update:script", definedScript);
  emit("update:customDia", false);
};

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, "");
  readScript.value = code;
  loading.value = false;
};
</script>

<style lang="less" scoped>
.box-top {
  height: 50px;
  border-bottom: 1px solid rgb(238 238 238 / 93%);
  padding: 16px;
}

.config-box {
  height: 700px;
}
</style>
