<script setup lang="ts">
import { cloneDeep } from 'lodash-es';
import { Asterisk, Trash } from 'lucide-vue-next';
import { useRoute, useRouter } from 'vue-router';

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
})
const emit = defineEmits(['update:modelValue', 'preStep'])
const router = useRouter()

const route = useRoute()

const { type } = route.query

const message = useMessage()
const loading = ref(false)

const localForm = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  },
})
function preStep() {
  emit('preStep')
}
const showSuccessModal = ref(false)


//发布
async function handlePublish() {
  for (let i = 0; i < localForm.value.modelVersionList.length; i++) {
    if (localForm.value.modelVersionList[i].delFlag === '0' && localForm.value.modelVersionList[i].sampleImagePaths.length === 0) {
      return message.error('请上传图片')
    }
  }
  try {
    const param = cloneDeep(localForm.value)
    if (param.modelProduct.tagsList.length !== 0) {
      param.modelProduct.tags = JSON.stringify(param.modelProduct.tagsList)
    }
    else {
      param.modelProduct.type = '[]'
    }
    for (let i = 0; i < param.modelVersionList.length; i++) {
      if (param.modelVersionList[i].sampleImagePaths.length !== 0) {
        param.modelVersionList[i].sampleImagePaths = param.modelVersionList[i].sampleImagePaths.join(',')
      }
      else {
        param.modelVersionList[i].sampleImagePaths = ''
      }
    }
    
    if (type === 'add') {
      try {
        const res = await request.post('/model/insert', param)
        if (res.code === 200) {
          showSuccessModal.value = true
        }
      }
      catch (error) {
        console.log(error)
      }
    }
    else {
      try {
        const res = await request.post('/model/update', param)
        if (res.code === 200) {
          showSuccessModal.value = true
        }
      }
      catch (error) {
        console.log(error)
      }
    }
  }
  catch (error) {
    console.log(error)
  }
}
watch(
  () => localForm.value,
  (newVal) => {
    emit('update:modelValue', newVal)
  },
  { immediate: true, deep: true },
)
const fileInput = ref<HTMLInputElement | null>(null)
const uploadFileIndex = ref(0)


//点击上传按钮
function triggerFileInput(index: number) {
  (fileInput.value as HTMLInputElement)?.click()
  uploadFileIndex.value = index
}

//选择上传图片
async function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement
  const files = target.files
  if (files && files.length > 0) {
    const sum = localForm.value.modelVersionList[uploadFileIndex.value].sampleImagePaths.length + files.length
    if (sum >= 20)
      return message.error('最多20张')
      try{
        loading.value = true
        const res = await uploadImagesInBatches(files)
        const urlList = res.map(item => item.url)
        localForm.value.modelVersionList[uploadFileIndex.value].sampleImagePaths.push(...urlList)
      }catch(err){
        console.log(err);
      }finally{
        loading.value = false
      }
  }
  target.value = ''
}

// 发布成功后的确认按钮 跳转到个人中心
function onPositiveClick() {
  showSuccessModal.value = false
  router.push('/personal-center')
}

// 删除图片
const deleteSampleImage = (index:number, data:any) =>{
  data.splice(index, 1)
}
</script>

<template>
  <div class="mx-auto mt-10">
    <div class="w-[700px] mx-auto items-start rounded-lg">
      <template v-for="(item, index) in localForm.modelVersionList" :key="index">
        <div v-if="item.delFlag === '0'" class="w-full bg-gray-100 p-4 rounded-lg mt-2">
          <div class="flex justify-between items-center">
            <div>
              版本名: <span>{{ item.versionName }}</span>
            </div>
            <div>
              <n-checkbox
                v-model:checked="item.hideImageGenInfo"
                :checked-value="1" :unchecked-value="0"
              />
              隐藏图片生成信息
            </div>
          </div>
          <div class="flex justify-between items-center mt-4">
            <div class="flex">
              添加版本示例图片
              <Asterisk :size="10" color="#ff0000" class="mt-1" />
            </div>
            <div class="text-[12px] text-gray-400">
              最多20张图片, 图片不超过30M
            </div>
          </div>
          <n-spin :show="loading">
          <div>
            <div class="flex flex-col justify-center items-center w-30 h-40 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" @click="triggerFileInput(index)">
                上传文件
              </div>
              <div class="my-3">
                点击上传图片
              </div>
              <div class="text-[#999999] text-xs">
                请勿上传裸露、暴力、血腥或其他包含非法信息图片
              </div>
            </div>
          </div>
        </n-spin>

          <div class="grid grid-cols-3 gap-2.5 mt-4 w-full">
            <div v-for="(subItem, subIndex) in item.sampleImagePaths" :key="subIndex" class="relative">
              <img class="w-full h-[200px] object-cover rounded-lg" :src="subItem" alt="">
              <Trash @click="deleteSampleImage(subIndex, item.sampleImagePaths)" :size="20" class="mt-1 absolute top-2 right-2 text-gray-400 cursor-pointer hover:text-gray-100" />
            </div>
          </div>
        </div>
      </template>
    </div>
    <div class="flex items-center justify-center mt-5">
      <div class="flex justify-center items-center mt-5  w-[20%] mx-2 h-10 rounded-lg bg-[#f1f2f7] cursor-pointer" @click="preStep">
        上一步
      </div>
      <div class="flex justify-center items-center mt-5 text-white mx-2 w-[20%] h-10 rounded-lg bg-[#3162ff] cursor-pointer" @click="handlePublish">
        发布
      </div>
    </div>
  </div>
  <input
    ref="fileInput"
    type="file"
    class="hidden"
    accept="image/*"
    multiple
    @change="handleFileChange"
  >

  <!-- 成功之后的弹框 -->
  <n-modal
    v-model:show="showSuccessModal"
    :mask-closable="false"
    preset="dialog"
    title="发布成功！"
    content="工作流发布成功， 可至个人中心查看状态"
    positive-text="确认"
    @positive-click="onPositiveClick"
  />
</template>

<style scoped>

</style>
