<template>
  <div class="app-page">
    <!-- 筛选区 -->
    <section class="glass-card section-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="采购单号">
          <el-input v-model="filters.poNo" placeholder="PO-xxx" clearable style="width:160px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="filters.supplier" placeholder="全部" clearable filterable style="width:160px">
            <el-option v-for="s in supplierOptions" :key="s" :label="s" :value="s" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购状态">
          <el-select v-model="filters.status" placeholder="全部" clearable style="width:130px">
            <el-option v-for="s in poStatuses" :key="s.value" :label="s.label" :value="s.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="SKU">
          <el-input v-model="filters.sku" placeholder="SKU 编码" clearable style="width:140px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="filters.createdRange" type="daterange" start-placeholder="开始" end-placeholder="结束" value-format="YYYY-MM-DD" style="width:240px" />
        </el-form-item>
        <el-form-item label="预计交期">
          <el-date-picker v-model="filters.expectedRange" type="daterange" start-placeholder="开始" end-placeholder="结束" value-format="YYYY-MM-DD" style="width:240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </section>

    <!-- 工具栏 -->
    <section class="glass-card section-card" style="padding:12px 24px">
      <div class="table-toolbar" style="margin-bottom:0">
        <div class="chip-list">
          <el-button type="primary" @click="openCreate">创建采购单</el-button>
          <el-button :disabled="!selected.length" @click="batchConfirmArrival">确认到货</el-button>
        </div>
        <el-button @click="loadData">刷新</el-button>
      </div>
    </section>

    <!-- 列表 -->
    <section class="glass-card section-card">
      <el-table :data="filteredItems" stripe style="width:100%" v-loading="loading" @selection-change="onSelection">
        <el-table-column type="selection" width="45" />
        <el-table-column prop="poNo" label="采购单号" width="160" />
        <el-table-column prop="supplier" label="供应商" min-width="180" />
        <el-table-column prop="skuCount" label="SKU 数" width="80" />
        <el-table-column prop="amount" label="采购总额" width="120" />
        <el-table-column prop="expectedDate" label="预计交期" width="120" />
        <el-table-column prop="arrivalProgress" label="到货进度" min-width="140">
          <template #default="{ row }">
            <el-progress :percentage="parseProgress(row.arrivalProgress)" :stroke-width="6" style="width:100px" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="采购状态" width="110">
          <template #default="{ row }">
            <el-tag :type="poStatusType(row.status)" size="small">{{ poStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openConfirmArrival(row)" :disabled="row.status === '已关闭' || row.status === 'completed'">确认到货</el-button>
            <el-button link type="danger" @click="closePO(row)" :disabled="row.status === '已关闭' || row.status === 'completed'">关闭</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
      <div style="display:flex;justify-content:flex-end;margin-top:16px" v-if="total > 0">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" @size-change="loadData" @current-change="loadData" />
      </div>
    </section>

    <!-- 创建采购单弹窗 -->
    <el-dialog v-model="createDialogVisible" title="创建采购单" width="800px" destroy-on-close>
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px" label-position="right">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-select v-model="createForm.supplier" placeholder="请选择供应商" filterable style="width:100%" @change="onSupplierChange">
                <el-option v-for="s in supplierOptions" :key="s" :label="s" :value="s" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货仓库" prop="warehouse">
              <el-select v-model="createForm.warehouse" placeholder="请选择仓库" style="width:100%">
                <el-option label="华东仓" value="华东仓" />
                <el-option label="华南仓" value="华南仓" />
                <el-option label="海外仓" value="海外仓" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="createForm.currency" placeholder="币种" style="width:100%">
                <el-option label="CNY" value="CNY" />
                <el-option label="USD" value="USD" />
                <el-option label="EUR" value="EUR" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率" prop="tax">
              <el-input v-model="createForm.tax" placeholder="如 13%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运费" prop="freight">
              <el-input v-model="createForm.freight" placeholder="运费金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="预计交期" prop="expectedDate">
          <el-date-picker v-model="createForm.expectedDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>

        <!-- 采购 SKU 明细 -->
        <el-divider content-position="left">采购 SKU 明细</el-divider>
        <div v-for="(item, idx) in createForm.items" :key="idx" style="margin-bottom:12px">
          <el-row :gutter="8" align="middle">
            <el-col :span="8">
              <el-form-item :prop="`items.${idx}.sku`" :rules="[{ required: true, message: '请输入 SKU', trigger: 'blur' }]">
                <el-input v-model="item.sku" placeholder="SKU 编码" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item :prop="`items.${idx}.qty`" :rules="[{ required: true, message: '数量', trigger: 'blur' }]">
                <el-input-number v-model="item.qty" :min="1" :max="99999" controls-position="right" placeholder="数量" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item :prop="`items.${idx}.price`" :rules="[{ required: true, message: '单价', trigger: 'blur' }]">
                <el-input v-model="item.price" placeholder="单价" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <span style="line-height:32px;font-weight:600">{{ lineTotal(item) }}</span>
            </el-col>
            <el-col :span="2">
              <el-button link type="danger" @click="removeItem(idx)" :disabled="createForm.items.length <= 1">删除</el-button>
            </el-col>
          </el-row>
        </div>
        <el-button type="primary" link @click="addItem" style="margin-bottom:12px">+ 添加 SKU</el-button>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="createForm.remark" type="textarea" :rows="3" placeholder="备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleCreateSubmit">确认创建</el-button>
      </template>
    </el-dialog>

    <!-- 确认到货弹窗 -->
    <el-dialog v-model="arrivalDialogVisible" title="确认到货" width="520px" destroy-on-close>
      <el-form ref="arrivalFormRef" :model="arrivalForm" :rules="arrivalRules" label-width="100px">
        <el-form-item label="采购单号">
          <el-input :model-value="arrivalForm.poNo" disabled />
        </el-form-item>
        <el-form-item label="到货 SKU" prop="sku">
          <el-input v-model="arrivalForm.sku" placeholder="到货 SKU 编码" />
        </el-form-item>
        <el-form-item label="到货数量" prop="qty">
          <el-input-number v-model="arrivalForm.qty" :min="1" :max="99999" controls-position="right" style="width:100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="arrivalForm.remark" type="textarea" :rows="2" placeholder="到货备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="arrivalDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleArrivalSubmit">确认到货</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { api } from '@/api/services';
import type { PurchaseOrderItem, PurchaseOrderFormData } from '@/types/page';

const items = ref<PurchaseOrderItem[]>([]);
const selected = ref<PurchaseOrderItem[]>([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const createDialogVisible = ref(false);
const arrivalDialogVisible = ref(false);
const submitting = ref(false);

const createFormRef = ref<FormInstance>();
const arrivalFormRef = ref<FormInstance>();

const supplierOptions = ref<string[]>([]);

const poStatuses = [
  { label: '草稿', value: 'draft' },
  { label: '待审批', value: 'pending_approval' },
  { label: '已审批', value: 'approved' },
  { label: '部分到货', value: 'partial_arrival' },
  { label: '已完成', value: 'completed' },
  { label: '已关闭', value: 'closed' }
];

const filters = ref({
  poNo: '',
  supplier: '',
  status: '',
  sku: '',
  createdRange: null as string[] | null,
  expectedRange: null as string[] | null
});

interface CreateFormItem {
  sku: string;
  qty: number;
  price: string;
}

const defaultCreateForm = (): PurchaseOrderFormData & { items: CreateFormItem[] } => ({
  supplier: '',
  warehouse: '',
  items: [{ sku: '', qty: 1, price: '' }],
  currency: 'CNY',
  tax: '',
  freight: '',
  expectedDate: '',
  remark: ''
});

const createForm = reactive(defaultCreateForm());
const createRules: FormRules = {
  supplier: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  warehouse: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  currency: [{ required: true, message: '请选择币种', trigger: 'change' }],
  expectedDate: [{ required: true, message: '请选择预计交期', trigger: 'change' }]
};

const arrivalForm = reactive({
  poNo: '',
  poId: '',
  sku: '',
  qty: 1,
  remark: ''
});

const arrivalRules: FormRules = {
  sku: [{ required: true, message: '请输入到货 SKU', trigger: 'blur' }],
  qty: [{ required: true, message: '请输入到货数量', trigger: 'blur' }]
};

const filteredItems = computed(() => {
  return items.value.filter((item) => {
    if (filters.value.poNo && !item.poNo.includes(filters.value.poNo)) return false;
    if (filters.value.supplier && item.supplier !== filters.value.supplier) return false;
    if (filters.value.status && item.status !== filters.value.status) return false;
    if (filters.value.sku && !String(item.skuCount).includes(filters.value.sku)) return false;
    if (filters.value.createdRange && filters.value.createdRange.length === 2) {
      if (item.createdAt < filters.value.createdRange[0] || item.createdAt > filters.value.createdRange[1]) return false;
    }
    if (filters.value.expectedRange && filters.value.expectedRange.length === 2) {
      if (item.expectedDate < filters.value.expectedRange[0] || item.expectedDate > filters.value.expectedRange[1]) return false;
    }
    return true;
  });
});

const total = computed(() => filteredItems.value.length);

const parseProgress = (p: string) => {
  const num = parseInt(p, 10);
  return isNaN(num) ? 0 : Math.min(100, Math.max(0, num));
};

const poStatusType = (s: string) => {
  const map: Record<string, string> = {
    draft: 'info',
    pending_approval: 'warning',
    approved: '',
    partial_arrival: 'warning',
    completed: 'success',
    closed: 'danger'
  };
  return map[s] || '';
};

const poStatusLabel = (s: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    pending_approval: '待审批',
    approved: '已审批',
    partial_arrival: '部分到货',
    completed: '已完成',
    closed: '已关闭'
  };
  return map[s] || s;
};

const lineTotal = (item: CreateFormItem) => {
  const price = parseFloat(item.price) || 0;
  return (price * item.qty).toFixed(2);
};

const loadData = async () => {
  loading.value = true;
  try {
    const [poRes, supplierRes] = await Promise.all([
      api.getPurchaseOrders(),
      api.getSuppliers()
    ]);
    items.value = poRes.items;
    supplierOptions.value = supplierRes.items.map((s) => s.name);
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.value = { poNo: '', supplier: '', status: '', sku: '', createdRange: null, expectedRange: null };
};

const onSelection = (rows: PurchaseOrderItem[]) => {
  selected.value = rows;
};

const onSupplierChange = (_val: string) => {
  // Auto-fill default lead time & MOQ from supply capability (future enhancement)
};

const addItem = () => {
  createForm.items.push({ sku: '', qty: 1, price: '' });
};

const removeItem = (idx: number) => {
  createForm.items.splice(idx, 1);
};

const openCreate = () => {
  Object.assign(createForm, defaultCreateForm());
  createDialogVisible.value = true;
};

const handleCreateSubmit = async () => {
  if (!createFormRef.value) return;
  await createFormRef.value.validate();
  submitting.value = true;
  try {
    await api.createPurchaseOrder(createForm);
    ElMessage.success('采购单创建成功');
    createDialogVisible.value = false;
    loadData();
  } finally {
    submitting.value = false;
  }
};

const openConfirmArrival = (row: PurchaseOrderItem) => {
  arrivalForm.poNo = row.poNo;
  arrivalForm.poId = row.id;
  arrivalForm.sku = '';
  arrivalForm.qty = 1;
  arrivalForm.remark = '';
  arrivalDialogVisible.value = true;
};

const handleArrivalSubmit = async () => {
  if (!arrivalFormRef.value) return;
  await arrivalFormRef.value.validate();
  submitting.value = true;
  try {
    const po = items.value.find(p => p.id === arrivalForm.poId);
    await api.updatePurchaseOrder(Number(arrivalForm.poId), {
      status: 'partial_arrival'
    } as Partial<PurchaseOrderItem>);
    
    const invRes = await api.getInventories();
    const invItem = invRes.items.find((inv: any) => inv.sku === arrivalForm.sku);
    if (invItem) {
      const newAvailable = (invItem.available || 0) + arrivalForm.qty;
      const newInTransit = Math.max(0, ((invItem as any).inTransit || 0) - arrivalForm.qty);
      await api.updateInventory(Number(invItem.id), {
        available: newAvailable,
        inTransit: newInTransit
      } as any);
      await api.createInventoryLog({
        source: '采购到货入库',
        relatedOrder: po?.poNo || arrivalForm.poId,
        operator: '采购',
        quantity: arrivalForm.qty,
        afterQty: newAvailable,
        time: new Date().toISOString()
      });
      ElMessage.success(`到货确认成功，${arrivalForm.sku} 库存 +${arrivalForm.qty}`);
    } else {
      ElMessage.success('到货确认成功（未找到对应库存记录）');
    }
    arrivalDialogVisible.value = false;
    loadData();
  } finally {
    submitting.value = false;
  }
};

const batchConfirmArrival = async () => {
  if (!selected.value.length) return;
  try {
    await ElMessageBox.confirm(
      `确认对选中的 ${selected.value.length} 个采购单进行到货确认？`,
      '批量确认到货'
    );
    for (const po of selected.value) {
      await api.updatePurchaseOrder(Number(po.id), { status: 'partial_arrival' } as Partial<PurchaseOrderItem>);
    }
    ElMessage.success('批量到货确认成功');
    loadData();
  } catch {
    // cancelled
  }
};

const closePO = async (row: PurchaseOrderItem) => {
  try {
    await ElMessageBox.confirm(
      `确认关闭采购单「${row.poNo}」？关闭后将无法继续到货确认。`,
      '关闭确认',
      { type: 'warning' }
    );
    await api.updatePurchaseOrder(Number(row.id), { status: 'closed' } as Partial<PurchaseOrderItem>);
    ElMessage.success('采购单已关闭');
    loadData();
  } catch {
    // cancelled
  }
};

onMounted(loadData);
</script>

<style scoped>
.filter-form :deep(.el-form-item) { margin-bottom: 0; }
</style>
