<template>
  <Dialog
    style="max-width: 100vw; min-width: 40vw;max-height: 70vh;min-height: 45vh"
    v-model="dialogVisible"
    :title="title"
    class="OutwardRegistrationBak"
    noPaddingEL="OutwardRegistrationBak"
    @close="handleClosed"
  >
    <el-form ref="formRef" :model="dataForm" :rules="dataRule" :label-width="labelWidth">
      <div class="info-wrap">
        <el-row align="bottom" justify="start">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="餐厅名称" prop="restaurantName">
              <el-input
                v-model="dataForm.restaurantName"
                placeholder="餐厅名称"
                show-word-limit
                :maxlength="25"
                @input="handleFormActivity"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row align="bottom" justify="start" style="margin-top: 8px">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="餐厅描述" prop="restaurantDescription">
              <el-input
                v-model="dataForm.restaurantDescription"
                type="textarea"
                placeholder="餐厅描述"
                show-word-limit
                :maxlength="200"
                :rows="4"
                @input="handleFormActivity"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row align="bottom" justify="start" style="margin-top: 8px">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="餐厅图片" prop="elderName">
              <SelectUpload v-model="dataForm.pictures" fun-name="餐厅图片" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button v-loading="formLoading" type="primary" @click="submitForm">确定</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { FormRules } from 'element-plus'
import { useMediaQuery } from '@vueuse/core'

import { useUpload } from '@/components/UploadFile/src/useUpload'
import { restaurantManagementAdd, restaurantManagementEdit } from '@/api/system/foods'

// const { uploadUrl, httpRequest } = useUpload()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗
const title = ref('') // 表单 Ref
const formRef = ref() // 表单 Ref
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

let dataForm = ref({
  // 表单字段
  id: undefined,
  restaurantName: '',
  restaurantDescription: '',
  pictures: [] as any[]
})
// 表单规则
const dataRule = reactive<FormRules>({
  restaurantName: [{ required: true, message: '餐厅名称不能为空', trigger: 'blur' }],
  restaurantDescription: [{ required: true, message: '餐厅描述不能为空', trigger: 'blur' }]
})

// 计算窗口大小
const currentWidth = useMediaQuery('(max-width: 800px)')
// 计算文字大小
const labelWidth = computed(() => {
  return currentWidth.value ? '110px' : '120px'
})

/** 提交表单 */
const emit = defineEmits(['success', 'visible-change', 'form-activity']) // 定义 success 事件，用于操作成功后的回调

/** 打开弹窗 */
const open = async (id?: any) => {
  resetForm()
  dialogVisible.value = true
  emit('visible-change', true)
  if (id !== undefined) {
    try {
      dataForm.value = JSON.parse(JSON.stringify(id))
      if (dataForm.value.pictures && dataForm.value.pictures.length > 0) {
        for (const idElement of dataForm.value.pictures) {
          idElement.fileUrl = idElement.url ? idElement.url : idElement.fileUrl
        }
      }
    } catch (error) {}

    title.value = '编辑餐厅'
  } else {
    title.value = '新增餐厅'
  }
}

const handleFormActivity = () => {
  emit('form-activity')
}

const applyAiSuggest = (suggest: { restaurantName?: string; restaurantDescription?: string }) => {
  if (!dataForm.value.restaurantName && suggest?.restaurantName) {
    dataForm.value.restaurantName = suggest.restaurantName as string
  }
  if (!dataForm.value.restaurantDescription && suggest?.restaurantDescription) {
    dataForm.value.restaurantDescription = suggest.restaurantDescription as string
  }
  emit('form-activity')
}

const getFormData = () => {
  return {
    restaurantName: dataForm.value.restaurantName,
    restaurantDescription: dataForm.value.restaurantDescription
  }
}

defineExpose({ open, applyAiSuggest, getFormData }) // 提供 open 方法，用于打开弹窗

const submitForm = async () => {
  if (formLoading.value) {
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    // 校验表单
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return

    let dataFormUP = {
      ...dataForm.value,
      pictures: JSON.stringify(dataForm.value.pictures) //改成字符串
    }

    if (dataForm.value.id) {
      const res = await restaurantManagementEdit(dataFormUP)
      if (res) {
        message.success(t('common.updateSuccess'))
        dialogVisible.value = false
        emit('visible-change', false)
        emit('success')
      }
    } else {
      const res = await restaurantManagementAdd(dataFormUP)
      if (res) {
        message.success(t('common.updateSuccess'))
        dialogVisible.value = false
        emit('visible-change', false)
        emit('success')
      }
    }
  } finally {
    setTimeout(() => {
      formLoading.value = false
    }, 500)
  }
}

/** 重置表单 */
const resetForm = () => {
  dataForm.value = {
    id: undefined,
    restaurantName: '',
    restaurantDescription: '',
    pictures: []
  }
  formRef.value?.resetFields()
}

// 关闭表单
const handleClosed = () => {
  dialogVisible.value = false
  emit('visible-change', false)
  resetForm()
}
</script>

<style lang="scss" scoped>
.OutwardRegistrationBak {
  .el-form {
    padding: 15px !important;
  }
  .info-title {
    min-width: 75px;
    max-width: 180px;
    padding: 15px;
    font-weight: bolder;
    background-color: #f3f6fb;
    border-top-right-radius: 50px;
    border-bottom-right-radius: 50px;
  }
  .info-wrap {
    margin: 15px 2vw 15px 15px;
  }
  @media (max-width: 1200) {
    :deep(.el-form-item--default .el-form-item__label) {
      line-height: 0 !important;
    }
  }
}
</style>
