<script setup>
import { ref } from 'vue'
import {
  informationCreateService,
  informationUpdateService,
  typeListService
} from '@/api/information'
const dialogVisible = ref(false)
const formModel = ref({
  venueName: '',
  type: '',
  location: '',
  capacity: 10,
  typeId: 0
})
const isAdd = ref(false)
const formRef = ref()
const typeList = ref([])
const rules = {
  typeId: [{ required: true, message: '请选择对应场馆', trigger: 'blur' }],
  venueName: [
    { required: true, message: '请输入场地名称', trigger: 'blur' },
    {
      pattern: /^\S{1,15}$/,
      message: '必须是 1~15 位的非空字符',
      trigger: 'blur'
    }
  ],
  location: [
    { required: true, message: '请输入场地位置', trigger: 'blur' },
    {
      pattern: /^\S{1,15}$/,
      message: '必须是 1~10 位的非空字符',
      trigger: 'blur'
    }
  ],
  capacity: [
    { required: true, message: '请输入场地容量', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        // 判断当前的 value 是否大于 0
        if (value <= 0) {
          callback(new Error('场地容量需要大于0'))
        } else {
          // 校验成功，也需要 callback()
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载分类数据
const typeOptions = ref([])
const getTypeOptions = async () => {
  typeOptions.value = []
  const {
    data: { data }
  } = await typeListService()
  data.forEach((item) => {
    typeOptions.value.push({ label: item, value: item })
  })
}

// 添加选择的类型
const isAdding = ref(false)
const optionName = ref('')
const onAddOption = () => {
  isAdding.value = true
}

const onConfirm = () => {
  // let isAdd = true
  if (optionName.value) {
    typeOptions.value.forEach((item) => {
      if (item.label === optionName.value) {
        ElMessage.error('场地类型已经存在')
        isAdding.value = false
      }
    })
    if (isAdding.value) {
      typeOptions.value.push({
        label: optionName.value,
        value: optionName.value
      })
    }
    clear()
  }
}

const clear = () => {
  optionName.value = ''
  isAdding.value = false
}
// 组件对外暴露一个方法 open ，基于 open 传来的参数，区分添加还是编辑
const open = (row, types) => {
  if (!row.id) {
    isAdd.value = true
  } else {
    formModel.value = { ...row }
  }
  getTypeOptions()
  typeList.value = types
  typeList.value.push({ label: '请选择场馆', value: 0 })
  dialogVisible.value = true
}
// 向外暴露
defineExpose({
  open
})
const emit = defineEmits(['success'])
const onSubmit = async () => {
  if (formModel.value.typeId === 0) {
    ElMessage.info('请选择对应场馆')
    return
  }
  if (formModel.value.type === '') {
    ElMessage.info('请选择分类')
    return
  }
  console.log(formModel.value)
  await formRef.value.validate()
  ElMessageBox.confirm('确认提交？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      isAdd.value
        ? await informationCreateService(formModel.value)
        : await informationUpdateService(formModel.value)
      ElMessage.success('编辑成功')
      dialogVisible.value = false
      isAdd.value = false
      emit('success')
      formModel.value = {}
    })
    .catch(() => {})
}

const onClose = () => {
  dialogVisible.value = false
  formRef.value.clearValidate()
  // 重置数据
  formModel.value = {
    venueName: '',
    type: '',
    location: '',
    capacity: 10,
    typeId: 0
  }
}
</script>
<template>
  <el-drawer
    v-model="dialogVisible"
    :title="formModel.id ? '编辑场地' : '添加场地'"
    width="30%"
    @close="onClose"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="对应场馆" prop="venue">
        <el-select
          v-model="formModel.typeId"
          placeholder="请选择场馆"
          style="width: 160px"
        >
          <el-option
            v-for="(t, i) of typeList"
            :key="i"
            :label="t.label"
            :value="t.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="场地名称" prop="venueName">
        <el-input
          placeholder="请输入场地名称"
          v-model="formModel.venueName"
          style="width: 160px"
        ></el-input>
      </el-form-item>
      <el-form-item label="场地分类" prop="type">
        <el-select
          v-model="formModel.type"
          placeholder="请选择场地类型"
          style="width: 160px"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
          <template #footer>
            <el-button
              v-if="!isAdding"
              text
              bg
              size="small"
              @click="onAddOption"
            >
              点击添加其他类型
            </el-button>
            <template v-else>
              <el-input
                v-model="optionName"
                class="option-input"
                placeholder="请输入场地类型"
                size="small"
              />
              <el-button type="primary" size="small" @click="onConfirm">
                确认
              </el-button>
              <el-button size="small" @click="clear">取消</el-button>
            </template>
          </template>
        </el-select>
        <!-- <el-input placeholder="请输入分类" v-model="formModel.type"></el-input> -->
      </el-form-item>
      <el-form-item label="位置信息" prop="location">
        <el-input
          placeholder="请输入位置"
          v-model="formModel.location"
          style="width: 160px"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="场地容量" prop="capacity">
        <el-input-number v-model="formModel.capacity" :min="1" :max="100">
          <template #suffix>
            <span>RMB</span>
          </template>
        </el-input-number>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-drawer>
</template>
