<script lang="ts" setup>
import { ElMessageBox, ElMessage } from 'element-plus'
import { createOrg, deleteOrg, updateOrg, getOrgList } from '@/api/org'
import { orgFormConfig } from '@/utils/constants'

const emits = defineEmits(['click'])

const orgList = ref<any>([])
const curOrg = ref<any>({})
const loaded = ref(false)
const query = ref({
  name: ''
})

const fetchOrgList = () => {
  getOrgList(query.value)
    .then(res => {
      orgList.value = res.data.list
      orgList.value.length && handleOrgClick(orgList.value[0])
    })
    .finally(() => {
      loaded.value = true
    })
}
watch(
  query,
  () => {
    fetchOrgList()
  },
  {
    immediate: true
  }
)

// 删除
const handleDel = async () => {
  if (!curOrg.value.id) {
    return ElMessage({
      type: 'error',
      message: '请先选择需要删除的项'
    })
  }
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteOrg({ id: curOrg.value.id })
    curOrg.value = {}
    ElMessage({
      type: 'success',
      message: '删除成功'
    })

    fetchOrgList()
  })
}

const handleOrgClick = (item: any) => {
  curOrg.value = item
  emits('click', item)
}

// ============== 表单部分开始 ===============
const formData = ref<any>({})
const dialogVisible = ref(false)
// ============== 表单部分结束 ===============
</script>

<template>
  <div class="flex flex-col w-[300px] bg-white h-full">
    <div class="p-[10px] flex-shrink-0">
      <el-input placeholder="请输入组织名称" v-model="query.name"></el-input>
    </div>
    <div class="org-list h-full flex-grow overflow-auto">
      <div
        class="p-[15px] cursor-pointer org-item"
        :class="{ active: curOrg.id === item.id }"
        v-for="item in orgList"
        :key="item.id"
      >
        <div class="" @click="handleOrgClick(item)" :title="item.name">{{ item.name }}</div>
      </div>
      <el-empty v-if="!orgList.length && loaded" :image-size="100"></el-empty>
    </div>
    <el-space class="p-[10px] flex-shrink-0">
      <el-button icon="plus" type="primary" size="small" @click="dialogVisible = true"></el-button>
      <el-button icon="delete" type="danger" size="small" @click="handleDel"></el-button>
      <el-button icon="refresh" size="small" @click="fetchOrgList"></el-button>
    </el-space>
  </div>

  <dialog-form
    v-model="dialogVisible"
    :formConfig="orgFormConfig"
    :formData="formData"
    :create="createOrg"
    :update="updateOrg"
    v-if="dialogVisible"
  />
</template>

<style lang="scss" scoped>
.org-list {
  border-top: 1px solid var(--el-border-color);
  border-bottom: 1px solid var(--el-border-color);
}
.active,
.org-item:hover {
  background-color: var(--el-color-primary-light-9);
}
</style>
