<script setup lang="ts">
import { ref } from 'vue'
import TableConfiguration from './components/TableConfiguration.vue'
import RespnseConfiguration from './components/RespnseConfiguration.vue'
import OutputConfiguration from './components/OutputConfiguration.vue'
import PreviewTesting from './components/PreviewTesting.vue'
import submitsucessful from './images/icon_success_big@2x.png'
import moment from 'moment'

const rolename = ref('')
const tablename = ref('')
const professionalfield = ref('')
const tabledescription = ref('')
const maintasks = ref('')
const outputvalue = ref('')
const editid = ref('')
const prompttextvalue = ref('')
const TableConfigurationref = ref()
const RespnseConfigurationref = ref()
const tableDataList = ref([])
const stepData = ref([])
const formatList = ref([])
const promptValue = ref([])
const PromptdialogVisible = ref(false)
const PromptdialogInnerVisible = ref(false)
const UnableSaveVisible = ref(false)
const SaveedVisible = ref(false)
const ChangeLogList = ref([])
const prompttext = ref('')

const AddTableConfiguration = () => {
  TableConfigurationref.value.addNewTableColumn()
}

const addstepdata = () => {
  RespnseConfigurationref.value.addstepdata()
}

// 计算属性
const testquestiontEmpty = computed(() => {
  // 去除首尾空格后检查长度
  if(rolename.value.trim().length == 0 || professionalfield.value.trim().length == 0 || maintasks.value.trim().length == 0 || tablename.value.trim().length == 0 || tableDataList.value.length == 0 || stepData.value.length == 0 || formatList.value.length == 0) {
    return true
  } else {
    return false
  }
})

const getPromptConfiguration = () => {
  $api.getPromptConfiguration().then((res) => {
    if (res.code === 200) {
      rolename.value = res.data.character_name
      professionalfield.value = res.data.professional_field
      maintasks.value = res.data.main_tasks
      tablename.value = res.data.table_name
      tabledescription.value = res.data.table_description
      tableDataList.value = res.data.tableData
      stepData.value = res.data.stepData
      formatList.value = res.data.formatList
      outputvalue.value = res.data.formatListType
      prompttextvalue.value = res.data.complete_prompt
      promptValue.value = res.data.prompt_summary
      editid.value = res.data.id
      ChangeLogList.value = res.data.prompt_log_record
    }
  })
}
// 保存
const missingmessage = ref()
const SavePromptConfiguration = () => {
  missingmessage.value = ''
  if(rolename.value != '' && professionalfield.value != '' && maintasks.value != '' && professionalfield.value != '' && tableDataList.value.length != 0 && stepData.value.length != 0 &&  formatList.value.length != 0 &&  outputvalue.value != '' && prompttextvalue.value != '') {
    $api.SavePromptConfiguration({
      role_name: rolename.value,
      professional_field: professionalfield.value,
      main_tasks: maintasks.value,
      table_name: tablename.value,
      table_description: tabledescription.value,
      tableDataList: tableDataList.value,
      stepData: stepData.value,
      formatList: formatList.value,
      outputvalue: outputvalue.value,
      prompttextvalue: prompttextvalue.value,
      id: editid.value
    }).then((res) => {
      if (res.code === 200) {
        SaveedVisible.value = true
        setTimeout(() => {
          window.location.reload()
        }, 3000)
      }
    })
  } else {
    if(rolename.value == '' || professionalfield.value == '' || maintasks.value == '') {
      missingmessage.value += '系统角色配置, '
    }
    if(tablename.value == '' || tableDataList.value.length == 0) {
      missingmessage.value += '表结构配置, '
    }
    if(stepData.value.length == 0) {
      missingmessage.value += '响应规则配置, '
    }
    if(formatList.value.length == 0 || outputvalue.value == '') {
      missingmessage.value += '输出格式配置, '
    }
    missingmessage.value = missingmessage.value.substring(0, missingmessage.value.length - 2)
    UnableSaveVisible.value = true
  }
}

const EditPrompt = () => {
  $api.EditPrompt({
      role_name: rolename.value,
      professional_field: professionalfield.value,
      main_tasks: maintasks.value,
      table_name: tablename.value,
      table_description: tabledescription.value,
      tableDataList: tableDataList.value,
      stepData: stepData.value,
      formatList: formatList.value,
      outputvalue: outputvalue.value,
      prompttextvalue: prompttextvalue.value,
      id: editid.value
    }).then((res) => {
      if (res.code === 200) {
        prompttextvalue.value = res.data.complete_prompt
        promptValue.value = res.data.prompt_summary
      }
    })
}

// 导出为txt
const exporttxt = () => {
  // 创建 Blob 对象
  const blob = new Blob([prompttext.value], { type: 'text/plain' })
   // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  const currentDate = moment();
  const formattedDate = currentDate.format('YYYY-MM-DD HH:mm');
  link.download = `${formattedDate} Prompt.txt` // 自定义文件名
  
  // 触发下载
  link.click()
  
  // 清理内存
  URL.revokeObjectURL(link.href)
}

// 查看日志
const ViewPrompt = (item: any) => {
  PromptdialogInnerVisible.value = true
  prompttext.value = item
}

// 返回上一级
const Backprompt = () => {
  PromptdialogInnerVisible.value = false
}

onMounted(() => {
  getPromptConfiguration()
})
</script>

<template>
  <div class="Title">
    <div>Prompt Configuration</div>
    <div>
      <el-button class="el-button--default title-button" style="margin-right: 8px;" @click="PromptdialogVisible = true"><span class="font_family icon-icon_dashboard_b icon_dark" style="margin-right: 5px;"></span>变更日志查看</el-button>
      <el-button class="el-button--main title-button" @click="SavePromptConfiguration"><span class="font_family icon-icon_save_b icon_dark" style="margin-right: 5px;"></span>保存生效</el-button>
    </div>
  </div>
  <el-dialog
    v-model="PromptdialogVisible"
    width="1000px"
    title="变更日志"
    :modal="false"
    align-center
    class="prompt-dialog"
    :close-on-click-modal="false"
  > 
    <div class="diaolog-body">
      <div class="diaolog-content" v-for="(item, index) in ChangeLogList" :key="index">
        <div class="diaolog-flex">
          <div>
            <div class="dialog-title">{{ item.time }}</div>
            <div class="dialog-person">{{ item.person }}</div>
          </div>
          <div>
            <el-button class="el-button--default" @click="ViewPrompt(item.text)"><span class="font_family icon-icon_view_b icon_dark" style="margin-right: 5px;" ></span>查看完整Prompt</el-button>
          </div>
        </div>
        <div class="diaolog-text">
          {{ item.text }}
        </div>
      </div>
    </div>
  </el-dialog>
  <el-dialog
    v-model="PromptdialogInnerVisible"
    width="1000px"
    :modal="false"
    align-center
    class="prompt-dialog prompt-dialog-inner"
    :close-on-click-modal="false"
  > 
    <template #header>
      <div class="dialog-header">
        <div style="width: 55%;display: flex;justify-content: space-between;">
          <div class="Back" @click="Backprompt"><span class="font_family icon-icon_previous_b icon_dark"></span>Back</div>
          <div style="display: flex;align-items: center;">查看完整Prmopt</div>
        </div>
        <el-button class="el-button--default" @click="exporttxt"><span class="font_family icon-icon_import_b icon_dark" style="margin-right: 5px;" ></span>导出完整日志</el-button>
      </div>
    </template>
    <pre class="diaolog-content">
      {{ prompttext }}
    </pre>
  </el-dialog>
  <div class="prompt-content">
    <!-- 系统角色设置 -->
    <div class="prompt-border">
      <div class="prompt-title">系统角色设置</div>
      <div class="flex">
        <div style="width: 50%; margin-right: 8px;">
          <div class="little-title">角色名称</div>
          <el-input v-model="rolename" placeholder="为AI Robot创建一个角色名称" class="input-name" @change="EditPrompt"></el-input>
        </div>
        <div style="width: 50%;">
          <div class="little-title">专业领域</div>
          <el-input v-model="professionalfield" placeholder="为AI Robot设定专业领域" class="input-name"></el-input>
        </div>
      </div>
      <div style="margin-top: 16px;">
        <div class="little-title">主要任务</div>
        <el-input v-model="maintasks" type="textarea" placeholder="简要描述AI Robot的主要任务" class="input-name-textarea" :rows="3"></el-input>
      </div>
    </div>
    <!-- 表结构配置 -->
    <div class="prompt-border">
      <div class="prompt-title">表结构配置</div>
      <div class="flex">
        <div style="width: 50%; margin-right: 8px;">
          <div class="little-title"><span class="stars_red">*</span>表名</div>
          <el-input v-model="tablename" placeholder="创建一个表名" class="input-name" @change="EditPrompt"></el-input>
        </div>
        <div style="width: 50%;">
          <div class="little-title">表描述</div>
          <el-input v-model="tabledescription" placeholder="简要描述表的用途" class="input-name"></el-input>
        </div>
      </div>
      <div style="margin-top: 16px;">
        <el-button class="el-button--noborder--configuration prompt-button" @click="AddTableConfiguration">+ 添加字段</el-button>
        <TableConfiguration ref="TableConfigurationref" :tableDataList="tableDataList"></TableConfiguration>
      </div>
    </div>
    <!-- 响应规则配置 -->
    <div class="prompt-border">
      <div class="prompt-title">响应规则配置</div>
      <div style="margin-top: 16px;">
        <el-button class="el-button--noborder--configuration prompt-button" @click="addstepdata" v-if="stepData.length != 0">+ 添加步骤</el-button>
        <RespnseConfiguration ref="RespnseConfigurationref" :stepDataprops="stepData"></RespnseConfiguration>
      </div>
    </div>
    <!-- 输出格式配置 -->
    <div class="prompt-border">
      <div class="prompt-title">输出格式配置</div>
      <div style="margin-top: 16px;">
        <OutputConfiguration ref="OutputConfigurationref" :formatList="formatList" :outputvalue="outputvalue"></OutputConfiguration>
      </div>
    </div>
    <!-- 预览与测试 -->
     <div class="propmt-border-colorful">
        <div class="prompt-title" style="padding: 0 14px;">预览与测试</div>
        <div style="margin-top: 16px;">
          <PreviewTesting ref="PreviewTestingref" :prompttext="prompttextvalue" :testquestion="testquestiontEmpty" :promptValue="promptValue"></PreviewTesting>
        </div>
     </div>
     <div class="propmt-save"><el-button class="el-button--main" @click="SavePromptConfiguration"><span class="font_family icon-icon_save_b icon_dark" style="margin-right: 5px;"></span>保存生效</el-button></div>
     <!-- 保存失败 -->
    <el-dialog v-model="UnableSaveVisible" width="480">
      <div>{{ missingmessage }} missing.</div>
      <div>Please complete all required fields.</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            class="el-button--danger"
            @click="UnableSaveVisible = false"
            style="width: 100px"
          >
            OK
          </el-button>
        </div>
      </template>
      <template #header>
        <div class="cancel_header">
          <span class="iconfont_icon iconfont_warning">
            <svg class="iconfont icon_danger" aria-hidden="true">
              <use xlink:href="#icon-icon_fail_fill_b"></use>
            </svg>
          </span>
          Unable to Save
        </div>
      </template>
    </el-dialog>
    <!-- 保存成功 -->
    <el-dialog v-model="SaveedVisible" width="320" style="height: 212px">
      <div style="text-align: center"><el-image :src="submitsucessful" style="width: 64px;" /></div>
      <div style="text-align: center; margin-top: 20px">Saved successfully</div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.Title {
  display: flex;
  height: 68px;
  border: 1px solid var(--color-border);
  border-top: none;
  border-width: 1px 0 1px 0;
  font-size: var(--font-size-6);
  font-weight: 700;
  padding: 0 24px;
  align-items: center;
  justify-content: space-between;
}
.prompt-content {
  padding: 16px 24px;
}
.prompt-border {
  border: 1px solid var(--color-system-border-1);
  border-radius: 12px;
  padding: 13px 16px;
  margin-bottom: 8px;
}
.propmt-border-colorful {
  border: 2px solid transparent;
  border-radius: 12px;
  background-clip: padding-box, border-box;
  background-origin: padding-box, border-box;
  background-image: linear-gradient(to bottom, var(--color-mode), var(--color-mode)), linear-gradient(to bottom, #FF7500, #8112FF);
  margin-bottom: 8px;
  padding: 13px 0;
}
.prompt-button {
  margin-bottom: 8px;
}
.stars_red {
  color: var(--color-danger);
}
.prompt-title {
  font-size: 18px;
  font-weight: 700;
  margin-bottom: 21px;
}
.flex {
  display: flex;
}
.little-title {
  font-size: 12px;
  font-weight: 400;
  color: var(--color-neutral-2);
  margin-bottom: 4px;
}
.input-name {
  height: 40px;
}
.input-name-textarea {
  height: 80px;
}
:deep(.el-textarea__inner) {
  height: 80px;
  line-height: 1.5; /* 多行文本的行高 */
  padding: 11px 8px; /* 调整垂直居中 */
  resize: none; /* 禁用拖拽调整大小（可选） */
}
:deep(.el-button, .el-button.is-round) {
  padding: 4px 8px;
}
:deep(.el-textarea__inner) {
  font-weight: 400;
  font-size: 14px;
  color: var(--color-neutral-1);
}
.propmt-save {
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-button--main {
  width: 400px;
  height: 40px;
}
.title-button {
  width: 128px;
  height: 40px;
}
.diaolog-body {
  max-height: 720px;
  overflow-y: scroll;
}
.diaolog-content {
  background-color: var(--color-prompt-diaolog-bg);
  padding: 16px;
  margin-bottom: 8px;
  border-radius: 6px;
  line-height: 21px; 
  white-space: break-spaces;
}
.diaolog-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.el-button--default {
  height: 40px;
}
.dialog-title {
  font-size: 14px;
  font-weight: 700;
  color: var(--color-neutral-1);
}
.dialog-person {
  font-size: 12px;
  font-weight: 400;
  color: var(--color-neutral-2);
}
.diaolog-text {
  font-size: 14px;
  color: var(--color-neutral-2);
  font-weight: 400;
  margin-top: 16px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.dialog-header {
  height: 48px;
  width: 95%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.Back {
  color: var(--color-neutral-1);
  font-size: 14px;
  font-weight: 400;
  display: flex;
  align-items: end;
  margin-left: 23px;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
}
.Back:hover {
  border-color: var(--color-btn-default-bg-hover);
  background-color: var(--color-btn-default-bg-hover);
  color: var(--color-theme);
    span {
      color: var(--color-theme);
    }
}
.cancel_header {
  font-size: 18px;
  font-weight: 700;
  color: var(--color-neutral-1);
  display: flex;
  align-items: center;
}
.icon_danger {
  fill: var(--color-btn-danger-bg);
}
.iconfont_warning {
  display: flex;
  align-items: center;
}
</style>