<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref } from 'vue'
import { NewsTableData } from '@/api/manage/types'
import { useValidator } from '@/hooks/web/useValidator'
import { IDomEditor } from '@wangeditor/editor'
import { useStorage } from '@/hooks/web/useStorage'
import { Icon } from '@/components/Icon'
import { uploadFile } from '@/api/common'
const { required } = useValidator()
const { getStorage } = useStorage()
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<NewsTableData>>,
    default: () => null
  }
})

const articlePic = ref(props.currentRow?.articlePic)

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods
type InsertFnType = (url: string, alt: string, href: string) => void
const schema = reactive<FormSchema[]>([
  {
    field: 'articleTitle',
    label: '文章标题',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'introduce',
    label: '文章简介',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea',
      placeholder: '请输入'
    }
  },
  {
    field: 'categoryId',
    label: '文章类目',
    component: 'Select',
    colProps: {
      span: 8
    },
    componentProps: {
      options: [
        {
          label: '新闻资讯',
          value: '0'
        },
        {
          label: '经典案例',
          value: '1'
        },
        {
          label: '解决方案',
          value: '2'
        },
        {
          label: '技术支持',
          value: '3'
        }
      ]
    }
  },
  {
    field: 'weight',
    label: '权重',
    component: 'InputNumber',
    value: 0,
    colProps: {
      span: 8
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'articleViews',
    label: '当前浏览量',
    component: 'InputNumber',
    value: 0,
    colProps: {
      span: 8
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'articlePic',
    component: 'Upload',
    label: '文章展图',
    componentProps: {
      httpRequest: (data: any) => {
        let file = data.file
        let formData = new FormData()
        formData.append('file', file)
        uploadFile(file.size <= 1024 * 1000 ? formData : file).then((response) => {
          console.log(response)
          let resUrl = ''
          if (file.size <= 1024 * 1000) {
            resUrl = response.data.virtualPath
          } else {
            resUrl = response.url
          }
          setValues({
            articlePic: resUrl
          })
          articlePic.value = response.data.resUrl
        })
        // uploadFile(formData).then((response) => {
        //   setValues({
        //     articlePic: response.data.virtualPath
        //   })
        //   articlePic.value = response.data.virtualPath
        // })
      },
      showFileList: false,
      class: 'NewsUploader',
      headers: {
        token: getStorage('token')
      },
      onSuccess: (response) => {
        setValues({
          articlePic: response.data.virtualPath
        })
        articlePic.value = response.data.virtualPath
      },
      slots: {
        default: () => (
          <>
            {articlePic.value ? <img src={articlePic.value} class="avatar" /> : null}
            {!articlePic.value ? (
              <Icon class="avatar-uploader-icon" icon="ep:plus" size={28}></Icon>
            ) : null}
          </>
        )
      }
    }
  },
  {
    field: 'remark',
    label: '备注',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea',
      placeholder: '请输入'
    }
  },
  {
    field: 'articleContent',
    label: '文章内容',
    component: 'Editor',
    colProps: {
      span: 24
    },
    componentProps: {
      defaultHtml: '',
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            fieldName: 'file',
            headers: {
              token: getStorage('token')
            },
            async customUpload(file: File, insertFn: InsertFnType) {
              // 定义表单数据
              let formData = new FormData()
              formData.append('file', file)
              // 上传文件
              uploadFile(formData).then((res) => {
                // 调用 insertFn 方法插入图片
                insertFn(res.data.virtualPath, res.data.fileName, '')
              })
            },
            customInsert(res: any, insertFn: InsertFnType) {
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data.virtualPath, res.fileName, '')
            }
          },
          uploadVideo: {
            fieldName: 'file',
            headers: {
              token: getStorage('token')
            },
            async customUpload(file: File, insertFn: InsertFnType) {
              let formData = new FormData()
              formData.append('file', file)
              uploadFile(formData).then((res) => {
                // 将视频上传成功后的路径和文件名插入到指定位置
                insertFn(res.data.virtualPath, res.data.fileName, '')
              })
            },
            customInsert(res: any, insertFn: InsertFnType) {
              // 从 res 中找到 url alt href ，然后插入视频
              insertFn(res.data.virtualPath, res.fileName, '')
            }
          }
        }
      },
      // @ts-ignore
      onChange: (edit: IDomEditor) => {
        setValues({
          articleContent: edit.getHtml()
        })
      }
    }
  }
])

const rules = reactive({})

// 定义一个submit函数，用于提交表单
const submit = async () => {
  // 获取表单元素
  const elForm = await getElFormExpose()
  // 调用表单元素的validate方法，获取表单验证结果
  const valid = await elForm?.validate().catch((err) => {
    // 如果表单验证失败，输出错误信息
    console.log(err)
  })
  // 如果表单验证成功，获取表单数据
  if (valid) {
    const formData = await getFormData()
    // 返回表单数据
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    // 如果当前行为空，则返回
    if (!currentRow) return
    // 设置值
    setValues(currentRow)
    // 设置模式
    setSchema([
      {
        field: 'articleContent',
        path: 'componentProps.defaultHtml',
        value: currentRow.articleContent
      }
    ])
    // 设置图片
    articlePic.value = currentRow.articlePic
  },
  {
    deep: true,
    immediate: true
  }
)
defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="schema" />
</template>

<style scoped>
.NewsUploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="less">
/**添加图片上传组件样式 */
.NewsUploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  img {
    width: 178px;
    height: 178px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
