<template>
  <ElDialog v-model="showDialog"
    :close-on-click-modal="false"
    @close="dialogCloseHandler"
    destroy-on-close
    width="25vw">
    <ElForm :model="roleFormData"
      class="sys_role-form"
    >
      <ElFormItem label="角色代码">
        <ElInput
          v-model="roleFormData.roleCode"

          placeholder="角色代码"/>
      </ElFormItem>
      <ElFormItem label="角色名称">
        <ElInput
          v-model="roleFormData.roleName"

          placeholder="角色名称"/>
      </ElFormItem>
      <ElFormItem label="备注">
        <ElInput
          v-model="roleFormData.memo"

          placeholder="备注"/>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="showDialog = false">{{ status === 'view' ? '关闭' : '取消' }}</ElButton>
      <ElButton v-if="status !== 'view'" :loading="submiting" type="primary" @click="submitHandler">提交</ElButton>
    </template>
  </ElDialog>
</template>
<script lang="ts" setup>
import RoleApi from '@/pages/sys/role/role-api.ts'
import Strings from '@/common/utils/strings.ts'
import { ElMessage } from 'element-plus'

const emits = defineEmits([ 'editSucc' ])
const showDialog = ref(false)
const submiting = ref(false)
const status = ref<'add' | 'view' | 'modify'>('add')
const roleFormData = ref<RoleTypes.SearchRoleResult>({})

function dialogCloseHandler() {
  roleFormData.value = {}
}

function submitHandler() {
  if (status.value === 'view') return
  submiting.value = true
  if (roleFormData.value.id != null) {
    RoleApi.modify(roleFormData.value)
      .then(() => {
        ElMessage.success('修改成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  } else {
    RoleApi.add(roleFormData.value)
      .then(() => {
        ElMessage.success('添加成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  }
}

defineExpose({
  open(data: RoleTypes.SearchRoleResult = {}) {
    showDialog.value = true
    if (!Strings.isBlank(data.id)) {
      status.value = 'modify'
      RoleApi.detail(data.id!)
        .then(res => {
          roleFormData.value = res.data
        })
    } else {
      status.value = 'add'
      roleFormData.value = data
    }
  },
})
</script>
<style lang="stylus" scoped>
.sys_role-form {
  padding 20px
}
</style>
