<template>
  <div class="organization-management">
    <!-- 操作栏 -->
    <el-card class="toolbar">
      <div class="toolbar-actions">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新建机构
        </el-button>
        <el-button @click="handleExpandAll">
          展开全部
        </el-button>
        <el-button @click="handleCollapseAll">
          折叠全部
        </el-button>
      </div>
    </el-card>

    <!-- 机构树 -->
    <el-card class="tree-card">
      <el-tree
        ref="treeRef"
        :data="organizationTree"
        :props="treeProps"
        :expand-on-click-node="false"
        node-key="id"
        default-expand-all
        :highlight-current="true"
      >
        <template #default="{ node, data }">
          <span class="tree-node">
            <span class="node-label">
              <el-icon class="node-icon">
                <component :is="getOrgIcon(data.orgType)" />
              </el-icon>
              {{ data.orgName }}
            </span>
            <span class="node-actions">
              <el-tag size="small" type="info">{{ getOrgTypeLabel(data.orgType) }}</el-tag>
              <el-button
                link
                type="primary"
                size="small"
                @click.stop="handleAddChild(data)"
              >
                添加子机构
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click.stop="handleEdit(data)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="warning"
                size="small"
                @click.stop="handleMove(data)"
                :disabled="data.treeLevel === 0"
              >
                移动
              </el-button>
              <el-popconfirm
                title="确定删除该机构吗？"
                @confirm.stop="handleDelete(data)"
              >
                <template #reference>
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click.stop
                    :disabled="data.children && data.children.length > 0"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </span>
          </span>
        </template>
      </el-tree>
    </el-card>

    <!-- 新建/编辑机构对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @closed="handleDialogClosed"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="机构编码" prop="orgCode">
          <el-input
            v-model="formData.orgCode"
            placeholder="请输入机构编码（如：ORG001）"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="机构名称" prop="orgName">
          <el-input
            v-model="formData.orgName"
            placeholder="请输入机构名称"
          />
        </el-form-item>

        <el-form-item label="机构类型" prop="orgType">
          <el-select
            v-model="formData.orgType"
            placeholder="请选择机构类型"
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option label="省级" value="province" />
            <el-option label="市级" value="city" />
            <el-option label="网点" value="outlet" />
          </el-select>
        </el-form-item>

        <el-form-item label="父级机构" prop="parentId" v-if="!isAddChild && !isEdit">
          <el-tree-select
            v-model="formData.parentId"
            :data="organizationTree"
            :props="treeProps"
            placeholder="请选择父级机构"
            clearable
            check-strictly
          />
        </el-form-item>

        <el-form-item label="父级机构" v-if="isAddChild || isEdit">
          <el-input :value="parentOrgName" disabled />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input
            v-model="formData.address"
            placeholder="请输入地址"
          />
        </el-form-item>

        <el-form-item label="联系人" prop="contactPerson">
          <el-input
            v-model="formData.contactPerson"
            placeholder="请输入联系人"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="contactPhone">
          <el-input
            v-model="formData.contactPhone"
            placeholder="请输入联系电话"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 移动机构对话框 -->
    <el-dialog
      v-model="moveDialogVisible"
      title="移动机构"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="当前机构">
          <el-input :value="currentOrg?.orgName" disabled />
        </el-form-item>

        <el-form-item label="目标父级">
          <el-tree-select
            v-model="targetParentId"
            :data="organizationTree"
            :props="treeProps"
            placeholder="请选择目标父级机构"
            clearable
            check-strictly
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="moveDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="moveLoading" @click="handleMoveSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus, OfficeBuilding, MapLocation, Location } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  getOrganizationTree,
  createOrganization,
  updateOrganization,
  deleteOrganization,
  moveOrganization
} from '@/api/organizations'
import type { Organization } from '@/types'

// 响应式数据
const loading = ref(false)
const organizationTree = ref<Organization[]>([])
const treeRef = ref()

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const isAddChild = ref(false)
const dialogTitle = computed(() => {
  if (isAddChild.value) return '添加子机构'
  return isEdit.value ? '编辑机构' : '新建机构'
})
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const parentOrg = ref<Organization>()

const formData = reactive({
  orgCode: '',
  orgName: '',
  orgType: 'outlet' as Organization['orgType'],
  parentId: null as number | null,
  address: '',
  contactPerson: '',
  contactPhone: ''
})

const formRules: FormRules = {
  orgCode: [
    { required: true, message: '请输入机构编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_]+$/, message: '机构编码只能包含大写字母、数字和下划线', trigger: 'blur' }
  ],
  orgName: [
    { required: true, message: '请输入机构名称', trigger: 'blur' }
  ],
  orgType: [
    { required: true, message: '请选择机构类型', trigger: 'change' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const parentOrgName = computed(() => parentOrg.value?.orgName || '-')

// 移动机构相关
const moveDialogVisible = ref(false)
const moveLoading = ref(false)
const currentOrg = ref<Organization>()
const targetParentId = ref<number | null>()

// Tree组件配置
const treeProps = {
  children: 'children',
  label: 'orgName'
}

// 获取机构树
const fetchOrganizationTree = async () => {
  loading.value = true
  try {
    const { data } = await getOrganizationTree()
    organizationTree.value = data
  } finally {
    loading.value = false
  }
}

// 获取机构类型标签
const getOrgTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    province: '省级',
    city: '市级',
    outlet: '网点'
  }
  return typeMap[type] || type
}

// 获取机构图标
const getOrgIcon = (type: string) => {
  const iconMap: Record<string, any> = {
    province: OfficeBuilding,
    city: MapLocation,
    outlet: Location
  }
  return iconMap[type] || Location
}

// 展开全部
const handleExpandAll = () => {
  const nodes = treeRef.value?.store.nodesMap
  for (const key in nodes) {
    nodes[key].expanded = true
  }
}

// 折叠全部
const handleCollapseAll = () => {
  const nodes = treeRef.value?.store.nodesMap
  for (const key in nodes) {
    nodes[key].expanded = false
  }
}

// 新建机构
const handleCreate = () => {
  isEdit.value = false
  isAddChild.value = false
  parentOrg.value = undefined
  formData.parentId = null
  dialogVisible.value = true
}

// 添加子机构
const handleAddChild = (data: Organization) => {
  isEdit.value = false
  isAddChild.value = true
  parentOrg.value = data
  formData.parentId = data.id
  // 根据父机构类型确定子机构类型
  if (data.orgType === 'province') {
    formData.orgType = 'city'
  } else if (data.orgType === 'city') {
    formData.orgType = 'outlet'
  }
  dialogVisible.value = true
}

// 编辑机构
const handleEdit = (data: Organization) => {
  isEdit.value = true
  isAddChild.value = false
  parentOrg.value = organizationTree.value.find(org => org.id === data.parentId)
  Object.assign(formData, {
    orgCode: data.orgCode,
    orgName: data.orgName,
    orgType: data.orgType,
    parentId: data.parentId || null,
    address: data.address || '',
    contactPerson: data.contactPerson || '',
    contactPhone: data.contactPhone || ''
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate()

  submitLoading.value = true
  try {
    if (isEdit.value) {
      const updateData = {
        orgName: formData.orgName,
        address: formData.address,
        contactPerson: formData.contactPerson,
        contactPhone: formData.contactPhone
      }
      await updateOrganization(parentOrg.value?.id || 0, updateData)
      ElMessage.success('更新成功')
    } else {
      await createOrganization(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchOrganizationTree()
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    orgCode: '',
    orgName: '',
    orgType: 'outlet',
    parentId: null,
    address: '',
    contactPerson: '',
    contactPhone: ''
  })
  parentOrg.value = undefined
}

// 删除机构
const handleDelete = async (data: Organization) => {
  try {
    await deleteOrganization(data.id)
    ElMessage.success('删除成功')
    fetchOrganizationTree()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 移动机构
const handleMove = (data: Organization) => {
  currentOrg.value = data
  targetParentId.value = data.parentId || null
  moveDialogVisible.value = true
}

// 提交移动
const handleMoveSubmit = async () => {
  if (!currentOrg.value) return

  // 不能移动到自己的子节点下
  if (targetParentId.value === currentOrg.value.id) {
    ElMessage.warning('不能将机构移动到自身下')
    return
  }

  moveLoading.value = true
  try {
    await moveOrganization(currentOrg.value.id, targetParentId.value)
    ElMessage.success('移动成功')
    moveDialogVisible.value = false
    fetchOrganizationTree()
  } finally {
    moveLoading.value = false
  }
}

onMounted(() => {
  fetchOrganizationTree()
})
</script>

<style scoped lang="scss">
.organization-management {
  .toolbar {
    margin-bottom: 16px;
  }

  .tree-card {
    .tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;

      .node-label {
        display: flex;
        align-items: center;
        gap: 6px;

        .node-icon {
          color: #475569;
        }
      }

      .node-actions {
        display: flex;
        align-items: center;
        gap: 8px;
        padding-left: 20px;
      }
    }

    :deep(.el-tree-node__content) {
      height: 40px;

      &:hover {
        background-color: #f8fafc;
      }
    }
  }
}
</style>
