<script setup lang="ts">
import { ref, reactive } from "vue";
import { message } from "@/utils/message";
import { createOrder } from "@/api/replenishmentOrder";
import type { FormInstance, FormRules } from "element-plus";
import type { ReplenishmentOrderItem } from "../utils/types";

const emit = defineEmits<{
  (e: "success"): void;
}>();

const visible = ref(false);
const formRef = ref<FormInstance>();
const loading = ref(false);

const form = reactive({
  deviceId: "",
  shopId: undefined as string | undefined,
  supplierName: "",
  warehouseName: "",
  expectedArrivalTime: "",
  remark: ""
});

const items = ref<ReplenishmentOrderItem[]>([
  {
    productId: "",
    productCode: "",
    productName: "",
    plannedQuantity: 1,
    unitPrice: undefined,
    shelfNum: undefined,
    position: ""
  }
]);

const rules: FormRules = {
  deviceId: [
    { required: true, message: "请输入设备SN号", trigger: "blur" }
  ]
};

function open() {
  resetForm();
  visible.value = true;
}

function resetForm() {
  form.deviceId = "";
  form.shopId = undefined;
  form.supplierName = "";
  form.warehouseName = "";
  form.expectedArrivalTime = "";
  form.remark = "";
  items.value = [
    {
      productId: "",
      productCode: "",
      productName: "",
      plannedQuantity: 1,
      unitPrice: undefined,
      shelfNum: undefined,
      position: ""
    }
  ];
}

function addItem() {
  items.value.push({
    productId: "",
    productCode: "",
    productName: "",
    plannedQuantity: 1,
    unitPrice: undefined,
    shelfNum: undefined,
    position: ""
  });
}

function removeItem(index: number) {
  if (items.value.length <= 1) return;
  items.value.splice(index, 1);
}

async function handleSubmit(formEl: FormInstance | undefined) {
  if (!formEl) return;
  const valid = await formEl.validate().catch(() => false);
  if (!valid) return;

  // Validate items
  const emptyItem = items.value.find(
    item => !item.productId && !item.productCode
  );
  if (emptyItem) {
    message("请填写商品信息", { type: "warning" });
    return;
  }

  loading.value = true;
  try {
    const { code } = await createOrder({
      deviceId: form.deviceId,
      shopId: form.shopId ? Number(form.shopId) : undefined,
      supplierName: form.supplierName || undefined,
      warehouseName: form.warehouseName || undefined,
      expectedArrivalTime: form.expectedArrivalTime
        ? form.expectedArrivalTime.replace("T", " ") + ":00"
        : undefined,
      remark: form.remark || undefined,
      items: items.value.map(item => ({
        productId: Number(item.productId),
        productCode: item.productCode || undefined,
        productName: item.productName || undefined,
        plannedQuantity: item.plannedQuantity,
        unitPrice: item.unitPrice,
        shelfNum: item.shelfNum,
        position: item.position || undefined
      }))
    });

    if (code === 200) {
      message("创建补货单成功", { type: "success" });
      visible.value = false;
      emit("success");
    }
  } finally {
    loading.value = false;
  }
}

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="visible"
    title="新建补货单"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="110px"
    >
      <el-form-item label="设备SN号" prop="deviceId">
        <el-input v-model="form.deviceId" placeholder="请输入设备SN号" />
      </el-form-item>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="供应商">
            <el-input v-model="form.supplierName" placeholder="ERP供应商名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库">
            <el-input v-model="form.warehouseName" placeholder="ERP仓库名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="预计到货时间">
            <el-date-picker
              v-model="form.expectedArrivalTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="w-full!"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="备注信息" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">补货商品</el-divider>

      <div v-for="(item, index) in items" :key="index" class="mb-2">
        <el-row :gutter="8" align="middle">
          <el-col :span="5">
            <el-input
              v-model="item.productCode"
              placeholder="商品编码"
              size="small"
            />
          </el-col>
          <el-col :span="5">
            <el-input
              v-model="item.productName"
              placeholder="商品名称"
              size="small"
            />
          </el-col>
          <el-col :span="3">
            <el-input-number
              v-model="item.plannedQuantity"
              :min="1"
              :max="99999"
              size="small"
              controls-position="right"
              class="w-full!"
            />
          </el-col>
          <el-col :span="3">
            <el-input-number
              v-model="item.unitPrice"
              :min="0"
              :precision="2"
              placeholder="单价"
              size="small"
              controls-position="right"
              class="w-full!"
            />
          </el-col>
          <el-col :span="2">
            <el-input-number
              v-model="item.shelfNum"
              :min="1"
              placeholder="层"
              size="small"
              controls-position="right"
              class="w-full!"
            />
          </el-col>
          <el-col :span="3">
            <el-input
              v-model="item.position"
              placeholder="货道位置"
              size="small"
            />
          </el-col>
          <el-col :span="2">
            <el-button
              type="danger"
              size="small"
              :icon="'ep:delete'"
              circle
              :disabled="items.length <= 1"
              @click="removeItem(index)"
            />
          </el-col>
        </el-row>
      </div>

      <el-button type="primary" link :icon="'ep:plus'" @click="addItem">
        添加商品
      </el-button>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit(formRef)">
        确认创建
      </el-button>
    </template>
  </el-dialog>
</template>
