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

import { useVbenModal } from '@vben/common-ui';

import { Form, FormItem, Select, message } from 'ant-design-vue';

import { updateRegion } from '#/views/system/region/api';

import type { RegionRow } from '../constants';

const moveTarget = ref<RegionRow | null>(null);
const targetId = ref<number | undefined>(undefined);
const level1List = ref<RegionRow[]>([]);
const onSuccess = ref<(() => void) | null>(null);

const options = computed(() =>
  level1List.value
    .filter((item) => item.id !== moveTarget.value?.pid)
    .map((item) => ({
      label: item.name,
      value: item.id,
    })),
);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (!moveTarget.value || !targetId.value) {
      message.error('请选择目标地区');
      return;
    }
    modalApi.setState({ confirmLoading: true });
    try {
      await updateRegion({
        id: moveTarget.value.id,
        pid: targetId.value,
      });
      message.success('移动成功');
      onSuccess.value?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{
        level1List: RegionRow[];
        onSuccess?: () => void;
        target: RegionRow;
      }>();
      moveTarget.value = data?.target ?? null;
      level1List.value = data?.level1List ?? [];
      onSuccess.value = data?.onSuccess ?? null;
      targetId.value = moveTarget.value?.pid || undefined;
    } else {
      moveTarget.value = null;
      targetId.value = undefined;
      onSuccess.value = null;
    }
  },
});
</script>

<template>
  <Modal title="移动子地区到地区" class="w-[400px]">
    <Form layout="vertical">
      <FormItem label="目标地区" required>
        <Select
          v-model:value="targetId"
          :options="options"
          placeholder="请选择"
          show-search
          :filter-option="
            (input: string, option: any) =>
              option?.label?.toLowerCase().includes(input.toLowerCase())
          "
        />
      </FormItem>
    </Form>
  </Modal>
</template>
