<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 { updateProcess } from '#/views/system/process/api';

import type { ProcessNoteRow, ProcessRuleRow } from '../constants';

type MoveTarget =
  | { kind: 'method'; row: ProcessRuleRow }
  | { kind: 'note'; row: ProcessNoteRow };

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

const isNote = computed(() => moveTarget.value?.kind === 'note');

const options = computed(() => {
  if (!moveTarget.value) {
    return [];
  }
  if (moveTarget.value.kind === 'method') {
    return level1List.value.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }
  return allMethods.value.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 {
      if (moveTarget.value.kind === 'method') {
        await updateProcess({
          id: moveTarget.value.row.id,
          node_type: 'rule',
          pid: targetId.value,
        });
      } else {
        const row = moveTarget.value.row;
        await updateProcess({
          id: row.id,
          node_type: 'note',
          real_id: row.real_id,
          rule_id: targetId.value,
          note: row.note ?? row.name,
        });
      }
      message.success('移动成功');
      onSuccess.value?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{
        allMethods: ProcessRuleRow[];
        level1List: ProcessRuleRow[];
        onSuccess?: () => void;
        target: MoveTarget;
      }>();
      moveTarget.value = data?.target ?? null;
      level1List.value = data?.level1List ?? [];
      allMethods.value = data?.allMethods ?? [];
      onSuccess.value = data?.onSuccess ?? null;
      if (moveTarget.value?.kind === 'method') {
        targetId.value = moveTarget.value.row.pid || undefined;
      } else if (moveTarget.value?.kind === 'note') {
        targetId.value = moveTarget.value.row.rule_id ?? moveTarget.value.row.pid;
      }
    } else {
      moveTarget.value = null;
      targetId.value = undefined;
      onSuccess.value = null;
    }
  },
});
</script>

<template>
  <Modal
    :title="isNote ? '移动备注到煎法' : '移动煎法到制剂'"
    class="w-[400px]"
  >
    <Form layout="vertical">
      <FormItem :label="isNote ? '目标煎法' : '目标制剂'" 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>
