<script lang="ts" setup>
import { $t } from "@/common/languages";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { get, post } from "@/common/http/request";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  warehouseItemId: {
    type: Number,
    default: null,
  },
  selectedVendorUrl: {
    type: String,
    default: "",
  },
  saveVendorUrl: {
    type: String,
    default: "",
  },
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  saved: [];
}>();

const visible = defineModel<boolean>("visible");

const loading = ref(false);
const saving = ref(false);
const formRef = ref<FormInstance>();
const vendorList = ref<any[]>([]);
const allVendors = ref<any[]>([]);

const rules = reactive<FormRules>({
  vendorId: [{ required: true, message: $t("_message.warehouse.warehouse_item.select_vendor"), trigger: "change" }],
  costPrice: [{ required: true, message: $t("_message.warehouse.warehouse_item.input_costPrice"), trigger: "blur" }],
});

const loadVendorList = async () => {
  if (!props.warehouseItemId) {
    return;
  }

  loading.value = true;
  try {
    const response = await get(props.selectedVendorUrl, { warehouseItemId: props.warehouseItemId });
    vendorList.value = response.data || [];
  } catch (error) {
    console.error("Load vendor list failed:", error);
  } finally {
    loading.value = false;
  }
};

const loadAllVendors = async () => {
  try {
    const response = await get("/systemset/vendor/getVendorPage", { current: 1, size: 1000 });
    allVendors.value = response.data.records || [];
  } catch (error) {
    console.error("Load all vendors failed:", error);
  }
};

const addRow = () => {
  vendorList.value.push({
    id: null,
    vendorId: null,
    vendorName: "",
    costPrice: null,
    procureDate: null,
  });
};

const editRow = (row: any) => {
  row.isEditing = true;
};

const deleteRow = (index: number) => {
  vendorList.value.splice(index, 1);
};

const saveRow = (row: any) => {
  row.isEditing = false;
};

const cancelEdit = (row: any, originalRow: any) => {
  row.vendorId = originalRow.vendorId;
  row.costPrice = originalRow.costPrice;
  row.procureDate = originalRow.procureDate;
  row.isEditing = false;
};

const handleSave = async () => {
  if (!formRef.value) {
    return;
  }

  try {
    await formRef.value.validate();
  } catch (error) {
    return;
  }

  if (vendorList.value.length === 0) {
    ElMessage.warning($t("_message.warehouse.warehouse_item.select_vendor"));
    return;
  }

  saving.value = true;
  try {
    const vendorListData = vendorList.value.map(item => ({
      vendorId: item.vendorId,
      costPrice: item.costPrice,
      procureDate: item.procureDate,
    }));

    await post(props.saveVendorUrl, {
      warehouseItemId: props.warehouseItemId,
      vendorList: vendorListData,
    });

    ElMessage.success($t("_message.common.edit_success"));
    visible.value = false;
    emit("saved");
  } catch (error) {
    console.error("Save vendor list failed:", error);
  } finally {
    saving.value = false;
  }
};

const getVendorName = (vendorId: number) => {
  const vendor = allVendors.value.find(v => v.id === vendorId);
  return vendor ? vendor.vendorName : "";
};

watch(
  () => visible.value,
  val => {
    if (val) {
      loadVendorList();
      loadAllVendors();
    }
  }
);
</script>

<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="900px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form ref="formRef" :model="{ vendorList }" label-width="120px">
      <el-table :data="vendorList" border style="width: 100%" max-height="50vh" v-loading="loading">
        <el-table-column :label="$t('_prop.warehouse.warehouse_item.vendorName')" width="200">
          <template #default="{ row, $index }">
            <el-form-item v-if="row.isEditing" :prop="`vendorList.${$index}.vendorId`" :rules="rules.vendorId">
              <el-select
                v-model="row.vendorId"
                :placeholder="$t('_message.warehouse.warehouse_item.select_vendor')"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="vendor in allVendors"
                  :key="vendor.id"
                  :label="vendor.vendorName"
                  :value="vendor.id"
                />
              </el-select>
            </el-form-item>
            <span v-else>{{ getVendorName(row.vendorId) }}</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('_prop.warehouse.warehouse_item.costPrice')" width="150">
          <template #default="{ row, $index }">
            <el-form-item v-if="row.isEditing" :prop="`vendorList.${$index}.costPrice`" :rules="rules.costPrice">
              <el-input-number
                v-model="row.costPrice"
                :min="0"
                :precision="2"
                :placeholder="$t('_message.warehouse.warehouse_item.input_costPrice')"
                style="width: 100%"
              />
            </el-form-item>
            <span v-else>{{ row.costPrice }}</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('_prop.warehouse.warehouse_item.procureDate')" width="200">
          <template #default="{ row, $index }">
            <el-form-item v-if="row.isEditing" :prop="`vendorList.${$index}.procureDate`">
              <el-date-picker
                v-model="row.procureDate"
                type="datetime"
                :placeholder="$t('_message.warehouse.warehouse_item.select_procureDate')"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
            <span v-else>{{ row.procureDate }}</span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('_prop.common.operate')" width="150" align="center">
          <template #default="{ row, $index }">
            <template v-if="row.isEditing">
              <el-button type="primary" link size="small" @click="saveRow(row)">
                {{ $t("_button.confirm") }}
              </el-button>
              <el-button link size="small" @click="cancelEdit(row, { ...row })">
                {{ $t("_button.cancel") }}
              </el-button>
            </template>
            <template v-else>
              <el-button type="primary" link size="small" @click="editRow(row)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button type="danger" link size="small" @click="deleteRow($index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <div class="table-actions">
      <el-button type="primary" @click="addRow">
        <el-icon><Plus /></el-icon>
        {{ $t("_button.add") }}
      </el-button>
    </div>

    <template #footer>
      <el-button @click="visible = false">{{ $t("_button.cancel") }}</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        {{ $t("_button.confirm") }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.table-actions {
  margin-top: 10px;
  text-align: right;
}

.el-form-item {
  margin-bottom: 0;
}
</style>
