<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 { useVbenForm } from '#/adapter/form';
import { inspectionRouteAdd, inspectionRouteInfo, inspectionRouteUpdate } from '#/api/property/inspectionManagement/inspectionRoute';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import {
  inspectionPointList,
} from '#/api/property/inspectionManagement/inspectionPoint';
import {modalSchema} from './data';

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-1',
    labelWidth: 100,
    componentProps: {
      class: 'w-full',
    }
  },
  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-[60%]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    await queryWorkOrdersType()
    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await inspectionRouteInfo(id);
      await formApi.setValues(record);
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? inspectionRouteUpdate(data) : inspectionRouteAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

async function queryWorkOrdersType() {
  let params = {
    pageSize: 1000,
    pageNum: 1
  }
  const res = await inspectionPointList(params)
  const options = res.rows.map((item) => ({
    label: item.pointName,
    value: item.id,
  }));
  tableApi.formApi.updateSchema([{
    componentProps: () => ({
      options: options,
      showSearch: true,
      filterOption: filterOption,
    }),
    fieldName: 'pointId',
  }])
}

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};


//!!!!!!
import { Page, type VbenFormProps } from '@vben/common-ui';
import { Space } from 'ant-design-vue';
import {
  useVbenVxeGrid,
  type VxeGridProps
} from '#/adapter/vxe-table';
import {
  inspectionRouteList,
} from '#/api/property/inspectionManagement/inspectionRoute';
import type { InspectionRouteForm } from '#/api/property/inspectionManagement/inspectionRoute/model';
import pointModal from './point-modal.vue';
import pointModalSetting from './pointSetting-modal.vue';
import { columnsPoint, querySchemaPoint } from './data';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 90,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchemaPoint(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
  },
  columns: columnsPoint,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await inspectionRouteList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'property-inspectionRoute-index'
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [PointModal, pointModalApi] = useVbenModal({
  connectedComponent: pointModal,
});

const [PointModalSetting, pointModalSettingApi] = useVbenModal({
  connectedComponent: pointModalSetting,
});

function handleAdd() {
  pointModalApi.setData({});
  pointModalApi.open();
}

async function handleEdit(row: Required<InspectionRouteForm>) {
  pointModalSettingApi.setData({ id: row.id });
  pointModalSettingApi.open();
}

const setData = ref({})
const handleSet = (data) => {
  setData.value = data; // 更新父组件的数据源
  console.log(setData.value,111);
};
const pointData = ref({})
const handlePoint = (data) => {
  pointData.value = data; // 更新父组件的数据源
  console.log(pointData.value,222);
};
// const allDate = {
//   ...pointData,
//   ...setData
// }
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
    <Page :auto-content-height="true" style="background-color: #F1F3F6">
      <BasicTable table-title="巡检点">
        <template #toolbar-tools>
          <Space>
            <a-button
              type="primary"
              @click="handleAdd"
            >
              {{ $t('pages.common.add') }}
            </a-button>
          </Space>
        </template>
        <template #action="{ row }">
          <Space>
            <ghost-button
              @click.stop="handleEdit(row)"
            >
              {{ '巡检点' }}
            </ghost-button>
          </Space>
        </template>
      </BasicTable>
      <PointModal @reload="tableApi.query()"  @update-data="handlePoint"/>
      <PointModalSetting @reload="tableApi.query()" @update-data="handleSet"/>
    </Page>
  </BasicModal>
</template>

