<template>
  <div class="organization-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>组织管理</span>
          <el-button type="primary" @click="handleAddRoot">
            <el-icon><Plus /></el-icon>
            添加师团
          </el-button>
        </div>
      </template>
      
      <el-table 
        :data="organizations" 
        style="width: 100%" 
        row-key="id" 
        :tree-props="{ children: 'children' }"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column prop="name" label="组织名称" min-width="200">
          <template #default="{ row }">
            <span :style="{ paddingLeft: (row.level - 1) * 20 + 'px' }">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="层级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)" size="small">{{ getLevelName(row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="380" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                v-if="row.level !== OrganizationalLevel.Company" 
                type="primary" 
                text 
                size="small" 
                @click="handleAddChild(row)"
              >
                添加{{ getChildLevelName(row.level) }}
              </el-button>
              <el-button type="warning" text size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="info" text size="small" @click="handleViewAccounts(row)">查看账号</el-button>
              <el-button type="success" text size="small" @click="handleCreateAccount(row)">创建账户</el-button>
              <el-button type="danger" text size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Create/Edit Dialog -->
    <el-dialog v-model="showCreateDialog" :title="dialogTitle" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级组织" v-if="parentOrg">
          <el-input :value="parentOrg.name" disabled />
        </el-form-item>
        <el-form-item label="组织层级">
          <el-tag :type="getLevelTagType(form.level)">{{ getLevelName(form.level) }}</el-tag>
        </el-form-item>
        <el-form-item label="组织名称" prop="name">
          <el-input v-model="form.name" :placeholder="'请输入' + getLevelName(form.level) + '名称'" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- Create Account Dialog -->
    <el-dialog v-model="showAccountDialog" title="创建账户" width="500px">
      <el-form ref="accountFormRef" :model="accountForm" :rules="accountRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="accountForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="accountForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAccountDialog = false">取消</el-button>
        <el-button type="primary" :loading="savingAccount" @click="handleSaveAccount">创建</el-button>
      </template>
    </el-dialog>
    
    <!-- View Accounts Dialog -->
    <el-dialog v-model="showAccountsDialog" title="组织账号列表" width="900px">
      <div v-if="selectedOrg" style="margin-bottom: 16px;">
        <el-tag type="info">{{ selectedOrg.name }}</el-tag>
      </div>
      <el-table :data="accounts" v-loading="loadingAccounts" :header-cell-style="{ textAlign: 'center' }">
        <el-table-column prop="username" label="用户名" min-width="120" align="center" />
        <el-table-column prop="plainPassword" label="密码" min-width="120" align="center">
          <template #default="{ row }">
            <span v-if="row.plainPassword">{{ row.plainPassword }}</span>
            <el-tag v-else type="info" size="small">未记录</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'" size="small">
              {{ row.isActive ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录" min-width="160" align="center">
          <template #default="{ row }">
            {{ row.lastLoginAt ? formatDate(row.lastLoginAt) : '从未登录' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="danger" text size="small" @click="handleDeleteAccount(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="!loadingAccounts && accounts.length === 0" description="该组织暂无账号" />
      <template #footer>
        <el-button @click="showAccountsDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { organizationsApi } from '@/api'
import type { OrganizationalUnit } from '@/types'
import { OrganizationalLevel } from '@/types'

const organizations = ref<OrganizationalUnit[]>([])
const showCreateDialog = ref(false)
const showAccountDialog = ref(false)
const showAccountsDialog = ref(false)
const editingOrg = ref<OrganizationalUnit | null>(null)
const parentOrg = ref<OrganizationalUnit | null>(null)
const selectedOrg = ref<OrganizationalUnit | null>(null)
const saving = ref(false)
const savingAccount = ref(false)
const loadingAccounts = ref(false)
const accounts = ref<any[]>([])
const formRef = ref<FormInstance>()
const accountFormRef = ref<FormInstance>()

const form = reactive({
  name: '',
  level: OrganizationalLevel.Division as OrganizationalLevel,
  parentId: null as number | null
})

const accountForm = reactive({
  username: '',
  password: ''
})

const dialogTitle = computed(() => {
  if (editingOrg.value) {
    return '编辑' + getLevelName(editingOrg.value.level)
  }
  return '添加' + getLevelName(form.level)
})

const rules: FormRules = {
  name: [{ required: true, message: '请输入组织名称', trigger: 'blur' }]
}

const accountRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

function getLevelName(level: OrganizationalLevel): string {
  switch (level) {
    case OrganizationalLevel.Division: return '师团'
    case OrganizationalLevel.Regiment: return '团'
    case OrganizationalLevel.Battalion: return '营'
    case OrganizationalLevel.Company: return '连'
    default: return ''
  }
}

function getChildLevelName(level: OrganizationalLevel): string {
  switch (level) {
    case OrganizationalLevel.Division: return '团'
    case OrganizationalLevel.Regiment: return '营'
    case OrganizationalLevel.Battalion: return '连'
    default: return ''
  }
}

function getLevelTagType(level: OrganizationalLevel): string {
  switch (level) {
    case OrganizationalLevel.Division: return 'danger'
    case OrganizationalLevel.Regiment: return 'warning'
    case OrganizationalLevel.Battalion: return 'success'
    case OrganizationalLevel.Company: return 'info'
    default: return 'info'
  }
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleString('zh-CN')
}

async function loadOrganizations() {
  try {
    organizations.value = await organizationsApi.getAll()
  } catch {
    ElMessage.error('加载组织列表失败')
  }
}

function handleAddRoot() {
  editingOrg.value = null
  parentOrg.value = null
  form.name = ''
  form.level = OrganizationalLevel.Division
  form.parentId = null
  showCreateDialog.value = true
}

function handleAddChild(parent: OrganizationalUnit) {
  editingOrg.value = null
  parentOrg.value = parent
  form.name = ''
  form.level = getChildLevel(parent.level)
  form.parentId = parent.id
  showCreateDialog.value = true
}

function getChildLevel(parentLevel: OrganizationalLevel): OrganizationalLevel {
  switch (parentLevel) {
    case OrganizationalLevel.Division: return OrganizationalLevel.Regiment
    case OrganizationalLevel.Regiment: return OrganizationalLevel.Battalion
    case OrganizationalLevel.Battalion: return OrganizationalLevel.Company
    default: return OrganizationalLevel.Company
  }
}

function handleEdit(org: OrganizationalUnit) {
  editingOrg.value = org
  parentOrg.value = null
  form.name = org.name
  form.level = org.level
  form.parentId = org.parentId
  showCreateDialog.value = true
}

function handleCreateAccount(org: OrganizationalUnit) {
  selectedOrg.value = org
  accountForm.username = ''
  accountForm.password = ''
  showAccountDialog.value = true
}

async function handleViewAccounts(org: OrganizationalUnit) {
  selectedOrg.value = org
  showAccountsDialog.value = true
  loadingAccounts.value = true
  try {
    accounts.value = await organizationsApi.getAccounts(org.id)
  } catch {
    ElMessage.error('加载账号列表失败')
  } finally {
    loadingAccounts.value = false
  }
}

async function handleDeleteAccount(account: any) {
  if (!selectedOrg.value) return
  
  try {
    await ElMessageBox.confirm(`确定要删除账号 "${account.username}" 吗？`, '确认删除', {
      type: 'warning'
    })
    await organizationsApi.deleteAccount(selectedOrg.value.id, account.id)
    ElMessage.success('账号删除成功')
    // 重新加载账号列表
    await handleViewAccounts(selectedOrg.value)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除账号失败')
    }
  }
}

async function handleDelete(org: OrganizationalUnit) {
  try {
    await ElMessageBox.confirm('确定要删除该组织吗？', '确认删除', {
      type: 'warning'
    })
    await organizationsApi.delete(org.id)
    ElMessage.success('删除成功')
    await loadOrganizations()
  } catch {
    // User cancelled or error
  }
}

async function handleSave() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    try {
      if (editingOrg.value) {
        await organizationsApi.update(editingOrg.value.id, { name: form.name })
      } else {
        await organizationsApi.create({
          name: form.name,
          level: form.level,
          parentId: form.parentId
        })
      }
      ElMessage.success(editingOrg.value ? '更新成功' : '创建成功')
      showCreateDialog.value = false
      editingOrg.value = null
      parentOrg.value = null
      form.name = ''
      form.level = OrganizationalLevel.Division
      form.parentId = null
      await loadOrganizations()
    } catch {
      ElMessage.error('操作失败')
    } finally {
      saving.value = false
    }
  })
}

async function handleSaveAccount() {
  if (!accountFormRef.value || !selectedOrg.value) return
  
  await accountFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    savingAccount.value = true
    try {
      await organizationsApi.createAccount(selectedOrg.value!.id, {
        username: accountForm.username,
        password: accountForm.password
      })
      ElMessage.success('账户创建成功')
      showAccountDialog.value = false
    } catch {
      ElMessage.error('创建账户失败')
    } finally {
      savingAccount.value = false
    }
  })
}

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

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  flex-wrap: nowrap;
  gap: 4px;
  align-items: center;
}
</style>
