<script setup lang="ts">
import { commonApi } from '@/api/common';
import { cloneDeep } from 'lodash-es';
import { useMessage } from 'naive-ui';
import { defineProps, ref } from 'vue';

const props = defineProps({
  formData: {
    type: Object,
    default: () => ({}),
  },
  type:{
    type: String,
    default: "",
  }
})
debugger
const emit = defineEmits(['closePublishImg'])
const message = useMessage()

const isVisible = ref(true)
const fileInput = ref<HTMLInputElement | null>(null)
const rules = {
  title: {
    required: true,
    message: '',
    trigger: 'blur',
  },
}
function triggerFileInput() {
  (fileInput.value as HTMLInputElement)?.click()
}

async function handleFileChange(event: Event) {
  // console.log('object', formData)
  const target = event.target as HTMLInputElement
  const files = target.files

  if (files && files.length > 0) {
    try{
      const res = await uploadImagesInBatches(files)
      const urlList = res.map(item => item.url)
      props.formData.imagePaths.push(...urlList)
    }catch(err){
      console.log(err);
    }
  }
  target.value = ''
}
// 获取图片标签
const imgLabelList = ref([])
async function getDictType() {
  try {
    const res = await commonApi.dictType({ type: 'image_label' })
    imgLabelList.value = res.data
  }
  catch (error) {
    console.log(error)
  }
}

// 发布
async function onPublish() {
  try {
    const param = cloneDeep(props.formData)
    param.imagePaths = param.imagePaths.join(',')
    param.tags = param.tags.join(',')
    if (param.id) {
      const res = await request.post('/image/update', param)
      if (res.code === 200) {
        message.success('发布成功')
        emit('closePublishImg')
      }
    }
    else {
      const res = await request.post('/image/publish', param)
      if (res.code === 200) {
        message.success('发布成功')
        emit('closePublishImg')
      }
    }
  }
  catch (error) {
    console.log(error)
  }
}
getDictType()
defineExpose({
  isVisible,
})
function closePublishImg() {
  emit('closePublishImg')
}
</script>

<template>
  <div>
    <n-modal
      v-model:show="isVisible"
      :preset="null"
      transform-origin="center"
      :mask-closable="false"
      class="custom-modal"
    >
      <div class="bg-white p-4 rounded-lg w-[600px]">
        <div class="flex justify-between items-center">
          <div class="text-[18px]">
            上传我的图片
          </div>
          <div
            class="w-[20px] h-[20px] text-[#999] text-center cursor-pointer" @click="closePublishImg"
          >
            X
          </div>
        </div>
        <div>
          <div class="upload-content">
            <div class="flex flex-col bg-[#f3f5f9] justify-center items-center w-30 h-30 border border-dashed mt-2 rounded-lg bg-white">
              <div class="w-24 bg-gradient-to-r from-[#2D28FF] to-[#1A7DFF] h-8 text-white rounded-sm bg-[#3162ff] cursor-pointer flex justify-center items-center mt-6" @click="triggerFileInput()">
                上传文件
              </div>
              <div class="my-3">
                点击上传文件
              </div>
              <!-- <div class="text-[#999999] text-xs">
                .json/.zip
              </div> -->
            </div>
          </div>
          <div class="grid grid-cols-3 gap-2.5 mt-4 w-full">
            <div v-for="(item, index) in props.formData.imagePaths" :key="index">
              <img class="w-full h-[180px] object-cover rounded-lg" :src="item" alt="">
            </div>
          </div>
          <!-- <div class="flex justify-center items-center my-2 gap-1 flex-wrap">
            <div v-for="(item, index) in formData.imagePaths" :key="index" class="w-1/3">
              <img :src="item" alt="" class="w-full h-[200px]">
            </div>
          </div> -->
          <div class="mt-2">
            <n-form
              :label-width="80"
              :model="formData"
              :rules="rules"
              size="large"
            >
              <n-form-item label="图片标题" path="title">
                <n-input v-model:value="props.formData.title" placeholder="好的标题可以获得更好的曝光率" />
              </n-form-item>

              <n-form-item label="图片标签" path="tags" class="w-full">
                <n-select
                  v-model:value="props.formData.tags"
                  placeholder="选择你的图片类型,比如 男生, 机械, 建筑设计 等"
                  multiple label-field="dictLabel"
                  value-field="dictValue" :options="imgLabelList"
                />
              </n-form-item>

              <n-form-item label="描述信息" path="description">
                <n-input
                  v-model:value="props.formData.description"
                  placeholder="填写更全面的描述信息"
                  type="textarea"
                  :autosize="{
                    minRows: 3,
                    maxRows: 5,
                  }"
                />
              </n-form-item>
            </n-form>
          </div>
        </div>
        <div class="flex justify-center items-center mt-5 text-white w-30 h-10 rounded-lg bg-[#3162ff] cursor-pointer" @click="onPublish">
          发布
        </div>
      </div>
    </n-modal>
    <input
      ref="fileInput"
      type="file"
      class="hidden"
      accept="image/*"
      multiple
      @change="handleFileChange"
    >
  </div>
</template>

<style scoped>

</style>
