<template>
  <div class="custom-copywriting-generation-page">
    <div
      class="custom-copywriting-generation"
      v-show="!loading"
      ref="CopywritingBox"
    >
      <img class="tip-box" :src="res_img ?? imgs.tips" alt="" />
      <div class="interaction-form">
        <CustomForm :formList="AdminData.list"></CustomForm>
        <div class="confirm-box">
          <div>字符余额：0/50000</div>
          <CustomResetButton @click="onReset" width="20%"
            >重置</CustomResetButton
          >
          <CustomResetButton @click="beforeSubmit" width="50%" bold
            >生成文案</CustomResetButton
          >
        </div>
        <div class="cust-line"></div>
        <CustomGptMessage computed :list="MessageList.list"></CustomGptMessage>
      </div>
    </div>
    <CustomLoading v-show="loading"></CustomLoading>
  </div>
</template>

<script lang="ts" setup>
import CustomForm from '@/components/custom/CustomForm.vue';
import CustomResetButton from '@/components/custom/resetbutton.vue';
import CustomGptMessage from '@/components/custom/gptmessage.vue';
import { onBeforeMount, reactive, ref, nextTick } from 'vue';
import { getScenesList, useSubmitConversation } from '@/utils/api/scenes';
import { useRoute } from 'vue-router';
import { show_message } from '@/utils/tdesign_tool';
import { FormExample, ConversationKey } from '@/utils/api/Task';
import CustomLoading from '@/components/custom/loading2.vue';
import { Validationrules, ChangePageHeight } from '@/utils/tool';
import { FilterFormType } from '@/constants/form';
const route = useRoute();
const id = route.query.id;
const imgs = {
  tips: new URL('../../assets/img/tips.png', import.meta.url).href,
};
const CopywritingBox = ref();
// 场景id
const scenario_id = ref();
// 场景示例图
const res_img = ref('');
const loading = ref(false);
// 后台配置的输入类型--input-select-textarea
// type-1是input,2是select,3是长文本输入
const AdminData = reactive({
  list: [],
});
// 获取本地存储的对话记录--先返回空数组
const getLocalList = () => {
  return [];
  // let list = localStorage.getItem(ConversationKey);
  // if (list) {
  //   return JSON.parse(list);
  // }
  // return [];
};
// gpt-消息列表
const MessageList = reactive({
  // 显示在页面的list
  list: [],
  // 存本地的完整对话列表
  localList: getLocalList(),
});
// 元素高度和页面高度比较
const getElementHeight = () => {
  if (CopywritingBox.value) {
    ChangePageHeight(CopywritingBox.value);
  }
};
// 获取后台配置的组件
const getAdminComponent = async () => {
  try {
    loading.value = true;
    console.log(JSON.stringify(FormExample));
    let res: any = await getScenesList(id, 'id');
    if (res.code == 0) {
      // 取id
      scenario_id.value = res.data.id;
      // 取图片
      res_img.value = res.data.example_image;
      let list = res.data.form;
      // 修改数据
      const result = FilterFormType(list);
      list = result.list;
      AdminData.list = list;
    }
    loading.value = false;
    nextTick(() => {
      getElementHeight();
    });
  } catch (e) {
    console.log(e);
    loading.value = false;
  }
};

// 重置
const onReset = () => {
  // 遍历整个列表,清空value
  AdminData.list.forEach((item: any) => {
    item.lists.forEach((it: any) => {
      if (it.value) {
        it.value = '';
      }
    });
  });
};
// 提交
const onSubmit = async (params: any) => {
  try {
    // 提交前先创建一个消息
    MessageList.list.push({
      message: '',
    });
    let res: any = await useSubmitConversation({
      scenario_id: scenario_id.value,
      // messages: MessageList.localList,
      messages: [],
      parameters: params,
    });
    if (res.code == 0) {
      // 完整对话记录
      MessageList.localList = res.data;
      localStorage.setItem(
        ConversationKey,
        JSON.stringify(MessageList.localList)
      );
      // 要显示的内容--找到最后一条属于机器人的消息
      let RobotList = MessageList.localList.filter(
        (item: any) => item.role == 'assistant'
      );
      if (RobotList && RobotList.length) {
        MessageList.list[MessageList.list.length - 1].message =
          RobotList[RobotList.length - 1].content;
      }
    }
    console.log(res);
    // message列表存到本地
  } catch (e) {
    // 删除最后一个
    MessageList.list.pop();
    console.log(e);
  }
};
// 提交前的校验
const beforeSubmit = () => {
  let params: any = {};
  // 遍历整个列表
  for (let i = 0; i < AdminData.list.length; i++) {
    let item = AdminData.list[i];
    for (let j = 0; j < item.lists.length; j++) {
      let it = item.lists[j];
      // 校验规则
      let message = Validationrules(it.rules, it.value);
      if (message) {
        // 提示错误信息
        show_message(message);
        return;
      } else {
        // 添加params
        params[it.name] = it.value;
      }
    }
  }
  onSubmit(params);
};
onBeforeMount(async () => {
  if (!id) {
    show_message('禁止访问');
    return;
  }
  // 获取组件列表
  await getAdminComponent();
});
</script>

<style lang="less">
@import '@/style/variables.less';
.custom-copywriting-generation-page {
  position: relative;
  height: 100%;
  .custom-copywriting-generation {
    display: flex;
    padding-top: @page-padding-top;
    padding-bottom: @page-padding-top;
    .tip-box {
      width: 50%;
      // object-fit: contain;
    }
    .interaction-form {
      background: #2d2d2d;
      border: 1px solid #565656;
      border-radius: 18px;
      flex: 1;
      margin-left: 12px;
      padding: 12px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      .basic-info {
        .label {
          margin: 4px 0 12px 0;
          color: #b1b5c4;
          font-weight: 300;
          font-size: @font-size-12;
        }
        .value {
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          row-gap: 30px;
          .custom-input-global {
            width: 48%;
          }
          .custom-select-box {
            width: 48%;
          }
        }
      }
      .confirm-box {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 20px 0;
        box-sizing: border-box;
      }
      .cust-line {
        width: 100%;
        height: 1px;
        background: #565656;
      }
      .custom-gpt-message {
        max-height: none;
        min-height: 500px;
      }
      & > :not(:first-child) {
        margin-top: 20px;
      }
    }
  }
}
</style>
