<template>
  <div>
    <div class="page-header">
      <h1>客户/项目管理</h1>
      <p>管理系统中的客户与项目，并指定所属销售</p>
    </div>

    <div class="content-card">
      <div class="card-title">
        <span>全部客户/项目 ({{ clients.length }})</span>
        <el-button type="primary" @click="showDialog()">+ 新增客户/项目</el-button>
      </div>
      <el-table :data="clients" stripe v-loading="loading">
        <el-table-column prop="name" label="客户/项目名称" min-width="160" />
        <el-table-column prop="sales_name" label="所属销售" min-width="100" />
        <el-table-column label="子项目预设" min-width="200">
          <template #default="{ row }">
            <template v-if="row.service_types && row.service_types.length">
              <el-tag v-for="st in row.service_types" :key="st" size="small" style="margin: 2px;">{{ st }}</el-tag>
            </template>
            <span v-else style="color: var(--text-muted); font-size: 12px;">未设置</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" effect="dark" round>
              {{ row.status === 1 ? '进行中' : '已结算' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_hours" label="总工时(h)" width="100" />
        <el-table-column prop="rd_count" label="参与研发" width="90" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="showDialog(row)">编辑</el-button>
            <el-button size="small" :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(row)">{{ row.status === 1 ? '结算' : '激活' }}</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="editingId ? '编辑客户/项目' : '新增客户/项目'" width="500px" destroy-on-close>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="客户/项目名称" />
        </el-form-item>
        <el-form-item label="所属销售" prop="sales_id">
          <el-select v-model="form.sales_id" placeholder="请选择销售人员" style="width: 100%" filterable>
            <el-option v-for="user in salesUsers" :key="user.id" :label="user.realname" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="子项目">
          <div class="tag-editor">
            <el-tag
              v-for="(st, idx) in form.service_types"
              :key="idx"
              closable
              effect="dark"
              size="default"
              class="st-tag"
              @close="removeServiceType(idx)"
            >{{ st }}</el-tag>
            <template v-if="!addingST">
              <el-button size="small" class="add-st-btn" @click="startAddST">＋ 添加</el-button>
            </template>
            <template v-else>
              <el-input
                ref="stInputRef"
                v-model="newST"
                size="small"
                class="st-input"
                placeholder="类型名，回车确认"
                @keyup.enter="confirmST"
                @blur="confirmST"
                maxlength="20"
              />
            </template>
          </div>
          <div style="font-size: 12px; color: var(--text-muted); margin-top: 6px;">
            研发填报该项目工时时，可从这里选择子项目
          </div>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="项目描述（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '../../api'

const clients = ref([])
const salesUsers = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const saving = ref(false)
const editingId = ref(null)
const formRef = ref(null)

// Service type inline tag editor
const addingST = ref(false)
const newST = ref('')
const stInputRef = ref(null)

const form = reactive({ name: '', description: '', sales_id: '', service_types: [] })
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  sales_id: [{ required: true, message: '请选择所属销售', trigger: 'change' }]
}

async function loadData() {
  loading.value = true
  try {
    const [clientsRes, salesRes] = await Promise.all([
      adminApi.getClients(),
      adminApi.getSalesUsers()
    ])
    clients.value = clientsRes.data
    salesUsers.value = salesRes.data
  } finally { loading.value = false }
}

function showDialog(row) {
  editingId.value = row?.id || null
  form.name = row?.name || ''
  form.description = row?.description || ''
  form.sales_id = row?.sales_id || ''
  form.service_types = row?.service_types ? [...row.service_types] : []
  addingST.value = false
  newST.value = ''
  dialogVisible.value = true
}

// Tag editor helpers
async function startAddST() {
  addingST.value = true
  newST.value = ''
  await nextTick()
  stInputRef.value?.focus()
}
function confirmST() {
  const v = newST.value.trim()
  if (v && !form.service_types.includes(v)) form.service_types.push(v)
  addingST.value = false
  newST.value = ''
}
function removeServiceType(idx) {
  form.service_types.splice(idx, 1)
}

async function handleSave() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  saving.value = true
  try {
    const payload = {
      name: form.name,
      description: form.description,
      sales_id: form.sales_id,
      service_types: form.service_types
    }
    if (editingId.value) {
      await adminApi.updateClient(editingId.value, payload)
      ElMessage.success('更新成功')
    } else {
      await adminApi.createClient(payload)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadData()
  } finally { saving.value = false }
}

async function toggleStatus(row) {
  await adminApi.updateClient(row.id, { status: row.status === 1 ? 0 : 1 })
  ElMessage.success('状态已更新')
  loadData()
}

async function handleDelete(row) {
  await ElMessageBox.confirm(
    `确定删除项目「${row.name}」吗？如已有工时记录则无法删除，建议使用“结算”操作。`,
    '确认删除', { type: 'warning' }
  )
  await adminApi.deleteClient(row.id)
  ElMessage.success('删除成功')
  loadData()
}

onMounted(loadData)
</script>

<style scoped>
.tag-editor {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  min-height: 36px;
  padding: 6px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background: rgba(0,0,0,0.1);
}
.st-tag { border-radius: 16px; }
.add-st-btn {
  border-radius: 16px;
  border-style: dashed;
}
.st-input { width: 140px; }
</style>
