<script setup lang="ts" name="authManage_menuManage">
import type { FormInstance, FormRules } from 'element-plus'

import { addRole, editorRole } from '#/api'
import { delConfirm } from '#/utils/tool'

const props = defineProps({
  showDia: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '新增',
  },
  diaData: {
    type: Object,
    default: () => {},
  },
})

const emit = defineEmits(['update:showDia', 'onRefresh'])

const ruleFormRef = ref<FormInstance>()
const form = ref({
  code: '',
  name: '',
  remark: '',
  status: 0,
})
const rules = reactive<FormRules>({
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
})

const show = ref(false)

watch(
  () => props.showDia,
  (newVal) => {
    form.value = {
      code: '',
      name: '',
      remark: '',
      status: 0,
    }
    show.value = newVal
    if (props.diaData.code) {
      const { code, name, remark, status } = props.diaData
      form.value = { code, name, remark, status }
    }
  },
)

async function handleSave(formEl: FormInstance | undefined) {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      await (props.title === '新增'
        ? addRole(form.value)
        : editorRole({ id: props.diaData.id, ...form.value }))
      emit('onRefresh')
      emit('update:showDia', false)
    } else {
      ElMessage.error('请输入编码或名称')
    }
  })
}
async function onClose() {
  let flag = false
  for (const key in form.value) {
    if (
      (form.value as anyObj)[key] !== props.diaData[key] &&
      !(props.title === '新增' && !(form.value as anyObj)[key])
    ) {
      flag = true
      break
    }
  }
  if (flag) await delConfirm(true)
  emit('update:showDia', false)
}
</script>

<template>
  <el-dialog
    v-model="show"
    :title="title"
    width="600px"
    top="10vh"
    class="box"
    destroy-on-close
    :before-close="onClose"
  >
    <el-form ref="ruleFormRef" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="角色编码" prop="code">
        <el-input v-model="form.code" :disabled="title === '编辑'" />
      </el-form-item>
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <Switch v-model="form.status" :inactive-value="1" :active-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">关闭</el-button>
        <el-button type="primary" @click="handleSave(ruleFormRef)">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
