<template>
  <div class="custom-chose-model-dialog">
    <t-dialog
      class="chose-model-dialog"
      v-model:visible="visible"
      placement="center"
      :cancelBtn="null"
    >
      <template #confirmBtn>
        <ResetButton @click="ConfirmEnvent">确认</ResetButton>
      </template>
      <template #header>
        {{ dialog_title }}
      </template>
      <template #body>
        <div class="model-dialog-box">
          <CustomInput
            v-model="InputValue"
            :placeholder="placeholder"
            @inputChange="InputChange"
            align="left"
            class="select-model-input"
          >
            <template #rightIcon>
              <span class="right-input-icon">
                <ChevronDown></ChevronDown>
              </span>
            </template>
          </CustomInput>
          <div ref="ScrollELement" class="search-area-box narrow-scrollbar">
            <OnWaitVue
              v-if="SearchStatus == 'wait'"
              label="未有图片，快去上方输入模特样式吧"
            ></OnWaitVue>
            <OnLoading
              v-else-if="SearchStatus == 'loading'"
              label="搜索中"
            ></OnLoading>
            <div class="search-result-image" v-else-if="SearchList.list.length">
              <img
                v-for="(item, index) in SearchList.list"
                :key="index"
                :src="item.url"
                @click="ChoseModel(item, index)"
                :class="{ 'image-active': index == SearchList.index }"
              />
              <template
                v-for="(item, index) in SearchList.list"
                :key="item.image + '1'"
              >
                <i v-if="index !== SearchList.list.length - 1"></i>
              </template>
            </div>
            <OnWaitVue v-else label="未搜索到模特"></OnWaitVue>
          </div>
          <ScrollLoad
            :el="ScrollELement"
            :maxLen="maxLen"
            :curLen="SearchList.list.length"
            :hasMorePages="hasMorePages"
            :loadingMore="loadingMore"
            @submit="onSearchSubmit"
          ></ScrollLoad>
        </div>
      </template>
    </t-dialog>
    <ResetButton class="open-dialog-btn" @click="visible = true">{{
      label
    }}</ResetButton>
  </div>
</template>

<script lang="ts" setup>
import ResetButton from '@/components/custom/resetbutton.vue';
import { Dialog as TDialog } from 'tdesign-vue-next';
import { reactive, ref, watch } from 'vue';
import CustomInput from '@/components/custom/input/index.vue';
import ChevronDown from '@/assets/svg/select/chevron-down.svg';
import OnWaitVue from './ImgLoadingStatus/OnWait.vue';
import OnLoading from './ImgLoadingStatus/OnLoading.vue';
import { debounce } from '@/utils/tool';
import { show_message } from '@/utils/tdesign_tool';
import ScrollLoad from './ScrollLoad.vue';
import { useRequest } from '@/utils/http/http';
const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    dialog_title?: string;
    label?: string;
    placeholder?: string;
    tool_url: string;
    sub_type?: number;
    value: string;
    name: string;
  }>(),
  {
    sub_type: 0,
    placeholder: '请输入',
    label: '选择模特',
    dialog_title: '请选择',
  }
);
const emit = defineEmits(['update:value', 'update:modelValue', 'SubmitImage']);
const ScrollELement = ref<HTMLElement>();
const maxLen = ref(19);
const hasMorePages = ref(false);
const loadingMore = ref(false);
const pageNum = ref(1);
const pageSize = ref(20);
const visible = ref(props.modelValue);
const InputValue = ref('');
// 当前搜索状态
const SearchStatus = ref('wait');
const SearchList = reactive({
  list: [],
  //   当前选择的图片
  url: '',
  prompt: '',
  // 当前下标
  index: null,
});
// 确认事件
const ConfirmEnvent = () => {
  if (!SearchList.url) {
    show_message('未选择图片');
    return;
  }
  // 关闭弹窗并提交图片
  visible.value = false;
  emit('update:value', SearchList.url);
  emit('SubmitImage', {
    url: SearchList.url,
    prompt: SearchList.prompt,
    name: props.name,
  });
};
// 可以搜索
const onSearchSubmit = () => {
  pageNum.value += 1;
  loadingMore.value = true;
  Search();
};
const Search = async () => {
  console.log('开始搜索');
  try {
    if (!InputValue.value) {
      return;
    }
    const { tool_url, sub_type } = props;
    if (!tool_url || !sub_type) {
      show_message('未配置搜索功能');
      return;
    }
    if (pageNum.value == 1) {
      SearchStatus.value = 'loading';
    }
    // 本地使用代理
    const url =
      import.meta.env.MODE == 'development'
        ? '/api/users/photo/search'
        : tool_url;
    const res: any = await useRequest('post', url, {
      query: InputValue.value,
      page: pageNum.value,
      limit: pageSize.value,
      type: sub_type,
    });
    console.log(res);
    if (res.code == 0) {
      if (pageNum.value == 1) {
        SearchList.list = res.data.data;
      } else {
        SearchList.list = SearchList.list.concat(res.data.data);
      }
      loadingMore.value = false;
      //   success
      SearchStatus.value = 'success';
      if (res.data.data.length == pageSize.value) {
        hasMorePages.value = true;
      } else {
        hasMorePages.value = false;
      }
    }
  } catch (e) {
    console.log(e);
  }
};
// 选择模特
const ChoseModel = (item: any, index: number) => {
  if (index !== SearchList.index) {
    SearchList.index = index;
    SearchList.url = item.url;
    SearchList.prompt = item.title;
  }
};
watch(
  () => InputValue.value,
  (v) => {
    if (v) {
      pageNum.value = 1;
    }
  }
);
// 防抖
const InputChange = debounce(Search, 1000);
watch(
  () => props.modelValue,
  (v) => {
    visible.value = v;
  }
);

watch(
  () => visible.value,
  (v) => {
    emit('update:modelValue', v);
  }
);
</script>

<style lang="less">
@import '@/style/variables.less';
.custom-chose-model-dialog {
  width: 48%;
  .open-dialog-btn {
    width: 100% !important;
  }
  .chose-model-dialog {
    .t-dialog {
      background: #2d2d2d;
      border: none;
      width: 600px;
      .t-dialog__header-content {
        color: white;
      }
      .t-dialog__close {
        color: #ddd;
        &:hover {
          color: #2d2d2d;
        }
      }
    }
    .model-dialog-box {
      margin-top: 6px;
      .select-model-input {
        width: 100% !important;
        height: auto !important;
        color: white;
        .right-input-icon {
          padding-right: 12px;
        }
      }
      .search-area-box {
        width: 100%;
        height: 389px;
        background: #181818;
        border: @main-border;
        border-radius: 8px;
        margin-top: 6px;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow-y: auto;
        .search-result-image {
          width: 100%;
          height: 100%;
          padding: 12px;
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          row-gap: 12px;
          i {
            width: 150px;
          }
          img {
            width: 150px;
            height: 150px;
            border-radius: 8px;
            cursor: pointer;
            border: 1.5px solid transparent;
            transition: border 0.2s;
          }
          .image-active {
            border: 1.5px solid #00f9f9;
            transition: border 0.2s;
          }
        }
      }
    }
  }
}
</style>
