<template>
  <div class="custom-image-generation-box">
    <div class="generation-box-parent">
      <div class="generation-box" v-show="!loading" ref="GenerationBox">
        <div class="interaction-form">
          <CustomForm
            :formList="AdminData.list"
            :config="StrategyConfig"
          ></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"
            :list="AdminData.callback_list"
          ></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 { onBeforeMount, onBeforeUnmount, reactive, ref, watch } from 'vue';
import {
  getScenesList,
  useUploadStrategy,
  useSubmitConversationImage,
  useImageCallback,
} from '@/utils/api/scenes';
import { FilterFormType } from '@/constants/form';
import { FormExample2, CustomNum } from '@/utils/api/Task';
import { Validationrules } from '@/utils/tool';
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 CurSubmitNum = ref(0);
// 上传策略状态
const StrategyStatus = ref(false);
// 上传策略
const StrategyConfig = ref({});
const AdminData = reactive({
  list: [],
  // 回调图片列表
  callback_list: [],
  /**
   * loading-生成中
   * success-结束
   */
  status: '',
  reset_num: 1,
});
const scenario_id = ref();
// 获取后台配置的组件
const getAdminComponent = async () => {
  try {
    loading.value = true;
    console.log(JSON.stringify(FormExample2));
    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) {
        list.push(CustomNum);
        const result = FilterFormType(list);
        list = result.list;
        if (result.al_config) {
          // 获取上传策略
          StrategyStatus.value = true;
        }
      } else {
        show_message('表单未配置');
        return;
      }
      AdminData.list = list;
    }
    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 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 ||
          res.data.image.length == CurSubmitNum.value
        ) {
          // 关闭定时器
          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 = [];
};
// 提交--ai图片任务
const onSubmit = async (params: any) => {
  try {
    let res: any = await useSubmitConversationImage({
      scenario_id: scenario_id.value,
      parameters: params,
    });
    if (res.code == 0) {
      // 记录本次提交的数量
      CurSubmitNum.value = params.number;
      // 开启定时器
      openInterval(res.data.uuid);
      AdminData.status = 'loading';
    }
    console.log(res);
  } catch (e) {
    console.log(e);
  }
};
// 提交前的校验
const beforeSubmit = () => {
  // 定时器不能为开启状态
  if (IntervalImg) {
    show_message('请等待上一个任务完成');
    return;
  }
  let params: any = {};
  // 遍历整个列表
  for (let i = 0; i < AdminData.list.length; i++) {
    let item: any = AdminData.list[i];
    for (let j = 0; j < item.lists.length; j++) {
      let it = item.lists[j];
      // 校验规则
      let message = Validationrules(it.rules, it.value, it.name);
      if (message) {
        // 提示错误信息
        show_message(message);
        return;
      } else {
        // 类型为图片尺寸且当前选择的是自定义
        if (it.type == 'radio_group_size' && it.value == '') {
          // 找到options列表里的自定义模块
          let customObj = it.options.find((opt: any) => opt.type == 'custom');
          if (customObj) {
            if (customObj.value1 && customObj.value2) {
              params[it.name] = customObj.value1 + 'x' + customObj.value2;
            } else {
              show_message('自定义图片尺寸未填写完整');
              return;
            }
          }
        }
        if (it.value) {
          if (it.name == 'number') {
            // 转换为number类型
            params[it.name] = parseFloat(it.value + '');
          } else {
            // 添加params
            params[it.name] = it.value;
          }
        }
      }
    }
  }
  console.log(params);
  onSubmit(params);
};
onBeforeMount(async () => {
  if (!id) {
    show_message('禁止访问');
    return;
  }
  // 获取组件列表
  await getAdminComponent();
});

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

<style lang="less">
@import '@/style/variables.less';
.custom-image-generation-box {
  padding: @page-padding-top 0;
  box-sizing: border-box;
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  .generation-box-parent {
    width: 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;
        .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 {
          display: flex;
          align-items: center;
          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>
