<template>
  <div class="custom-model-generation-box">
    <div class="generation-box-parent" v-show="AdminData.page_module == 1">
      <div class="generation-box" v-show="!loading" ref="GenerationBox">
        <div class="interaction-form">
          <div
            class="basic-info"
            v-for="item in AdminData.list"
            :key="item.name"
          >
            <div class="label">*{{ item.name }}</div>
            <div class="value">
              <template v-for="it in item.lists" :key="it.name">
                <template v-if="it.component_type == 'input' && !it.is_hidden">
                  <CustomInput
                    v-model="it.value"
                    :type="it.type"
                    :placeholder="it.placeholder"
                  ></CustomInput>
                </template>
                <template v-else-if="it.component_type == 'select'">
                  <CustomSelect
                    :options="it.options"
                    v-model="it.value"
                    :placeholder="it.placeholder"
                  ></CustomSelect>
                </template>
                <!-- textarea -->
                <template v-else-if="it.component_type == 'textarea'">
                  <CustomTextArea
                    v-model="it.value"
                    :placeholder="it.placeholder"
                    :maxlength="it.maxlength"
                  ></CustomTextArea>
                </template>
                <template v-else-if="it.component_type == 'radio_group_size'">
                  <ImgSizeRadioGroupVue
                    :list="it.options"
                    v-model="it.value"
                  ></ImgSizeRadioGroupVue>
                </template>
                <template v-else-if="it.component_type == 'custom-number'">
                  <CustomInput
                    class="input-pay-num"
                    v-model="it.value"
                    type="number"
                    :placeholder="it.placeholder"
                  ></CustomInput>
                </template>
              </template>
            </div>
          </div>
          <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">
          <GenerateResult
            v-model:status="AdminData.status"
            v-model:page_module="AdminData.page_module"
            v-model:edit_image="AdminData.edit_image"
            :SelectImageGroup="SelectImageGroup"
            :list="AdminData.callback_list"
            @submit="SubmitModel"
          ></GenerateResult>
        </div>
      </div>
      <CustomLoading
        class="submit-loading-box"
        v-show="submit_loading"
      ></CustomLoading>
    </div>
    <div class="custom-image-edit-box" v-show="AdminData.page_module != 1">
      <CompositeImage
        v-model:status="AdminData.status"
        v-model:page_module="AdminData.page_module"
        v-model:edit_image="AdminData.edit_image"
      ></CompositeImage>
    </div>
    <CustomLoading v-show="loading"></CustomLoading>
  </div>
</template>

<script lang="ts" setup>
import CustomLoading from '@/components/custom/loading2.vue';
import CustomSelect from '@/components/custom/Select.vue';
import CustomTextArea from '@/components/custom/textarea.vue';
import CustomInput from '@/components/custom/input/index.vue';
import CustomResetButton from '@/components/custom/resetbutton.vue';
import GenerateResult from './components/GenerateResult';
import { useRequest } from '@/utils/http/http';
import {
  onBeforeMount,
  nextTick,
  onBeforeUnmount,
  reactive,
  ref,
  watch,
} from 'vue';
import ImgSizeRadioGroupVue from '@/components/custom/ImgSizeRadioGroup.vue';
import {
  getScenesList,
  useUploadStrategy,
  useSubmitConversationImage,
  useImageCallback,
} from '@/utils/api/scenes';
import { FormExample3 } from '@/utils/api/Task';
import { ChangePageHeight } from '@/utils/tool';
import { useRoute } from 'vue-router';
import { show_message } from '@/utils/tdesign_tool';
import CompositeImage from './components/CompositeImage.vue';
import { FilterForm, FilterFormType } from '@/constants/form';
const loading = ref(false);
// 提交图片时的加载状态
const submit_loading = ref(false);
const route = useRoute();
// 当前
const id = route.query.id;
// el
const GenerationBox = ref();

// 定时器
let IntervalImg: any = null;
// 上传策略状态
const StrategyStatus = ref(false);
// 右侧选择图片按钮组
const SelectImageGroup = ref({});
// 上传策略
const StrategyConfig = ref({});
const AdminData = reactive({
  list: [],
  // 回调图片列表
  // 'http://yunyi-tiktok.oss-cn-shenzhen.aliyuncs.com/files/avatar/admin/c3d37a14-7d1d-4ec5-aa67-20a447c094d6.png',
  callback_list: [],
  /**
   * 模特生成状态
   * loading-生成中
   * success-结束
   */
  status: '',
  /**
   * 当前显示的模块
   * 1--模特生成
   * 2--图片合成
   * 3--合成图片提交
   */
  page_module: 1,
  // 要修改的图片链接
  edit_image: '',
  reset_num: 1,
});
const scenario_id = ref();
//当前prompt
const current_prompt = ref('');
// 元素高度和页面高度比较
const getElementHeight = () => {
  if (GenerationBox.value) {
    ChangePageHeight(GenerationBox.value);
  }
};
// 获取后台配置的组件
const getAdminComponent = async () => {
  try {
    loading.value = true;
    console.log(JSON.stringify(FormExample3));
    let res: any = await getScenesList(id, 'id');
    if (res.code == 0) {
      // 取id
      scenario_id.value = res.data.id;
      let list = res.data.form;
      if (list.length) {
        const result = FilterFormType(list);
        list = result.list;
        if (result.al_config) {
          // 获取上传策略
          StrategyStatus.value = true;
        }
        if (result.select_image) {
          // 将列表传给右侧模块
          SelectImageGroup.value = result.select_image;
        }
      } else {
        show_message('表单未配置');
        return;
      }
      AdminData.list = list;
    }
    nextTick(() => {
      getElementHeight();
    });
    loading.value = false;
  } catch (e) {
    console.log(e);
    loading.value = false;
  }
};
const getStrategy = async () => {
  try {
    let res: any = await useUploadStrategy();
    if (res.code == 0) {
      StrategyConfig.value = res.data;
    }
  } catch (e) {
    console.log(e);
  }
};
watch(
  () => StrategyStatus.value,
  (v) => {
    if (v) {
      // 获取上传策略
      getStrategy();
    }
  }
);
// 提交模特
const SubmitModel = async (index: number) => {
  const url = SelectImageGroup.value.tool_url;
  if (!url) {
    show_message('tool_url empty');
  }
  let params: any = {};
  params.prompt = current_prompt.value;
  const newIndex = parseInt(index + '') - 1;
  params.url = AdminData.callback_list[newIndex];
  try {
    submit_loading.value = true;
    //   提交
    const res: any = await useRequest('post', url, params);
    console.log(res);
    submit_loading.value = false;
  } catch (e) {
    console.log(e);
    submit_loading.value = false;
  }
};
// 获取图片回调
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 && res.data.image.length) {
        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;
};
// 提交--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);
      //   保存prompt
      current_prompt.value = res.data.prompt;
      AdminData.status = 'loading';
    }
    console.log(res);
  } catch (e) {
    console.log(e);
  }
};
// 提交前的校验
const beforeSubmit = () => {
  // 定时器不能为开启状态
  if (IntervalImg) {
    show_message('请等待上一个任务完成');
    return;
  }
  const params = FilterForm(AdminData.list);
  if (params) {
    onSubmit(params);
  }
  console.log(params);
};
onBeforeMount(async () => {
  if (!id) {
    show_message('禁止访问');
    return;
  }
  // 获取组件列表
  await getAdminComponent();
});

onBeforeUnmount(() => {
  closeInterval();
});
</script>

<style lang="less">
@import '@/style/variables.less';
.custom-model-generation-box {
  padding: @page-padding-top 0;
  box-sizing: border-box;
  position: relative;
  width: 100%;
  height: 100%;
  .generation-box-parent {
    width: 100%;
    height: 100%;
    position: relative;
    .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;
        .basic-info {
          .label {
            margin: 4px 0 12px 0;
            color: #b1b5c4;
            font-weight: 300;
            font-size: @font-size-12;
            text-align: start;
          }
          .value {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            row-gap: 30px;
            .custom-input-global {
              width: 48%;
            }
            .custom-select-box {
              width: 48%;
            }
            .input-pay-num {
              width: 100%;
            }
          }
        }
        .confirm-box {
          flex: 1;
          display: flex;
          align-items: flex-end;
          justify-content: flex-end;
          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 {
            margin-left: 12px;
          }
        }
        & > :not(:first-child) {
          margin-top: 20px;
        }
      }
    }
  }
  .custom-image-edit-box {
    width: 100%;
    height: 100%;
  }
}
</style>
