<script setup lang="ts">
import {computed, ref} from 'vue';

import {useVbenModal} from '@vben/common-ui';
import {$t} from '@vben/locales';
import {cloneDeep} from '@vben/utils';

import {type FormSchemaGetter, useVbenForm} from "#/adapter/form";
import {
  applicationAdd,
  applicationInfo,
  applicationUpdate
} from '#/api/property/assetManage/application';
import {defaultFormValueGetter, useBeforeCloseDiff} from '#/utils/popup';

import {modalSchema} from './data';
import {assetTypeselect} from "#/api/property/assetType";
import {depotList} from "#/api/property/assetManage/depot";
import {suppliersList} from "#/api/property/assetManage/suppliers";
import {assetList} from "#/api/property/assetManage/asset";
import {userList} from "#/api/system/user";
import type {AssetVO} from "#/api/property/assetManage/asset/model";

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

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

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

formApi.getValues().then(setupPackageSelect);

async function upSelectUser(nickName: string) {
  const list = await userList({
    nickName: nickName,
    pageNum: 1,
    pageSize: 10,
  });
  const options = list.map(item => {
    item.label = item.userName;
    item.value = item.id;
  })
  fromApi.updateSchema([
    {
      componentProps: {
        optionFilterProp: 'label',
        optionLabelProp: 'label',
        options,
        showSearch: true,
      },
      fieldName: 'userId',
    },
  ]);
}

async function upSelectAssets(assetsName: string) {
  const list = await assetList({
    assetsName: assetsName,
    pageNum: 1,
    pageSize: 10,
  });
  const options = list.map(item => {
    item.label = item.assetsName;
    item.value = item.id;
  })
  fromApi.updateSchema([
    {
      componentProps: {
        optionFilterProp: 'label',
        optionLabelProp: 'label',
        options,
        showSearch: true,
      },
      fieldName: 'assetsId',
    },
  ]);
}

const assetsData = ref<AssetVO[]>([])

async function setupPackageSelect() {
  const users = await userList({
    pageNum: 1,
    pageSize: 1000,
  });
  const assets = await assetList({
    pageNum: 1,
    pageSize: 1000,
  });
  assetsData.value = assets.rows
  const options = users.rows.map((item) => ({
    label: item.nickName,
    value: item.userId,
  }));
  const assetOptions = assets.rows.map((item) => ({
    label: item.name,
    value: item.id,
  }));
  formApi.updateSchema([
    {
      componentProps: {
        optionFilterProp: 'label',
        optionLabelProp: 'label',
        options,
        showSearch: true,
      },
      async select(userId) {
        await upSelectUser(userId);
        userId = ""
      },
      fieldName: 'userId',
    },
    {
      componentProps: {
        optionFilterProp: 'label',
        optionLabelProp: 'label',
        options: assetOptions,
        showSearch: true,
        onChange: async (value: string) => {
          // 找到选中的服务数据
          const assetInfo = assetsData.value.find(item => item.id === value);
          if (assetInfo) {
            formApi.updateSchema([{
              componentProps: {
               max:assetInfo.stock
              },
              fieldName: 'number',
            }])
          }
        },
      },
      async select(assetsId) {
        await upSelectAssets(assetsId);
        assetsId = ""
      },
      fieldName: 'assetId',
    },

  ]);
}


const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[550px]',
  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;

    if (isUpdate.value && id) {
      const record = await applicationInfo(id);
      await formApi.setValues(record);
    }
    await markInitialized();
    await setupPackageSelect();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const {valid} = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? applicationUpdate(data) : applicationAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm/>
  </BasicModal>
</template>

