<template>
  <main class="safety-platform-container__main">
    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #status>
        <el-radio-group v-model="ruleFormData.status" :disabled="isViewMode">
          <el-radio label="ENABLE">启用</el-radio>
          <el-radio label="DISABLE">禁用</el-radio>
        </el-radio-group>
      </template>
    </BasicForm>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isCreateMode ? '提交' : '保存' }}
    </el-button>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { INVENTORY_FORM_CONFIG, INVENTORY_FORM_DATA, INVENTORY_FORM_RULES } from '../configs/form';
  import { saveInventory } from '@/api/production-safety/business-registration-application';
  import { queryInventoryDetail, updateInventory } from '@/api/inventory';

  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'inventory-create');
  const currentId = computed(() => Number(route.query.id));

  const isCreateMode = computed(() => operate.value === 'inventory-create');
  const isEditMode = computed(() => operate.value === 'inventory-edit');
  const isViewMode = computed(() => operate.value === 'inventory-view');

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } = useFormConfigHook(
    INVENTORY_FORM_CONFIG,
    INVENTORY_FORM_DATA,
    INVENTORY_FORM_RULES,
  );

  // 查看模式下，所有字段设为只读
  const viewFormConfig = ref(
    INVENTORY_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: true,
      },
    })),
  );

  const computedFormConfig = computed(() => {
    if (isViewMode.value) {
      return viewFormConfig.value;
    }
    return ruleFormConfig.value;
  });

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    return res;
  };

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryInventoryDetail(currentId.value);
      if (res) {
        // 映射接口字段到表单字段
        ruleFormData.itemName = res.stuffName; // 奖品名称
        ruleFormData.warehouseDate = res.inStoreTime ? res.inStoreTime.split('T')[0] : ''; // 入库日期（YYYY-MM-DD）
        ruleFormData.itemQuantity = res.stuffQty; // 奖品数量
        ruleFormData.status = res.status ? 'ENABLE' : 'DISABLE'; // 状态
        ruleFormData.remarks = res.remark || ''; // 备注
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取奖品库存详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      const basePayload = {
        stuffName: ruleFormData.itemName,
        inStoreTime: ruleFormData.warehouseDate ? new Date(ruleFormData.warehouseDate).toISOString() : '',
        stuffQty: ruleFormData.itemQuantity,
        status: ruleFormData.status === 'ENABLE',
        remark: ruleFormData.remarks || '',
      };

      if (isCreateMode.value) {
        await saveInventory(basePayload);
        ElMessage.success('创建成功');
      } else if (isEditMode.value && currentId.value) {
        await updateInventory({
          id: currentId.value,
          ...basePayload,
        });
        ElMessage.success('保存成功');
      }

      router.back();
    } catch (e) {
      console.error('保存奖品库存失败:', e);
      ElMessage.error(e?.message || e?.data || '保存失败，请重试');
    }
  };

  onMounted(() => {
    cloneRuleFormData();
    if (isEditMode.value || isViewMode.value) {
      getDetail();
    }
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
</style>
