<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,
  inspectionRouteList,
  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 pointList = ref<any[]>([]);
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);
      pointList.value = (record.inspectionRoutePointVoList || []).map(item => ({
        pointId: item.pointId ?? '',
        pointName: item.pointName ?? '',
      }));
      await tableApi.reload();
      console.log(pointList.value,111)
      await formApi.setValues(record);
    }
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    let data = {
      ...cloneDeep(await formApi.getValues()),
      inspectionRoutePointBoList:[pointData.value]
    }
    console.log(data,333)
    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 dayjs from 'dayjs';
import type { InspectionRouteForm } from '#/api/property/inspectionManagement/inspectionRoute/model';
import pointModal from './point-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: {},
  rowConfig: {
    keyField: 'id',
  },
  id: 'property-inspectionRoutePoint-index'
};

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

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

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

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

const pointData = ref({})
const handlePoint = (data) => {
  data.startTime = dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss')
  data.endTime = dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')
  pointData.value = data;
};
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
    <Page :auto-content-height="true" style="background-color: #F1F3F6">
      <BasicTable table-title="巡检点" :grid-options="gridOptions">
        <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"/>
    </Page>
  </BasicModal>
</template>

