<template>
  <el-drawer
    v-model="showDrawer"
    direction="rtl"
    :title="isEditMode ? '编辑需求物资' : '添加需求物资'"
    size="35%"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" label-width="auto" class="add-supply-form">
      <el-form-item
        label="物资名称："
        prop="info.supplyName"
        :rules="[{ required: true, message: '请输入物资名称', trigger: 'blur' }]"
      >
        <el-select v-model="formData.info.supplyName" placeholder="请输入物资名称">
          <el-option v-for="item in SuppliesNameList" :key="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="规格：" prop="info.specs">
        <el-input v-model="formData.info.specs" placeholder="请输入规格" />
      </el-form-item>
      <el-form-item label="需求详情：" v-if="deptTree">
        <AddSuppliesSubForm
          ref="subFormRef"
          v-for="item in formData.detailList"
          :key="item.id"
          :init-data="item"
          :dept-tree="deptTree"
          :dept-selected="deptSelected"
          @update-sub-form="onUpdateSubForm"
          @close-sub-form="onCloseSubForm(item.id)"
        />
      </el-form-item>
      <el-form-item>
        <div class="add-supply-form-btns">
          <el-button @click="addDetail">新增</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showDrawer = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit"> 提交 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, useTemplateRef, computed } from 'vue';
  import { useRoute } from 'vue-router';
  import { ElDrawer, ElForm, ElInput, ElSelect, ElMessage } from 'element-plus';
  import type {
    AddSupplyRequestForm,
    AddSupplyRequestSubForm,
    SupplyRequestDetailItem,
  } from '@/types/emergency-supplier';
  import type { DeptTree } from '@/types/dept/type';
  import { createSupplyRequestDetail, getSupplyNameList, updateSupplyRequestDetail } from '@/api/emergency-supplier';
  import { getAllDepartments } from '@/api/auth/dept';
  import AddSuppliesSubForm from './AddSuppliesSubForm.vue';

  const route = useRoute();
  const planId = Number(route.params.id);

  const formRef = ref<InstanceType<typeof ElForm>>();
  const subFormRefs = useTemplateRef('subFormRef');

  const showDrawer = ref(false);
  const isEditMode = ref(false);
  const editInfoId = ref<number | null>(null);

  const lastDetailId = ref(0);

  // 获取物资名称
  const SuppliesNameList = ref<string[]>();
  const getSuppliesNameList = async () => {
    const res = await getSupplyNameList(planId);
    SuppliesNameList.value = res;
  };

  // 获取部门树
  const deptTree = ref<DeptTree[]>();
  const getDeptTreeData = async () => {
    const res = await getAllDepartments();
    deptTree.value = res.flatMap((item) => item.children ?? []);
  };

  // 表单数据
  const formData = reactive<AddSupplyRequestForm>({
    info: {},
    detailList: [
      {
        id: lastDetailId.value,
      },
    ],
  });
  // 表单中已选择的部门id
  const deptSelected = computed(() => {
    return formData.detailList.map((item) => item.deptId).filter((item) => item !== undefined);
  });

  // 清理表单数据
  const clearFormData = () => {
    lastDetailId.value = 0;
    formData.info = {};
    formData.detailList = [
      {
        id: lastDetailId.value,
      },
    ];
    isEditMode.value = false;
    editInfoId.value = null;
  };

  // 初始化编辑数据
  const initEditData = (editData: SupplyRequestDetailItem) => {
    isEditMode.value = true;
    editInfoId.value = editData.info.id;

    // 设置 info 数据
    formData.info = {
      id: editData.info.id,
      supplyName: editData.info.supplyName,
      specs: editData.info.specs,
    };

    // 设置 detailList 数据（编辑时不需要保留 id，使用负数作为临时 id）
    formData.detailList = editData.detailList.map((detail, index) => {
      return {
        id: -(index + 1), // 使用负数作为临时 id
        deptId: detail.deptId,
        deptName: detail.deptName,
        quantity: detail.quantity,
        requestReason: detail.requestReason,
        sizeDetail: detail.sizeDetail,
      };
    });

    // 更新 lastDetailId，确保新增项的 id 不会冲突
    if (formData.detailList.length > 0) {
      lastDetailId.value = formData.detailList.length;
    }
  };

  // 打开需求列表&数据初始化
  const openDrawer = async (editData?: SupplyRequestDetailItem) => {
    // 先打开 drawer，再加载数据
    showDrawer.value = true;

    // 如果是编辑模式，初始化编辑数据
    if (editData) {
      initEditData(editData);
    } else {
      // 创建时清理为初始化
      clearFormData();
    }

    // 重新加载数据，确保数据是最新的
    try {
      await Promise.all([getSuppliesNameList(), getDeptTreeData()]);
    } catch (error) {
      console.error('加载数据失败:', error);
      // 即使数据加载失败，drawer 也应该保持打开状态
    }
  };

  // 表单需求详情加一项
  const addDetail = () => {
    lastDetailId.value += 1;
    // 使用负数作为新项的 id，避免与已存在的记录 id 冲突
    formData.detailList.push({
      id: -lastDetailId.value,
    });
  };

  // 删除一项需求详情
  const onCloseSubForm = (id: number) => {
    if (formData.detailList.length === 1) {
      ElMessage.warning('至少一条需求详情');
      return;
    }
    formData.detailList = formData.detailList.filter((item) => item.id !== id);
  };

  // 更新一项需求详情
  const onUpdateSubForm = (data: AddSupplyRequestSubForm) => {
    const detail = formData.detailList.find((item) => item.id === data.id);
    if (!detail) return;
    Object.assign(detail, data);
  };

  // 表单校验
  const formValidate = async () => {
    if (!formRef.value) return;
    if (!subFormRefs.value) return;
    const subFormsValidateResultList = await Promise.all(subFormRefs.value.map((item) => item?.subFormValidate()));
    const isSubFormsValidateResult = subFormsValidateResultList.every((item) => item);
    if (!isSubFormsValidateResult) return;
    return await formRef.value.validate();
  };

  const getFormData = () => {
    return {
      info: { ...formData.info, planId },
      detailList: formData.detailList.map((item) => {
        // 编辑时不需要保留 detailList 的 id，只保留 info 的 id
        return {
          deptId: item.deptId,
          deptName: item.deptName,
          quantity: item.quantity,
          requestReason: item.requestReason,
          sizeDetail: item.sizeDetail,
        };
      }),
    };
  };

  interface Emits {
    (e: 'success'): void;
  }

  const emit = defineEmits<Emits>();

  // 提交表单
  const handleSubmit = async () => {
    const res = await formValidate();
    if (!res) return;
    const data = getFormData();
    try {
      if (isEditMode.value && editInfoId.value) {
        // 编辑模式
        await updateSupplyRequestDetail(data);
        ElMessage.success('编辑成功');
      } else {
        // 创建模式
        await createSupplyRequestDetail(data);
        ElMessage.success('提交成功');
      }
      showDrawer.value = false;
      emit('success');
    } catch (error) {
      ElMessage.error(isEditMode.value ? '编辑失败' : '提交失败');
    }
  };

  onMounted(() => {
    getSuppliesNameList();
    getDeptTreeData();
  });

  defineExpose({
    openDrawer,
  });
</script>

<style scoped>
  .el-form {
    display: flex;
    flex-direction: column;
    width: auto;
    height: 100%;
    gap: 24px;
  }
  .el-form-item {
    margin-bottom: 0;
  }
  .add-supply-form-btns {
    padding-left: 88px;
  }

  :deep(.el-form-item__label) {
    padding: 0;
  }

  :deep(.el-form-item__content) {
    gap: 16px;
  }

  :deep(.el-textarea__inner) {
    padding-bottom: 20px;
  }
</style>
