<script setup>
import { getChuanKitDesignList } from '../api'
import { useUserStore } from '@/stores/user'
import { uploadFileByUrl } from '@/utils/upload'

const ChuangKitDesign = defineAsyncComponent(() => import('@/components/ChuangKitDesign.vue'))

const emit = defineEmits(['update', 'update:modelValue'])

const userStore = useUserStore()

const designVisible = ref(false)
const data = reactive({
  list: [],
  count: 0,
})
async function fetchList() {
  const res = await getChuanKitDesignList({
    user_flag: userStore.user.id,
    kind_id: 29,
    page_no: 1,
    page_size: 1000,
    time_order: 1,
  })
  Object.assign(data, res.data)
}
onMounted(fetchList)

function onClose() {
  designVisible.value = false
  fetchList()
}

const active = ref(null)
async function handleClick(item) {
  active.value = item
}

async function handleSubmit() {
  const url = await uploadFileByUrl(active.value.thumbUrl)
  emit('update', url)
  emit('update:modelValue', false)
}
</script>

<template>
  <el-dialog title="图库选择" :close-on-click-modal="false" @closed="$emit('update:modelValue', false)" width="860px">
    <div class="image-design">
      <el-button type="primary" @click="designVisible = true">打开编辑器</el-button>
      <ul>
        <li
          v-for="item in data.list"
          :key="item.designId"
          :class="{ active: item.designId === active?.designId }"
          @click="handleClick(item)">
          <img :src="item.thumbUrl" />
        </li>
      </ul>
      <ChuangKitDesign :kindId="29" @close="onClose" v-if="designVisible"></ChuangKitDesign>
    </div>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" round auto-insert-space :disabled="!active" @click="handleSubmit">确定</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.image-design {
  ul {
    margin: 30px auto;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 30px;
  }
  li {
    width: 140px;
    border-radius: 20px;
    overflow: hidden;
    cursor: pointer;
    box-sizing: border-box;
    &.active {
      border: 5px solid var(--main-color);
    }
  }
  img {
    width: 100%;
  }
}
</style>
