<template>
  <div>
    <el-tabs v-model="activeTab">
      <!-- Tab1: 系统配置 -->
      <el-tab-pane label="系统配置" name="config">
        <el-form :inline="true" class="mb-16">
          <el-form-item><el-input v-model="configKeyword" placeholder="配置项/说明" clearable @input="filterConfig" /></el-form-item>
        </el-form>
        <el-table :data="filteredConfigs" border stripe v-loading="configLoading">
          <el-table-column prop="configKey" label="配置项" show-overflow-tooltip />
          <el-table-column label="配置值" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ getDisplayValue(row) }}</span>
              <el-button v-if="isSensitive(row.configKey)" link type="primary" @click="toggleVisibility(row.configKey)" style="margin-left:6px">
                <i class="el-icon-view"></i>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="valueType" label="类型" align="center" />
          <el-table-column prop="description" label="说明" show-overflow-tooltip />
          <el-table-column label="操作" width="160" align="center">
            <template #default="{ row }">
              <div style="white-space:nowrap">
                <el-button link type="primary" @click="editConfig(row)">编辑</el-button>
                <el-button v-if="isSensitive(row.configKey)" link type="primary" @click="resetToken(row)">重置</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 编辑配置弹窗 -->
        <el-dialog v-model="configDialogVisible" title="编辑配置项" width="500px" destroy-on-close>
          <el-form :model="configForm" label-width="100px">
            <el-form-item label="配置项"><el-input v-model="configForm.configKey" disabled /></el-form-item>
            <el-form-item label="配置值" required>
              <template v-if="configForm.valueType === 'number'">
                <el-input-number v-model="configForm.numberValue" :min="0" style="width:100%" />
              </template>
              <template v-else>
                <div style="display:flex;gap:8px;align-items: center;">
                  <el-input v-model="configForm.displayValue" style="flex:1" />
                  <span v-if="isSensitive(configForm.configKey)" @click="toggleVisibility(configForm.configKey)" style="cursor:pointer;color:#409EFF;display:flex;align-items:center;gap:4px">
                    <i class="el-icon-view"></i>
                    <span>{{ configForm.displayValue === '••••••••' ? '显示' : '隐藏' }}</span>
                  </span>
                </div>
              </template>
            </el-form-item>
            <el-form-item label="说明"><el-input v-model="configForm.description" disabled /></el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="configDialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="configSubmitting" @click="saveConfig">保存</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>

      <!-- Tab2: 车间管理 -->
      <el-tab-pane label="车间管理" name="workshop">
        <div class="mb-16"><el-button type="primary" @click="addWorkshop">+ 新增车间</el-button></div>
        <el-table :data="workshopList" border stripe v-loading="workshopLoading">
          <el-table-column prop="name" label="车间名称" show-overflow-tooltip />
          <el-table-column prop="sortOrder" label="排序" align="center" sortable />
          <el-table-column label="状态" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isEnabled ? 'success' : 'danger'" size="small">{{ row.isEnabled ? '启用' : '停用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="{ row }">
              <div style="white-space:nowrap">
                <el-button link type="primary" @click="editWorkshop(row)">编辑</el-button>
                <el-button link type="primary" @click="toggleWorkshop(row)">{{ row.isEnabled ? '停用' : '启用' }}</el-button>
                <el-button link type="danger" @click="deleteWorkshop(row)" :disabled="row.machineCount > 0">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增/编辑车间弹窗 -->
        <el-dialog v-model="workshopDialogVisible" :title="editingWorkshopId ? '编辑车间' : '新增车间'" width="400px" destroy-on-close>
          <el-form ref="workshopFormRef" :model="workshopForm" :rules="workshopRules" label-width="100px">
            <el-form-item label="车间名称" prop="name"><el-input v-model="workshopForm.name" maxlength="100" /></el-form-item>
            <el-form-item label="排序号" prop="sortOrder"><el-input-number v-model="workshopForm.sortOrder" :min="0" :max="99" /></el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="workshopDialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="workshopSubmitting" @click="saveWorkshop">保存</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>

      <!-- Tab3: 修改密码 -->
      <el-tab-pane label="修改密码" name="password">
        <el-card shadow="hover" style="max-width:500px">
          <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="100px">
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input v-model="pwdForm.currentPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="pwdForm.newPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="pwdForm.confirmPassword" type="password" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="pwdSubmitting" @click="changePassword">确认修改</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'
import { useMockMode } from '@/composables/useMockMode'
import type { SysConfig } from '@/types'

/** 车间管理表格行类型（包含管理页面扩展字段） */
interface WorkshopRow {
  id: number
  name: string
  sortOrder: number
  isEnabled: boolean
  machineCount: number
}

const router = useRouter()
const { isMock } = useMockMode()
const activeTab = ref('config')

// 任务1: 敏感字段显示控制
// 记录每个配置项的可见性（仅对敏感字段有效）
const visibleMap = ref(new Map<string, boolean>())

function isVisible(key: string): boolean {
  return visibleMap.value.get(key) ?? false
}

function toggleVisibility(key: string) {
  const v = visibleMap.value.get(key) ?? false
  visibleMap.value.set(key, !v)
}

// 将表格中显示的值切换为真实值/掩码的逻辑，便于模板展示
function getDisplayValue(row: SysConfig): string {
  const key = row.configKey
  if (isSensitive(key)) {
    return isVisible(key) ? String(row.configValue) : '••••••••'
  }
  return String(row.configValue)
}

// 扩展：敏感字段识别规则（系统设置全部明文显示，不脱敏）
function isSensitive(_key: string): boolean {
  return false
}

// ===== Tab1: 系统配置 =====
const configLoading = ref(false)
const configList = ref<SysConfig[]>([])
const configKeyword = ref('')
const configDialogVisible = ref(false)
const configSubmitting = ref(false)
const configForm = reactive({ configKey: '', valueType: '', numberValue: 0, stringValue: '', description: '', id: 0, displayValue: '', originalValue: '' })

const filteredConfigs = computed(() => {
  if (!configKeyword.value) return configList.value
  const kw = configKeyword.value.toLowerCase()
  return configList.value.filter((c: {configKey:string;description:string}) => c.configKey.toLowerCase().includes(kw) || c.description.toLowerCase().includes(kw))
})
function filterConfig() { /* computed auto-filters */ }

async function loadConfigs() {
  configLoading.value = true
  try { const r = await request.get('/admin/sys-config') as any; configList.value = r.data?.items || [] } finally { configLoading.value = false }
}

function editConfig(row: SysConfig) {
  configForm.id = row.id
  configForm.configKey = row.configKey
  configForm.valueType = row.valueType
  configForm.description = row.description
  configForm.originalValue = row.configValue
  if (row.valueType === 'number') { configForm.numberValue = Number(row.configValue) } else {
    // 编辑弹窗中默认掩码，敏感字段显示为掩码，点击切换可显示/隐藏
    if (isSensitive(row.configKey)) {
      configForm.displayValue = '••••••••'
    } else {
      configForm.displayValue = String(row.configValue)
    }
  }
  configDialogVisible.value = true
}

async function saveConfig() {
  configSubmitting.value = true
  try {
    let valueToSend: string
    if (configForm.valueType === 'number') {
      valueToSend = String(configForm.numberValue)
    } else {
      const key = configForm.configKey
      if (isSensitive(key) && configForm.displayValue === '••••••••') {
        valueToSend = configForm.originalValue
      } else {
        valueToSend = configForm.displayValue
      }
    }
    await request.put(`/admin/sys-config/${configForm.id}`, { configValue: valueToSend })
    ElMessage.success('保存成功')
    configDialogVisible.value = false
    loadConfigs()
  } finally { configSubmitting.value = false }
}

async function resetToken(row: SysConfig) {
  await ElMessageBox.confirm(`确定重置${row.description}？重置后需同步更新相关服务配置。`, '提示', { type: 'warning' })
  const r = await request.post('/admin/sys-config/reset-token', { configKey: row.configKey }) as any
  ElMessage.success('重置成功，新值：' + (r.data?.newValue || '已生成'))
  loadConfigs()
}

// ===== Tab2: 车间管理 =====
const workshopLoading = ref(false)
const workshopList = ref<WorkshopRow[]>([])
const workshopDialogVisible = ref(false)
const workshopSubmitting = ref(false)
const editingWorkshopId = ref<number | null>(null)
const workshopFormRef = ref<FormInstance>()
const workshopForm = reactive({ name: '', sortOrder: 0 })
const workshopRules: FormRules = {
  name: [{ required: true, message: '请输入车间名称', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
}

async function loadWorkshops() {
  workshopLoading.value = true
  try { const r = await request.get('/admin/workshop') as any; workshopList.value = r.data?.items || [] } finally { workshopLoading.value = false }
}

function addWorkshop() {
  editingWorkshopId.value = null
  Object.assign(workshopForm, { name: '', sortOrder: workshopList.value.length + 1 })
  workshopDialogVisible.value = true
}

function editWorkshop(row: WorkshopRow) {
  editingWorkshopId.value = row.id
  Object.assign(workshopForm, { name: row.name, sortOrder: row.sortOrder })
  workshopDialogVisible.value = true
}

async function saveWorkshop() {
  const valid = await workshopFormRef.value?.validate().catch(() => false)
  if (!valid) return
  workshopSubmitting.value = true
  try {
    await request[editingWorkshopId.value ? 'put' : 'post'](editingWorkshopId.value ? `/admin/workshop/${editingWorkshopId.value}` : '/admin/workshop', { ...workshopForm })
    ElMessage.success('保存成功')
    workshopDialogVisible.value = false
    loadWorkshops()
  } finally { workshopSubmitting.value = false }
}

async function toggleWorkshop(row: WorkshopRow) {
  await ElMessageBox.confirm(`确定${row.isEnabled ? '停用' : '启用'}车间【${row.name}】？`, '提示', { type: 'warning' })
  await request.put(`/admin/workshop/${row.id}/toggle`)
  ElMessage.success('操作成功')
  loadWorkshops()
}

async function deleteWorkshop(row: WorkshopRow) {
  await ElMessageBox.confirm(`确定删除车间【${row.name}】？此操作不可恢复。`, '提示', { type: 'warning' })
  await request.delete(`/admin/workshop/${row.id}`)
  ElMessage.success('已删除')
  loadWorkshops()
}

// ===== Tab3: 修改密码 =====
const pwdSubmitting = ref(false)
const pwdFormRef = ref<FormInstance>()
const pwdForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' })

const validateConfirm = (_rule: unknown, value: string, callback: (err?:Error)=>void) => {
  if (value !== pwdForm.newPassword) { callback(new Error('两次输入密码不一致')) } else { callback() }
}

const pwdRules: FormRules = {
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 32, message: '密码长度8-32位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirm, trigger: 'blur' },
  ],
}

async function changePassword() {
  const valid = await pwdFormRef.value?.validate().catch(() => false)
  if (!valid) return
  pwdSubmitting.value = true
  try {
    await request.post('/admin/change-password', { currentPassword: pwdForm.currentPassword, newPassword: pwdForm.newPassword })
    ElMessage.success('密码修改成功，请重新登录')
    localStorage.removeItem('token')
    router.push(isMock.value ? '/mock/login' : '/login')
  } finally { pwdSubmitting.value = false }
}

onMounted(() => { loadConfigs(); loadWorkshops() })
</script>
