<template>
  <div>
    <div class="card">
      <div class="card-body" style="padding:10px 14px;">
        <div class="flex-row" style="flex-wrap:wrap;gap:12px;">
          <div class="flex-row">
            <span class="kv-label">状态</span>
            <select v-model="query.status" class="kv-input" style="width:110px;">
              <option value="">全部</option>
              <option v-for="s in statusOptions" :key="s.value" :value="s.value">{{ s.label }}</option>
            </select>
          </div>
          <div class="flex-row">
            <span class="kv-label">日期</span>
            <input v-model="query.start_date" type="date" class="kv-input" style="width:130px;" />
            <span class="kv-label">~</span>
            <input v-model="query.end_date" type="date" class="kv-input" style="width:130px;" />
          </div>
          <div class="flex-row">
            <button class="btn btn-primary" @click="fetchData">查询</button>
            <button class="btn btn-outline" @click="openDialog()">＋ 新增计划</button>
          </div>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-header">
        生产计划
        <span class="ch-badge">共 {{ total }} 条</span>
      </div>
      <div class="table-scroll" v-loading="loading">
        <table class="data-table">
          <thead>
            <tr>
              <th>计划号</th><th>计划日期</th><th>班次</th>
              <th>计划(卷)</th><th>计划重量(kg)</th>
              <th>实际(卷)</th><th>实际重量(kg)</th>
              <th>完成率</th><th>优先级</th><th>状态</th><th>创建人</th><th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in tableData" :key="row.id">
              <td class="td-num">{{ row.plan_no }}</td>
              <td class="td-muted">{{ fmtDate(row.plan_date) }}</td>
              <td>{{ row.shift ? row.shift + '班' : '—' }}</td>
              <td class="td-num">{{ row.plan_quantity }}</td>
              <td class="td-num">{{ row.plan_weight }}</td>
              <td class="td-num">{{ row.actual_quantity }}</td>
              <td class="td-num">{{ row.actual_weight }}</td>
              <td>
                <div v-if="row.plan_quantity > 0">
                  <div class="prog-bar-wrap" style="width:70px;display:inline-block;vertical-align:middle;margin-right:6px;">
                    <div class="prog-bar-fill" :style="{ width: completionRate(row) + '%', background: rateColor(row) }"></div>
                  </div>
                  <span :style="{ color: rateColor(row) }">{{ completionRate(row) }}%</span>
                </div>
                <span v-else class="td-muted">—</span>
              </td>
              <td>
                <span :class="['badge', row.priority >= 8 ? 'badge-red' : row.priority >= 5 ? 'badge-yellow' : 'badge-gray']">P{{ row.priority }}</span>
              </td>
              <td><span :class="['badge', statusBadge(row.status)]">{{ statusLabel(row.status) }}</span></td>
              <td class="td-muted">{{ row.created_by || '—' }}</td>
              <td>
                <span class="action-link" @click="openDialog(row)">编辑</span>
                <span v-if="row.status === 'draft'" class="action-link" style="color:var(--accent-green)" @click="confirmPlan(row)">确认</span>
              </td>
            </tr>
            <tr v-if="!tableData.length && !loading">
              <td colspan="12" class="td-muted" style="text-align:center;padding:24px;">暂无数据</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div v-if="dialogVisible" class="modal-mask" @click.self="dialogVisible=false">
      <div class="modal-box" style="width:640px;">
        <div class="modal-header">
          {{ editRow ? '编辑计划' : '新增计划' }}
          <span class="modal-close" @click="dialogVisible=false">✕</span>
        </div>
        <div class="modal-body">
          <div class="grid-2" style="gap:12px;">
            <div class="form-field">
              <div class="kv-label">计划号 *</div>
              <input v-model="form.plan_no" class="kv-input" :disabled="!!editRow" />
            </div>
            <div class="form-field">
              <div class="kv-label">计划日期</div>
              <input v-model="form.plan_date" type="date" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">班次</div>
              <select v-model="form.shift" class="kv-input">
                <option value="">不限</option>
                <option v-for="s in ['甲','乙','丙','丁']" :key="s" :value="s">{{ s }}班</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">优先级 (1-10)</div>
              <input v-model.number="form.priority" type="number" min="1" max="10" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">计划数量 (卷)</div>
              <input v-model.number="form.plan_quantity" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">计划重量 (kg)</div>
              <input v-model.number="form.plan_weight" type="number" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">主要钢种</div>
              <input v-model="form.steel_grade" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">规格范围</div>
              <input v-model="form.spec_range" class="kv-input" />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="dialogVisible=false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="save">{{ saving ? '保存中...' : '保存' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getPlans, createPlan, updatePlan, confirmPlan as apiConfirm } from '@/api'

const STATUS_MAP = {
  draft:       { label: '草稿',   badge: 'badge-gray'   },
  confirmed:   { label: '已确认', badge: 'badge-blue'   },
  in_progress: { label: '执行中', badge: 'badge-green'  },
  completed:   { label: '完成',   badge: 'badge-gray'   },
  cancelled:   { label: '取消',   badge: 'badge-red'    },
}

export default {
  name: 'Plan',
  data() {
    return {
      loading: false, saving: false,
      tableData: [], total: 0,
      query: { page: 1, page_size: 20, status: '', start_date: '', end_date: '' },
      statusOptions: Object.entries(STATUS_MAP).map(([value, { label }]) => ({ value, label })),
      dialogVisible: false, editRow: null, form: { priority: 5 },
    }
  },
  created() { this.fetchData() },
  methods: {
    async fetchData() {
      this.loading = true
      const params = { ...this.query }
      if (params.start_date) params.start_date += 'T00:00:00'
      if (params.end_date) params.end_date += 'T23:59:59'
      try { const res = await getPlans(params); this.tableData = res.data.items; this.total = res.data.total } finally { this.loading = false }
    },
    fmtDate(t) { return t ? t.slice(0, 10) : '—' },
    statusLabel(s) { return STATUS_MAP[s]?.label || s },
    statusBadge(s) { return STATUS_MAP[s]?.badge || 'badge-gray' },
    completionRate(row) { return row.plan_quantity > 0 ? Math.min(100, Math.round(row.actual_quantity / row.plan_quantity * 100)) : 0 },
    rateColor(row) {
      const r = this.completionRate(row)
      return r >= 90 ? 'var(--accent-green)' : r >= 70 ? 'var(--accent-yellow)' : 'var(--accent-red)'
    },
    openDialog(row = null) { this.editRow = row; this.form = row ? { ...row } : { priority: 5, plan_quantity: 0, plan_weight: 0 }; this.dialogVisible = true },
    async confirmPlan(row) {
      if (!confirm(`确认计划 ${row.plan_no}？`)) return
      await apiConfirm(row.id)
      this.$message.success('已确认')
      this.fetchData()
    },
    async save() {
      if (!this.form.plan_no) { this.$message.error('计划号不能为空'); return }
      this.saving = true
      try {
        const d = { ...this.form }
        if (d.plan_date && !d.plan_date.includes('T')) d.plan_date += 'T00:00:00'
        if (this.editRow) await updatePlan(this.editRow.id, d)
        else await createPlan(d)
        this.$message.success('保存成功')
        this.dialogVisible = false; this.fetchData()
      } finally { this.saving = false }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables';
.action-link { color: $sms-highlight; cursor: pointer; font-size: 12px; margin-right: 12px; &:hover { text-decoration: underline; } }
.form-field { display: flex; flex-direction: column; gap: 5px; }
.modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,.6); display: flex; align-items: center; justify-content: center; z-index: 9999; }
.modal-box { background: $bg-card; border: 1px solid $border; border-radius: 6px; max-width: 95vw; max-height: 90vh; display: flex; flex-direction: column; }
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: $bg-panel; border-bottom: 1px solid $border; font-size: 13px; font-weight: 600; color: $sms-highlight; .modal-close { cursor: pointer; color: $text-muted; &:hover { color: $text-primary; } } }
.modal-body { padding: 16px; overflow-y: auto; }
.modal-footer { padding: 10px 16px; background: $bg-panel; border-top: 1px solid $border; display: flex; justify-content: flex-end; gap: 10px; }
</style>
