<template>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="400px"
      @close="closeDialog(0)"
       @open="open"
    >
      <el-form
        ref="formInfo"
        :model="form"
        class="demo-form-inline"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="分组名称：" prop="groupingName">
          <el-input v-model="form.groupingName"  ></el-input>
        </el-form-item>
      
        <div style="text-align: right">
          <el-button type="primary" @click="submitForm('formInfo')"
            >保存</el-button
          >
        </div>
      </el-form>
    </el-dialog>
</template>
<script>
import { defineComponent, ref, watchEffect } from 'vue'
import * as api from '@/api/siteManage/index'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'AddGroupCom',
  emits: ['closeDialog'],
  props: {
    flag: Boolean,
    dialogTitle: String,
    itemInfo: Object,
  },
  setup(props, context) {
    context

    const dialogVisible = ref(false)
    const formInfo = ref(null)

    const form = ref([])

    // open(): Dialog弹窗打开之前做的事
    const open = () => {
      form.value = props.itemInfo.value

    }
    

    // 关闭弹框
    const closeDialog = () => {
      context.emit('closeDialog', false)
      dialogVisible.value = false
    }

    watchEffect((fn, options) => {
      fn, options
      dialogVisible.value = props.flag
    })

    const roleValid = (rule, value, callback) => {
      rule
      if (value.length === 0) {
        callback(new Error('角色不能为空'))
      } else {
        callback()
      }
    }

    // 保存-修改操作
    const submitForm = () => {
      console.log(formInfo)
      formInfo.value.validate((valid) => {
        if (valid) {
          api.siteGroupingAdd(form.value).then((requset) => {
              if (requset.status === 'SUCCESS') {
                ElMessage.success({
                  message: '新增成功',
                  type: 'success',
                })
                closeDialog()
              } else {
                ElMessage.error(requset.msg)
              }
            })

        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

    return {
      closeDialog,
      dialogVisible,
      roleValid,
      formInfo,
      form,
      open,
      submitForm,
      rules: {
        groupingName: [
          // required  是否为必填项， trigger:表单验证的触发时机，失去焦点进行验证
          { required: true, message: "请输入分组名称", trigger: "blur" },
          {
            min: 3,
            max: 6,
            message: "用户名长度在 3 到 6 个字符",
            trigger: "blur",
          },
        ],
      },
    }
  },

})
</script>
 
<style scoped lang="scss">


</style>