<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: [
    { designId: 1, thumbUrl: 'https://webapp-pub.ezijing.com/upload/saas-dml-pro/design/1.JPG' },
    { designId: 2, thumbUrl: 'https://webapp-pub.ezijing.com/upload/saas-dml-pro/design/2.JPG' },
    { designId: 3, thumbUrl: 'https://webapp-pub.ezijing.com/upload/saas-dml-pro/design/3.JPG' },
    { designId: 4, thumbUrl: 'https://webapp-pub.ezijing.com/upload/saas-dml-pro/design/4.JPG' },
    { designId: 5, thumbUrl: 'https://webapp-pub.ezijing.com/upload/saas-dml-pro/design/5.JPG' },
    { designId: 6, thumbUrl: 'https://webapp-pub.ezijing.com/upload/saas-dml-pro/design/6.JPG' },
  ],
})
async function fetchList() {
  return false
  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" v-if="false">打开编辑器</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;
    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%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
