<template>
  <div class="custom-model-template">
    <div class="generation-box-parent">
      <div class="generation-box" v-show="!loading" ref="GenerationBox">
        <div class="interaction-form">
          <CustomForm
            :formList="AdminData.list"
            :sub_type="sub_type"
            @SubmitBackGround="SubmitBackGround"
            @SubmitLocalImage="SubmitLocalImage"
          ></CustomForm>
          <div class="confirm-box">
            <div class="pay-num">
              <!-- <div>余额：0/5000</div>
          <div>实付：100</div> -->
            </div>
            <CustomResetButton @click="onReset" width="20%"
              >重置</CustomResetButton
            >
            <CustomResetButton @click="beforeSubmit" width="50%" bold
              >生成图片</CustomResetButton
            >
          </div>
        </div>
        <div class="generate-result">
          <CustomGenerateResult
            :status="AdminData.status"
            :backgroundImage="BackObj.url"
            :OverlayImages="OverlayImages.list"
            :list="AdminData.callback_list"
            :module_status="AdminData.module_status"
            :config="StrategyConfig"
            @submit="submitModelTask"
          ></CustomGenerateResult>
        </div>
      </div>
    </div>
    <div class="help"></div>
    <CustomLoading v-show="loading"></CustomLoading>
  </div>
</template>

<script lang="ts" setup>
import CustomForm from '@/components/custom/CustomForm.vue';
import CustomLoading from '@/components/custom/loading2.vue';
import CustomResetButton from '@/components/custom/resetbutton.vue';
import CustomGenerateResult from './components/GenerateResult';
import {
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
} from 'vue';
import {
  getScenesList,
  useUploadStrategy,
  useSubmitConversationImage,
  useImageCallback,
} from '@/utils/api/scenes';
import { FormExample4, ModelStatus } from '@/utils/api/Task';
import { ChangePageHeight } from '@/utils/tool';
import { FilterForm, FilterFormType } from '@/constants/form';
import { useRoute } from 'vue-router';
import { show_message } from '@/utils/tdesign_tool';
const loading = ref(false);
const route = useRoute();
const id = route.query.id;
// el
const GenerationBox = ref();

// 定时器
let IntervalImg: any = null;
// 背景图对象
const BackObj = reactive({
  url: '',
  prompt: '',
  name: '',
});
// 上传策略
const StrategyConfig = ref({});
const AdminData = reactive({
  list: [],
  // 回调图片列表
  callback_list: [],
  /**
   * loading-生成中
   * success-结束
   */
  status: '',
  module_status: ModelStatus.wait,
  reset_num: 1,
});
//
const OverlayImages = reactive({
  list: [],
});
const scenario_id = ref();
// 搜索时提交的类型
const sub_type = ref();
// 本地提交的图片
const SubmitLocalImage = (item: any) => {
  if (OverlayImages.list.length) {
    OverlayImages.list[0] = item;
  } else {
    OverlayImages.list.push(item);
  }
};
// 元素高度和页面高度比较
const getElementHeight = () => {
  if (GenerationBox.value) {
    ChangePageHeight(GenerationBox.value);
  }
};

// 选择的模特
const SubmitBackGround = (item: any) => {
  BackObj.url = item.url;
  BackObj.prompt = item.prompt;
  BackObj.name = item.name;
  AdminData.status = 'edit';
};

const getStrategy = async () => {
  try {
    let res: any = await useUploadStrategy();
    if (res.code == 0) {
      StrategyConfig.value = res.data;
    }
  } catch (e) {
    console.log(e);
  }
};

// 获取图片回调
const ImageCallback = async (uuid: string) => {
  try {
    let res: any = await useImageCallback({
      key: uuid,
      // key: 'generate_image:beacfaacc2fb819c17bb92e2495deee7',
    });
    if (res.code == 0) {
      if (res.data.image) {
        AdminData.status = 'success';
        if (res.data.image.length > AdminData.callback_list.length) {
          AdminData.callback_list = res.data.image;
        }
        if (res.data.image.length == 4) {
          // 关闭定时器
          closeInterval();
        }
      }
    }
    console.log(res);
  } catch (e) {
    console.log(e);
  }
};
// 开启定时器
const openInterval = (uuid: string) => {
  IntervalImg = window.setInterval(() => {
    //  请求接口
    ImageCallback(uuid);
  }, 2000);
};
// 关闭定时器
const closeInterval = () => {
  if (IntervalImg) {
    window.clearInterval(IntervalImg);
    clearInterval(IntervalImg);
    IntervalImg = null;
  }
};
// 重置
const onReset = () => {
  // 遍历整个列表,清空value
  AdminData.list.forEach((item: any) => {
    item.lists.forEach((it: any) => {
      if (it.value) {
        it.value = '';
      }
    });
  });
  // 恢复默认状态
  AdminData.status = '';
  AdminData.callback_list = [];
  // 初始化图片状态
  AdminData.reset_num += 1;
};
// 提交
const submitModelTask = (url: string) => {
  if (url) {
    // 过滤params
    const params = FilterForm(AdminData.list);
    if (params) {
      // 合并后的图片链接
      params.image = url;
      params[BackObj.name] = BackObj.prompt;
      // 提交
      onSubmit(params);
    }
  }
};
// 提交--ai图片任务
const onSubmit = async (params: any) => {
  try {
    let res: any = await useSubmitConversationImage({
      scenario_id: scenario_id.value,
      parameters: params,
    });
    if (res.code == 0) {
      // 开启定时器
      openInterval(res.data.uuid);
      AdminData.status = 'loading';
    }
    console.log(res);
  } catch (e) {
    console.log(e);
  }
};
// 提交前的校验
const beforeSubmit = () => {
  // 先校验一次规则
  const params = FilterForm(AdminData.list);
  if (params) {
    // 通知子组件上传图片
    AdminData.module_status = ModelStatus.upload;
    AdminData.status = 'loading';
  }
};
onBeforeMount(async () => {
  //   获取上传策略
  getStrategy();
});

// 获取后台配置的组件
const getAdminComponent = async () => {
  try {
    loading.value = true;
    console.log(JSON.stringify(FormExample4));
    let res: any = await getScenesList(id, 'id');
    if (res.code == 0) {
      // 取id
      scenario_id.value = res.data.id;
      sub_type.value = res.data.sub_type;

      let list = res.data.form;
      if (list.length) {
        const result = FilterFormType(list);
        list = result.list;
      } else {
        show_message('表单未配置');
        return;
      }
      AdminData.list = list;
    }
    loading.value = false;
    nextTick(() => {
      getElementHeight();
    });
  } catch (e) {
    console.log(e);
    loading.value = false;
  }
};
onMounted(async () => {
  if (!id) {
    show_message('禁止访问');
    return;
  }
  // 获取组件列表
  await getAdminComponent();
});
onBeforeUnmount(() => {
  closeInterval();
});
</script>

<style lang="less">
@import '@/style/variables.less';
.custom-model-template {
  padding: @page-padding-top 0;
  box-sizing: border-box;
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  .generation-box-parent {
    width: 100%;
    height: 100%;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
    .generation-box {
      width: 100%;
      display: flex;
      .generate-result {
        width: 50%;
        border: 2px dashed #565656;
        border-radius: 18px;
        margin-left: 12px;
        display: flex;
        justify-content: center;
        align-items: center;
        & > :nth-child(1) {
          width: 100%;
          height: 100%;
        }
      }
      .interaction-form {
        background: #2d2d2d;
        border: 1px solid #565656;
        border-radius: 18px;
        flex: 1;
        padding: 12px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;

        .confirm-box {
          flex: 1;
          display: flex;
          align-items: flex-end;
          justify-content: space-between;
          margin: 20px 0;
          box-sizing: border-box;
          .pay-num {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            & > :nth-child(1) {
              font-size: @font-size-16;
              color: #b1b5c4;
            }
            & > :nth-child(2) {
              font-size: @font-size-20;
            }
          }
          & > :last-child,
          & > :nth-child(2) {
            &::before {
              width: calc(200% - 2px);
            }
          }
        }
        & > :not(:first-child) {
          margin-top: 20px;
        }
      }
    }
  }
  .help {
    width: 0;
    height: 100%;
    display: inline-block;
    vertical-align: middle;
  }
}
</style>
