<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { todayStr } from '@/utils'
import { workPlansApi } from '@/api/workPlans'
import { customersApi } from '@/api/customers'
import { useAuthStore } from '@/stores/auth'
import api from '@/api/index'

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()
const isEdit = computed(() => !!route.params.id)
const submitLoading = ref(false)
const customers = ref<any[]>([])
const allManagers = ref<any[]>([])

const form = ref({
  customer_id: '',
  plan_content: '',
  plan_date: todayStr(),
  status: '计划中',
  manager_id: auth.userId || '',
})

onMounted(async () => {
  loadCustomers()
  if (auth.isDirector || auth.isLeader) {
    api.get('/users/', { params: { role: 'manager' } }).then(r => { allManagers.value = r.data }).catch(() => {})
  }
  if (isEdit.value) {
    try {
      const res = await api.get(`/work-plans/${route.params.id}`)
      const d = res.data
      form.value = { customer_id: d.customer_id, plan_content: d.plan_content || '', plan_date: d.plan_date, status: d.status, manager_id: d.manager_id || auth.userId || '' }
    } catch (_) {}
  }
})

const customerSearch = ref('')

async function loadCustomers(q?: string) {
  try {
    const params: any = { page_size: 100 }
    if (q) params.search = q
    const res = await customersApi.list(params)
    customers.value = res.data.items || []
  } catch (_) {}
}

async function handleCustomerSearch(query: string) {
  customerSearch.value = query
  if (query) { await loadCustomers(query) }
  else { await loadCustomers() }
}

async function handleQuickCreate() {
  const name = customerSearch.value.trim()
  if (!name) { ElMessage.warning('请输入单位名称'); return }
  try {
    const res = await api.post('/customers/quick-create', null, { params: { name } })
    const newCust = res.data
    customers.value.unshift(newCust)
    form.value.customer_id = newCust.id
    customerSearch.value = ''
    ElMessage.success(`已创建客户：${name}`)
    await loadCustomers()
  } catch (e: any) {
    ElMessage.error('创建失败: ' + (e.response?.data?.detail || e.message))
  }
}

async function handleSubmit() {
  if (!form.value.customer_id) { ElMessage.warning('请选择客户'); return }
  submitLoading.value = true
  try {
    if (isEdit.value) {
      await api.put(`/work-plans/${route.params.id}`, form.value)
      ElMessage.success('已更新')
    } else {
      await workPlansApi.create(form.value)
      ElMessage.success('计划已提交')
    }
    router.push('/m/plans')
  } catch (e: any) {
    ElMessage.error((isEdit.value ? '更新' : '提交') + '失败')
  } finally { submitLoading.value = false }
}

async function handleDelete() {
  try {
    await ElMessageBox.confirm('确定删除？', '确认', { type: 'warning' })
    await api.delete(`/work-plans/${route.params.id}`)
    ElMessage.success('已删除')
    router.push('/m/plans')
  } catch (e: any) { if (e !== 'cancel') ElMessage.error('删除失败') }
}
</script>

<template>
  <div class="form-page">
    <header class="form-editorial-header">
      <button class="form-back-btn" @click="router.back()">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="19" y1="12" x2="5" y2="12"></line>
          <polyline points="12 19 5 12 12 5"></polyline>
        </svg>
      </button>
      <div class="form-title-group">
        <h2 class="form-title">{{ isEdit ? '编辑工作计划' : '添加工作计划' }}</h2>
        <span class="form-subtitle">WORK PLAN</span>
      </div>
      <div class="form-rule"></div>
    </header>

    <el-form label-position="top" class="editorial-form">
      <el-form-item>
        <template #label><span class="form-label">客户单位</span></template>
        <el-select v-model="form.customer_id" filterable remote :remote-method="handleCustomerSearch" placeholder="搜索客户" style="width:100%">
          <el-option v-for="c in customers" :key="c.id" :label="c.name" :value="c.id" />
          <template #empty>
            <div v-if="customerSearch" class="select-empty-create">
              <p style="color:var(--warm-gray);font-size:13px;margin:0 0 8px">未找到「{{ customerSearch }}」</p>
              <button type="button" class="quick-create-btn" @click.stop="handleQuickCreate">新建客户「{{ customerSearch }}」</button>
            </div>
          </template>
        </el-select>
      </el-form-item>

      <el-form-item v-if="auth.isDirector || auth.isLeader">
        <template #label><span class="form-label">客户经理</span></template>
        <el-select v-model="form.manager_id" filterable placeholder="选择客户经理" style="width:100%">
          <el-option v-for="m in allManagers" :key="m.id" :label="m.name" :value="m.id" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <template #label><span class="form-label">工作计划</span></template>
        <el-input v-model="form.plan_content" type="textarea" :rows="4" placeholder="描述下周工作计划..." />
      </el-form-item>

      <el-form-item>
        <template #label><span class="form-label">计划拜访时间</span></template>
        <el-date-picker v-model="form.plan_date" type="date" style="width:100%" />
      </el-form-item>

      <div class="form-actions">
        <button class="submit-btn" :disabled="submitLoading" @click="handleSubmit">
          <span v-if="submitLoading" class="btn-loading"></span>
          {{ isEdit ? '保存修改' : '提交计划' }}
        </button>
        <button v-if="isEdit" class="delete-btn" @click="handleDelete">删除</button>
      </div>
    </el-form>
  </div>
</template>

<style scoped>
.form-page { max-width: 100%; margin: 0 auto; padding-bottom: 20px; }

.form-editorial-header {
  display: flex; align-items: flex-start; gap: 14px;
  margin-bottom: 26px; flex-wrap: wrap;
}

.form-back-btn {
  background: var(--surface); border: 1px solid var(--warm-border);
  padding: 8px 10px; cursor: pointer; color: var(--warm-gray);
  display: flex; align-items: center; transition: all var(--transition);
  flex-shrink: 0; margin-top: 2px;
}
.form-back-btn:hover { color: var(--ink); border-color: var(--ink); }

.form-title-group { display: flex; flex-direction: column; gap: 0; flex: 1; }

.form-title {
  margin: 0; font-family: var(--font-heading);
  font-size: 24px; font-weight: 400; color: var(--ink);
  letter-spacing: 0.06em; line-height: 1.3;
}

.form-subtitle {
  font-family: var(--font-mono);
  font-size: 9px; color: var(--gold); letter-spacing: 0.2em;
}

.form-rule {
  width: 100%; height: 2px; background: var(--warm-border);
  margin-top: 6px; position: relative;
}
.form-rule::after {
  content: ''; position: absolute; left: 0; top: 0;
  width: 32px; height: 2px; background: var(--gold);
}

.form-label {
  font-family: var(--font-heading) !important;
  font-size: 14px !important; color: var(--ink) !important;
  letter-spacing: 0.04em; font-weight: 500 !important;
}

.editorial-form .el-form-item { margin-bottom: 20px; }

.submit-btn {
  width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px;
  padding: 16px; background: var(--ink); color: #fff; border: none;
  font-family: var(--font-heading);
  font-size: 16px; letter-spacing: 0.08em; cursor: pointer; transition: all 0.25s;
  margin-top: 24px;
}
.submit-btn:hover { background: var(--ink-light); }
.submit-btn:active { transform: scale(0.98); }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }

.btn-loading {
  width: 16px; height: 16px;
  border: 2px solid rgba(255,255,255,0.3);
  border-top-color: #fff; border-radius: 50%;
  animation: spin 0.6s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.quick-create-btn { display: inline-flex; align-items: center; gap: 4px; background: none; border: 1px dashed var(--gold); padding: 8px 14px; color: var(--gold-dark); font-family: var(--font-body); font-size: 13px; cursor: pointer; transition: all 0.2s; letter-spacing: 0.03em; }
.quick-create-btn:hover { border-color: var(--vermilion); color: var(--vermilion); background: rgba(184,71,46,0.03); }
.select-empty-create { padding: 8px 12px; text-align: center; }
.form-actions { display: flex; gap: 10px; margin-top: 24px; }
.submit-btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: 8px; padding: 16px; background: var(--ink); color: #fff; border: none; font-family: var(--font-heading); font-size: 16px; letter-spacing: 0.08em; cursor: pointer; transition: all 0.25s; }
.submit-btn:hover { background: var(--ink-light); }
.submit-btn:active { transform: scale(0.98); }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.delete-btn { padding: 16px 24px; background: var(--surface); color: var(--vermilion); border: 1px solid var(--vermilion); font-family: var(--font-heading); font-size: 16px; letter-spacing: 0.08em; cursor: pointer; transition: all 0.25s; }
.delete-btn:hover { background: var(--vermilion); color: #fff; }
.btn-loading { width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.3); border-top-color: #fff; border-radius: 50%; animation: spin 0.6s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
