<script setup lang="ts">
import { computed, ref } from 'vue';
import { Button } from 'ant-design-vue';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { Page, useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { procurementApplicationInfo } from '#/api/property/assetManage/procurementApplication';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { modalSchema } from './data';
import procurementDetailModal from './procurement-detail-modal.vue';
import { detailColumns } from './data';
import {
  procurementApplicationAdd,
  procurementApplicationUpdate,
} from '#/api/property/assetManage/procurementApplication';
import { useUserStore } from '@vben/stores';

const userStore = useUserStore();
const emit = defineEmits<{ reload: [] }>();
const detailData = ref<any[]>([]); //采购资产详情
const isUpdate = ref(false);
const isDetail = ref(false);
const title = computed(() => {
  if (isDetail.value) {
    return '采购申请详情';
  }
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-1',
    // 默认label宽度 px
    labelWidth: 80,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
      disabled: computed(() => isDetail.value),
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[70%]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;
    // 只有在有id时才设置为详情模式（用于详情查看）
    isDetail.value = !!id;
    if (isUpdate.value && id) {
      const record = await procurementApplicationInfo(id);
      await formApi.setValues(record);

      // 在详情模式下，设置资产详情数据到表格
      if (isDetail.value && record.capitalInfoVoList) {
        detailData.value = record.capitalInfoVoList;
        // 更新表格数据
        if (tableApi.grid && tableApi.grid.loadData) {
          tableApi.grid.loadData(detailData.value);
        }
      }
    } else {
      // 新增模式
      isDetail.value = false; // 确保新增时不是详情模式
      await formApi.setValues({
        applicat: userStore.userInfo?.userId, // 存放ID
        applicatDisplay: userStore.userInfo?.realName, // 显示姓名
      });
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});
const [ProcurementDetailModal, detailModalApi] = useVbenModal({
  connectedComponent: procurementDetailModal,
});

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
  columns: detailColumns,
  data: detailData.value,
  // height: 'auto',
  keepSource: true,
  pagerConfig: {},
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'domain-procurementApplication-index',
  toolbarConfig: {
    // 隐藏"刷新/重置"按钮（对应 redo）
    refresh: false,
    zoom: false, // 显示全屏
    custom: false, // 隐藏列设置
  },
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
});
async function handleConfirm() {
  // 如果是详情模式，直接关闭弹窗
  if (isDetail.value) {
    modalApi.close();
    return;
  }

  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value
      ? procurementApplicationUpdate(data)
      : procurementApplicationAdd({
          ...data,
          capitalInfoBolist: detailData.value,
        }));

    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
function handleDetailReload(data: any) {
  detailData.value.push(data);
}
function handleEditDetailReload() {}
//添加物资
function handleAddDetail() {
  detailModalApi.setData({});
  detailModalApi.open();
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
    <div class="flex items-center justify-between" v-if="!isDetail">
      <div>采购物资：</div>
      <Button type="primary" @click="handleAddDetail">选择物资</Button>
    </div>
    <BasicTable />
    <ProcurementDetailModal
      @reload="handleDetailReload"
      @editReload="handleEditDetailReload"
    />
  </BasicModal>
</template>
