<template>
  <KlNavTab />
  <div class="mx-auto mt-[30px] box-border w-[1200px] border border-[#EEEEEE] rounded-[12px] border-solid bg-white px-[30px] py-[40px]">
    <el-form ref="formRef" :model="form" label-width="110px" size="large">
      <el-form-item label-width="110px" label="标题：" prop="title" :rules="{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }">
        <el-input v-model="form.title" placeholder="请输入标题" class="w-[361px]!" maxlength="128"></el-input>
      </el-form-item>
      <el-form-item label-width="110px" label="分类：" prop="projectType" :rules="{ required: true, message: '请选择分类', trigger: ['blur', 'change'] }">
        <el-select v-model="form.projectType" placeholder="请选择分类" class="w-[361px]!" multiple>
          <el-option v-for="(item, index) in projectTypeList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label-width="110px" label="标签：" prop="labels" :rules="{ required: true, message: '请选择标签', trigger: ['blur', 'change'] }">
        <el-select
          v-model="form.labels"
          :remote-method="remoteMethod"
          :loading="loading"
          multiple
          filterable
          remote
          placeholder="请输入搜索标签"
          class="w-[361px]!"
        >
          <el-option v-for="(item, index) in labelsList" :key="index" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label-width="110px" label="金币：" prop="points" :rules="{ required: true, message: '请输入金币', trigger: ['blur', 'change'] }">
        <el-input-number v-model="form.points" :controls="false" :precision="0" :min="0" placeholder="请输入金币" class="w-[361px]! text-left!"></el-input-number>
      </el-form-item>

      <el-form-item
        label-width="110px"
        label="上传封面："
        prop="coverImages"
        :rules="{ required: true, message: '请上传上传封面', trigger: ['blur', 'change'] }"
      >
        <KlUploader
          v-model:file-list="form.coverImages"
          list-type="picture-card"
          :limit="1000"
          :size="1"
          tips="上传图片支持jpg/gif/png格式、第一张为封面图片、每张图片大小不得超过1M"
          @validate="formRef.validateField('coverImages')"
        >
          <div class="h-[77px] w-[161px] flex items-center justify-center border border-[#cdd0d6] rounded-[1px] border-dashed bg-[#fafafa]">
            <el-icon class="text-[#999999]"><Plus /></el-icon>
            <div class="ml-[4px] mt-[2px] text-[14px] text-[#999999] font-normal">上传图纸</div>
          </div>
        </KlUploader>
      </el-form-item>

      <el-form-item label-width="110px" label="上传附件：" prop="files" :rules="{ required: true, message: '请上传附件', trigger: ['blur', 'change'] }">
        <KlUploader v-model:file-list="form.files" tips="请将系列文件分别压缩后上传，支持批量上传"> </KlUploader>
      </el-form-item>
      <el-form-item
        label-width="110px"
        label="描述："
        prop="description"
        :rules="[
          { required: true, message: '请输入描述', trigger: ['blur', 'change'] },
          {
            validator: (rule, value, callback) => {
              console.log(rule)
              if (value.length < 70) {
                callback(new Error('输入内容不能少于 70 字'))
              } else {
                callback()
              }
            },
            trigger: ['blur', 'change'],
          },
        ]"
      >
        <el-input v-model="form.description" type="textarea" :rows="6" placeholder="请输入描述" class="w-[361px]!" minlength="70" show-word-limit></el-input>
      </el-form-item>
      <!-- 添加预览和保存按钮 -->
      <el-form-item label-width="110px" label=" ">
        <div class="flex justify-start">
          <!-- <el-button @click="save" :loading="saveLoading" type="primary" class="btn">预览</el-button> -->
          <el-button :loading="saveLoading" type="primary" class="btn" @click="save">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  import KlUploader from '~/components/kl-uploader/index.vue'
  import { parent, keywords, labels } from '~/api/upnew/index'
  import { create } from '~/api/toolbox/index.js'
  import type { TcreateReq } from '~/api/toolbox/types'
  const router = useRouter() // 导入路由实例，用于跳转页面

  const form = reactive<TcreateReq>({
    title: '',
    projectType: [],
    labels: [],
    points: 0,
    coverImages: [],
    files: [],
    description: '',
  })

  const loading = ref(false)
  /** 获取标签 */
  const labelsList = ref<any>([])
  const remoteMethod = (query: string) => {
    if (query) {
      loading.value = true
      keywords({
        type: 1,
        keywords: query,
      })
        .then((res) => {
          labelsList.value = res.data
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      labelsList.value = []
    }
  }

  const formatTypeList = ref<any>([])
  const getFormatTypeList = () => {
    labels({
      type: 2,
    }).then((res) => {
      // @ts-ignore
      formatTypeList.value = res.data[0]
    })
  }
  getFormatTypeList()

  const projectTypeList = ref<any>([])
  /** 获取分类下拉框 */
  const getParent = () => {
    parent({
      type: 1,
      parentId: 0,
    }).then((res) => {
      projectTypeList.value = res.data
    })
  }
  getParent()

  /** 版本 */
  const editionsList = ref<any>([])
  const getEditionsList = () => {
    parent({
      type: 2,
      parentId: 0,
    }).then((res) => {
      editionsList.value = res.data
    })
  }
  getEditionsList()

  const formRef = ref()
  const saveLoading = ref(false)
  const save = () => {
    formRef.value.validate((valid: any) => {
      if (valid) {
        // 工具箱接口添加
        create(form)
          .then((res) => {
            console.log(res)
            if (res.code === 0) {
              ElMessage.success('发布成功')
              router.back()
              // window.setTimeout(() => {
              //   window.close()
              // }, 1000)
            }
          })
          .finally(() => {
            saveLoading.value = false
          })
      } else {
        console.log('error submit!')
      }
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.btn) {
    padding: 20px 40px !important;
  }
</style>
