import { defineComponent, onMounted, reactive, ref } from 'vue';
import './index.less';
import EnterKeywords from './components/EnterKeywords';
import { useStore } from 'vuex';
import UploadImg from './components/UploadImg';
import { Button as TButton } from 'tdesign-vue-next';
import { Tasks } from '@/utils/api/Task';
import { filterRepeatTimestamp } from '@/utils/tool';
import {
  IntervalCheckTask,
  SubmitSplitImgTask,
  get_split_img_status,
} from '@/utils/api/userApi';
import { useSubmitStableTask } from '@/utils/api/wf_task';
import CustomDialog from './components/Dialog/index.vue';
import Animation from '@/components/Animation.vue';
import ConfirmDIalog from './components/confimDialog.vue';
// wf
export default defineComponent({
  setup(props, ctx) {
    const store = useStore();
    let custom_interval: any = null;
    let split_interval: any = null;
    const task_id = ref();
    // 确认弹窗
    const confirmDialogVisible = ref(false);
    const prompt_num = ref();
    const task_result_list = reactive<{
      list: any[];
    }>({
      list: [],
    });
    // 关键词
    const keywords = ref('');
    const loading = ref(false);
    const dialogloading = ref(true);
    // 图片链接
    const Img_url = ref('');
    // 弹窗状态
    const DialogVisible = ref(false);
    // 测试
    const test_num = ref(1);
    onMounted(() => {
      store.dispatch('user/AdminConfig');
    });
    // 获取返回的四宫格图片
    const getTask = async () => {
      try {
        let res: any = await IntervalCheckTask({
          task_id: task_id.value,
        });
        if (res.code == 0 && res.data.length) {
          res.data.forEach((item: any) => {
            if (item.loading === undefined) {
              item.loading = false;
            }
          });
          if (res.data.length > task_result_list.list.length) {
            // 合并去重
            filterRepeatTimestamp(task_result_list.list, res.data);
          }
          if (prompt_num.value == task_result_list.list.length) {
            // 关闭定时器
            closeInterval();
            dialogloading.value = false;
          } else {
            dialogloading.value = true;
          }
        }
      } catch (e) {
        console.log(e);
      }
    };
    // 获取返回的切割图片
    const get_split_img = async (prompt_id: number) => {
      try {
        let res: any = await get_split_img_status({
          prompt_id: prompt_id,
        });
        if (res.code == 0 && res.data.cut_img && res.data.id) {
          // 切割成功--找到list对应的id,将cut_img添加进去
          task_result_list.list.forEach((item: any) => {
            if (item.id == res.data.id) {
              item.split_img = res.data.cut_img;
              item.loading = false;
            }
          });
          // 关闭定时器
          closeSplitTaskInterval();
        }
      } catch (e) {
        console.log(e);
      }
    };
    // 打开定时器
    const openInterval = () => {
      custom_interval = window.setInterval(() => {
        getTask();
      }, 3000);
    };
    // 打开图片切割任务定时器
    const openSplitTaskInterval = (prompt_id: number) => {
      split_interval = window.setInterval(() => {
        get_split_img(prompt_id);
      }, 3000);
    };
    // 关闭定时器
    const closeInterval = () => {
      if (custom_interval) {
        window.clearInterval(custom_interval);
      }
    };
    // 关闭图片切割任务定时器
    const closeSplitTaskInterval = () => {
      if (split_interval) {
        window.clearInterval(split_interval);
      }
    };
    const submit_before = () => {
      if (!keywords.value) {
        return;
      }
      // 打开的确认弹窗
      confirmDialogVisible.value = true;
      // submit();
    };
    // 确认对话框的确认事件
    const CanSubmit = () => {
      if (!keywords.value) {
        return;
      }
      submit();
    };
    // 提交任务
    const submit = async () => {
      // prompt_img需要传数组
      let params: any = {
        type: Img_url.value ? Tasks.img_to_img : Tasks.text_to_img,
        prompt: keywords.value,
        prompt_img: [Img_url.value],
        prompt_num: 5,
      };
      try {
        loading.value = true;
        // 请求
        let res: any = await useSubmitStableTask(params);
        if (res.code == 0) {
          task_id.value = res.data.task_id;
          prompt_num.value = res.data.prompt_num;
          // 打开弹窗
          DialogVisible.value = true;
          // 清空已返回的图片
          task_result_list.list = [];
          // 开启轮询
          openInterval();
        }
        loading.value = false;
      } catch (e) {
        console.log(e);
        loading.value = false;
      }
    };
    // 提交切割任务
    const SubmitSplit = async ({ prompt_id, click_id, index }: any) => {
      try {
        let res: any = await SubmitSplitImgTask({
          prompt_id: prompt_id,
          cut_id: click_id,
        });
        if (res.code == 0) {
          // 检测切割任务是否完成
          openSplitTaskInterval(res.data.prompt_id);
          // 将对应的item.loading打开
          task_result_list.list[index].loading = true;
        }
      } catch (e) {
        console.log(e);
      }
    };
    return () => (
      <div class="img-to-img-page">
        <div class="tips">提示：可不上传图片</div>
        <EnterKeywords v-model={keywords.value}></EnterKeywords>
        <UploadImg v-model={Img_url.value}></UploadImg>
        <TButton
          onClick={submit_before}
          class={['submit-button', !keywords.value ? 'disabled' : '']}
        >
          提交
        </TButton>
        <CustomDialog
          v-model={DialogVisible.value}
          list={task_result_list.list}
          dialogloading={dialogloading.value}
          onSubmitSplit={SubmitSplit}
        ></CustomDialog>
        <Animation position={'fixed'} v-show={loading.value}></Animation>
        <ConfirmDIalog
          v-model={confirmDialogVisible.value}
          onSubmit={CanSubmit}
        ></ConfirmDIalog>
      </div>
    );
  },
});
