<template>
  <el-dialog
    :model-value="visible"
    title="部门代字"
    width="800px"
    :append-to-body="true"
    :destroy-on-close="true"
    @open="onOpen"
    @close="onClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" label-position="left">
      <el-form-item label="应用" prop="appCode">
        <el-input v-model="form.appCode" :readonly="mode !== 'insert'"></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-input v-model="form.deptPath" readonly>
          <template #append>
            <el-button icon="Search" @click="onOrgDialogOpen" :disabled="mode === 'show'" />
          </template>
        </el-input>
        <org-selector
          :visible="orgVisible"
          :multiple="false"
          @on-close="onOrgDialogClose"
          @on-save="onOrgSave"
        ></org-selector>
      </el-form-item>
      <el-form-item label="代字" prop="snTitle">
        <el-input v-model="form.snTitle" :readonly="mode === 'show'"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="onClose">关闭</el-button>
        <el-button v-if="mode !== 'show' && mode !== ''" type="primary" @click="onSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { FormRules, FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import type { CacpOrganization } from '@cacp/ui'
import { type DeptSn, initDeptSn } from './types'
import OrgSelector from '@/components/auth/OrgSelector.vue'

const emits = defineEmits<{
  (e: 'on-close'): void
  (e: 'on-save', info: DeptSn): void
}>()
const props = defineProps<{
  mode: string
  visible: boolean
  info: DeptSn
}>()

const rules: FormRules = {
  appCode: [{ required: true, message: '必须输入应用代码' }],
  deptId: [{ required: true, message: '必须输入部门' }],
  snTitle: [{ required: true, message: '必须输入代字' }]
}

const formRef = ref<FormInstance>()
const form = ref<DeptSn>(initDeptSn)
const orgVisible = ref<boolean>(false)

async function onOpen() {
  form.value = cloneDeep(props.info)
}

function onClose() {
  formRef.value.resetFields()
  emits('on-close')
}
function onSave() {
  formRef.value!.validate((valid) => {
    if (valid) {
      emits('on-save', form.value)
    }
  })
}

function onOrgDialogOpen() {
  orgVisible.value = true
}
function onOrgDialogClose() {
  orgVisible.value = false
}

function onOrgSave(selectedList: Array<CacpOrganization>) {
  orgVisible.value = false
  if (selectedList.length  === 1) {
    form.value.deptId = selectedList[0].oguId
    form.value.deptPath = selectedList[0].fullPathName
  }
}
</script>
