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,
  Select as TSelect,
  Option as TOption,
  MessagePlugin,
} 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 CustomDialog from './components/Dialog/index.vue';
import Animation from '@/components/Animation.vue';
import ConfirmDIalog from './components/confimDialog.vue';
import { new_task_submit } from '@/utils/api/wf_task';
import DescribeDIalog from './components/DescribeDIalog.vue';
import { show_message } from '@/utils/tdesign_tool';
// 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 DialogVisible = ref(false);
    // 文本生成弹窗
    const DescribeDIalogVisible = ref(false);
    const prompt_num = ref();
    const task_result_list = reactive<{
      list: any[];
    }>({
      list: [],
    });
    // 三种任务
    const MidjourneyTaskType = [
      {
        // 两种都可以
        label: 'imagine',
        value: 1,
      },
      // 多图上传--
      {
        label: 'blend',
        value: 2,
      },
      // describe生成描述
      {
        label: 'describe',
        value: 3,
      },
    ];
    // select当前的值
    const SelectValue = ref(1);
    // 关键词
    const keywords = ref('');
    const loading = ref(false);
    const dialogloading = ref(true);
    // 图片链接--单图
    const Img_url = ref('');
    // 多图上传列表
    const ImgList = reactive({
      list: [
        {
          img_url: '',
        },
      ],
    });

    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);
      }
    };
    // select的值变化
    const SelectChange = (value: any) => {
      ImgList.list = [{ img_url: '' }];
      Img_url.value = '';
      keywords.value = '';
    };
    // 获取返回的切割图片
    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);
        clearInterval(custom_interval);
        custom_interval = null;
      }
    };
    // 关闭图片切割任务定时器
    const closeSplitTaskInterval = () => {
      if (split_interval) {
        window.clearInterval(split_interval);
        clearInterval(split_interval);
        split_interval = null;
      }
    };
    const submit_before = () => {
      if (SelectValue.value == 1) {
        if (!keywords.value) {
          show_message('请填写关键词');
          return;
        }
      } else if (SelectValue.value == 2) {
        // 多图上传-至少两张
        if (ImgList.list.length < 2) {
          show_message('至少上传两张图片');
          return;
        }
        //
        let list: any[] = [];
        ImgList.list.forEach((item: any) => {
          if (item.img_url) {
            list.push(item.img_url);
          }
        });
        if (list.length < 2) {
          show_message('至少上传两张图片');
          return;
        }
      } else if (SelectValue.value == 3) {
        // 生成文字描述
        if (!ImgList.list[0].img_url) {
          show_message('请上传图片');
          return;
        }
      }
      // 打开的确认弹窗
      confirmDialogVisible.value = true;
      // submit();
    };
    // 确认对话框的确认事件
    const CanSubmit = () => {
      if (!keywords.value) {
        return;
      }
      submit();
    };
    // 增加一个上传图片box
    const add_img_box = () => {
      if (SelectValue.value == 2 && ImgList.list.length < 5) {
        ImgList.list.push({
          img_url: '',
        });
      }
    };
    // 提交任务
    const submit = async () => {
      // prompt_img需要传数组
      // 公共数据
      let params: any = {
        prompt_num: 5,
        command_type: SelectValue.value,
      };
      if (SelectValue.value == 1) {
        params.type = Img_url.value ? Tasks.img_to_img : Tasks.text_to_img;
        params.prompt = keywords.value;
        params.prompt_img = [ImgList.list[0].img_url];
      } else if (SelectValue.value == 2) {
        let list: any[] = [];
        ImgList.list.forEach((item: any) => {
          list.push(item.img_url);
        });
        params.prompt_img = list;
      } else if (SelectValue.value == 3) {
        params.prompt_img = [ImgList.list[0].img_url];
      }

      try {
        loading.value = true;
        // 请求
        let res: any = await new_task_submit(params);
        if (res.code == 0) {
          task_id.value = res.data.task_id;
          prompt_num.value = res.data.prompt_num;
          if (SelectValue.value == 1) {
            // img任务
            // 打开弹窗
            DialogVisible.value = true;
            // 清空已返回的图片
            task_result_list.list = [];
            // 开启轮询
            openInterval();
          } else if (SelectValue.value == 2) {
            // blend 多图上传
          } else if (SelectValue.value == 3) {
            // 生成描述--打开生成文本弹窗
            DescribeDIalogVisible.value = true;
          }
        }
        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,
          type: 2,
        });
        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>
        <TSelect
          class="custom-mid-select"
          v-model={SelectValue.value}
          placeholder="请选择"
          onChange={SelectChange}
        >
          {MidjourneyTaskType.map((item: any) => (
            <TOption
              key={item.value}
              value={item.value}
              label={item.label}
            ></TOption>
          ))}
        </TSelect>
        {/* 1才输入文字 */}
        {SelectValue.value == 1 ? (
          <EnterKeywords v-model={keywords.value}></EnterKeywords>
        ) : (
          ''
        )}
        <div class="label">原图</div>
        <div class="custom-real-upload">
          <div class="real-upload-content">
            {ImgList.list.map((item: any) => (
              <UploadImg v-model={item.img_url}></UploadImg>
            ))}
          </div>
        </div>
        {SelectValue.value == 2 ? (
          <div>
            <TButton class="submit-button" onClick={add_img_box}>
              添加上传图片box
            </TButton>
          </div>
        ) : (
          ''
        )}
        <TButton onClick={submit_before} class={['submit-button']}>
          提交
        </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>
        {/* 文本dialog */}
        <DescribeDIalog
          v-model={DescribeDIalogVisible.value}
          text=""
        ></DescribeDIalog>
      </div>
    );
  },
});
