<template>
  <div>
    <el-dialog title="智能创建" :visible.sync="aiDialogVisible" :append-to-body="true" width="600px"
      :before-close="handleClose" class="pub_dialog_diy" v-loading="loading">
      <div>
        <div class="ex_box">
          <span>例子：</span>
          <el-button type="primary" size="mini" @click="checkExample('1')">选择题</el-button>
          <el-button type="primary" size="mini" @click="checkExample('2')">问答题</el-button>
        </div>
        <div class="ac_box">
          <el-input v-model="text" placeholder="请在这里输入要发送的消息" size="normal" type="textarea" resize="none"
            :rows="3"></el-input>
          <el-button type="primary" size="mini" @click="generate" style="margin-left:10px">生成</el-button>
        </div>
        <div class="ac_content" v-if="aiCreate.length">
          <div class="title">生成内容：</div>
          <div class="box" v-if="aiType == 1">
            <div v-for="(item, index) in aiCreate" :key="index" class="choice">
              <div class="title">{{ `${index + 1}：${item.title}` }}</div>
              <div class="options">
                <span v-for="(option, oIndex) in item.options" :key="`${index}-${oIndex}`">{{ option }}</span>
              </div>
              <div class="answer">{{ `答案：${item.answer}` }}</div>
            </div>
          </div>
          <div class="box" v-if="aiType == 3">
            <div v-for="(item, index) in aiCreate" :key="index" class="choice">
              <div class="title">{{ `${index + 1}：${item.title}` }}</div>
              <div class="answer">{{ `答案：${item.answer}` }}</div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="close">Cancel</el-button>
        <el-button type="primary" @click="exportT">导入</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

export default {
  props: {
    aiJson: {
      type: Array,
    },
    aiDialogVisible: {
      type: Boolean,
    }
  },
  data() {
    return {
      example: {
        '1':{
          'title':'请你以富文本的形式给我出三个关于小学数学单位换算的选择题，每个选择题选项不少于4个，需要答案，但不需要解释，符号请使用中文的'
        },
        '2':{
          'title':'请你以富文本的形式给我出三个关于三年级语文知识问答的问答题，需要答案，但不需要解释'
        }
      },
      text: "",
      aiCreate: [],
      aiType: "",
      loading: false
    }
  },
  methods: {
    handleClose(done) {
      this.close()
      done()
    },
    close() {
      this.$emit('update:aiDialogVisible', false)
    },
    checkExample(type){
      this.text = this.example[type].title
    },
    guid() {
      var _num,
        i,
        _guid = "";
      for (i = 0; i < 32; i++) {
        _guid += Math.floor(Math.random() * 16).toString(16); //随机0  - 16 的数字 转变为16进制的字符串
        _num = Math.floor((i - 7) / 4); //计算 (i-7)除4
        if (_num > -1 && _num < 4 && i == 7 + 4 * _num) {
          //会使guid中间加 "-"   形式为xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
          _guid += "-";
        }
      }
      return _guid;
    },
    generate() {
      if (this.text == "") {
        this.$message.error("请输入要发送的消息")
        return
      }
      // else if (this.text.indexOf("添加文档") !== -1) {
      //   this.aiType = 4
      // }
      if (this.text.indexOf("选择题") !== -1) {
        this.aiType = 1
      } else if (this.text.indexOf("问答题") !== -1) {
        this.aiType = 3
      }else {
        this.$message.error("生成的文字中要包含选择题或者问答题才能生成题目哦，请重新编辑下吧")
        return
      }
      this.loading = true
      let param = {
        model: "gpt-3.5-turbo",
        temperature: 0,
        max_tokens: 2048,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0,
        messages: [
          {
            role: "user",
            content: this.text,
          },
        ],
        uid: this.guid(),
        stream: false,
      };
      this.ajax.post("https://gpt.cocorobo.cn/chat", param).then(
        (res) => {
          if (
            res.data.FunctionResponse &&
            res.data.FunctionResponse.result &&
            res.data.FunctionResponse.result == "无效请求,请重新发起对话"
          ) {
            this.$message.error("你的内容太长，无法使用Ai创建!");
            this.loading = false
            return;
          }
          let aiReturn = res.data.FunctionResponse.choices[0].message.content;
          aiReturn = aiReturn.split("\n")
          aiReturn = aiReturn.filter(e => e != "")
          this.loading = false
          this.generate2(aiReturn)
        },
        (err) => {
          console.log(err);
          this.loading = false
        }
      );
    },
    generate2(aiReturn) {
      this.loading = true
      let content = ''
      if(this.aiType == 1){
        content = `${JSON.stringify(aiReturn)},要求返回格式是Array [{"title":"",options:[],answer:[]}]`
      }else if(this.aiType == 3) {
        content = `${JSON.stringify(aiReturn)},要求返回格式是Array [{title: "",answer: ""}]`
      }
      let param = {
        model: "gpt-3.5-turbo",
        temperature: 0,
        max_tokens: 2048,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0,
        messages: [
          {
            role: "user",
            content: content
          },
        ],
        uid: this.guid(),
        stream: false,
      };
      this.ajax.post("https://gpt.cocorobo.cn/chat", param).then(
        (res) => {
          if (
            res.data.FunctionResponse &&
            res.data.FunctionResponse.result &&
            res.data.FunctionResponse.result == "无效请求,请重新发起对话"
          ) {
            this.$message.error("你的内容太长，无法使用Ai创建!");
            this.loading = false
            return;
          }
          let aiCreate = res.data.FunctionResponse.choices[0].message.content;
          try {
            aiCreate = JSON.parse(aiCreate)
          } catch (error) {
            this.generate2(aiReturn) 
          }
          console.log(aiCreate)
          this.aiCreate = aiCreate;
          this.loading = false
        },
        (err) => {
          console.log(err);
          this.loading = false
        }
      );
    },
    exportT() {
      if (!this.aiCreate.length) {
        this.$message.error("请先创建Ai内容!");
        return;
      }
      if(this.aiType !== 1 && this.aiType !== 3){
        this.$message.error("目前只支持选择题/问答题的创建！输入内容必须包含选择题/问答题！");
        return;
      }
      var json = JSON.parse(JSON.stringify(this.aiJson))
      let array = []
      let englishIndex = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      if(this.aiType === 1){
        for (var i = 0; i < this.aiCreate.length; i++) {
          let answer = []
          let type = 1
          if (this.aiCreate[i].answer) {
            if (this.aiCreate[i].answer.length > 1) {
              type = 2
              for (var j = 0; j < this.aiCreate[i].answer.length; j++) {
                answer.push(englishIndex.indexOf(this.aiCreate[i].answer[j].toLocaleUpperCase()))
              }
            } else {
              answer = [englishIndex.indexOf(this.aiCreate[i].answer[0].toLocaleUpperCase())]
            }
          }

          let options = []
          for (var j = 0; j < this.aiCreate[i].options.length; j++) {
            options.push({
              img: "",
              option: this.aiCreate[i].options[j]
            })
          }
          array.push(
            {
              json: {
                answer: answer,
                array: options,
                title: this.aiCreate[i].title,
                type: type
              },
              ttype: 1,
              type: 1
            }
          )
        }
      }else if(this.aiType === 3){
        for (var i = 0; i < this.aiCreate.length; i++) {
          array.push(
            {
              json: {
                answer: this.aiCreate[i].answer,
                title: this.aiCreate[i].title,
                type: 1
              },
              ttype: 1,
              type: 3
            }
          )
        }
      }
      if (!json.length || json[0].ttype == 1) {
        json = [...json, ...array]
      } else if((json[0].ttype == 2 || json[0].ttype == 3) && !json[0].array.length){
        json[0].array = array
      } else if(json[0].ttype == 2 && json[0].array.length){
        json[0].array = [...json[0].array, ...array]
      } else if(json[0].ttype == 3 && json[0].array.length){
        if(json[0].array[0].ttype == 2){
          json[0].array[0].array = [...json[0].array[0].array, ...array]
        }else {
          json[0].array = [...json[0].array, ...array]
        }
      }
      this.$emit("update:aiJson", json)
      this.close()
    }
  },
}
</script>

<style scoped>
.ac_box {
  display: flex;
  width: 100%;
  align-items: flex-end;
  margin-bottom: 10px;
}

.ex_box {
  margin-bottom: 10px;
  color: #909090;
}

.ac_content {}

.ac_content>.title {
  margin-bottom: 10px;
}

.ac_content>.box {}

.ac_content>.box>.choice+.choice {
  margin-top: 10px;
}

.ac_content>.box>.choice>div+div {
  margin-top: 10px;
}

.ac_content>.box>.choice>.options {
  display: flex;
  flex-wrap: wrap;
}

.ac_content>.box>.choice>.options>span {
  margin-right: 10px;
  margin-bottom: 5px;
}
</style>