<script lang="ts" setup>
/**
 * 绑定门店可开方药品种类与默认种类
 * 为什么独立弹窗：诊所/药店列表共用，整表替换中间表绑定
 */
import { computed, ref } from 'vue';

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

import { Checkbox, CheckboxGroup, Form, FormItem, message, Radio, RadioGroup } from 'ant-design-vue';

import { bindPrescriptionTypesApi } from '../api';
import {
  STORE_PRESCRIPTION_TYPE_OPTIONS,
} from '../config/prescription-type-constants';

const formState = ref({
  id: undefined as number | undefined,
  allowed_prescription_types: [] as number[],
  default_prescription_type: undefined as number | undefined,
});

const gridApiRef = ref<any>(null);
const loading = ref(false);

/** 默认种类只能从已勾选里选 */
const defaultOptions = computed(() =>
  STORE_PRESCRIPTION_TYPE_OPTIONS.filter((o) =>
    formState.value.allowed_prescription_types.includes(o.value),
  ),
);

function onAllowedChange(values: number[]) {
  const next = (values || []) as number[];
  formState.value.allowed_prescription_types = next;
  // 默认种类若不在已选中，自动落到第一项
  if (
    formState.value.default_prescription_type &&
    !next.includes(formState.value.default_prescription_type)
  ) {
    formState.value.default_prescription_type = next[0];
  }
  if (!formState.value.default_prescription_type && next.length) {
    formState.value.default_prescription_type = next[0];
  }
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (!formState.value.id) {
      message.error('门店ID无效');
      return;
    }
    if (!formState.value.allowed_prescription_types.length) {
      message.error('请至少选择一种可开方种类');
      return;
    }
    if (
      !formState.value.default_prescription_type ||
      !formState.value.allowed_prescription_types.includes(
        formState.value.default_prescription_type,
      )
    ) {
      message.error('请选择默认开方种类');
      return;
    }
    loading.value = true;
    modalApi.setState({ confirmLoading: true });
    try {
      await bindPrescriptionTypesApi({
        id: formState.value.id,
        allowed_prescription_types: formState.value.allowed_prescription_types,
        default_prescription_type: formState.value.default_prescription_type,
      });
      message.success('绑定成功');
      gridApiRef.value?.reload();
      modalApi.close();
    } catch (error) {
      console.error(error);
      message.error('绑定失败');
    } finally {
      loading.value = false;
      modalApi.setState({ confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const { values, gridApi } = modalApi.getData<Record<string, any>>();
    gridApiRef.value = gridApi;
    const allowed = Array.isArray(values?.allowed_prescription_types)
      ? values.allowed_prescription_types.map((n: any) => Number(n))
      : [];
    let def = Number(values?.default_prescription_type) || 0;
    if (def && !allowed.includes(def)) {
      def = allowed[0] || 0;
    }
    formState.value = {
      id: values?.id,
      allowed_prescription_types: allowed,
      default_prescription_type: def || undefined,
    };
  },
});
</script>

<template>
  <Modal title="绑定开方种类" class="w-[520px]">
    <Form :model="formState" layout="vertical">
      <FormItem label="可开方种类" required>
        <CheckboxGroup
          v-model:value="formState.allowed_prescription_types"
          @change="onAllowedChange"
        >
          <div class="flex flex-wrap gap-2">
            <Checkbox
              v-for="opt in STORE_PRESCRIPTION_TYPE_OPTIONS"
              :key="opt.value"
              :value="opt.value"
            >
              {{ opt.label }}
            </Checkbox>
          </div>
        </CheckboxGroup>
      </FormItem>
      <FormItem label="进入开方页默认种类" required>
        <RadioGroup
          v-model:value="formState.default_prescription_type"
          :disabled="!defaultOptions.length"
        >
          <div class="flex flex-wrap gap-2">
            <Radio
              v-for="opt in defaultOptions"
              :key="opt.value"
              :value="opt.value"
            >
              {{ opt.label }}
            </Radio>
          </div>
        </RadioGroup>
        <div v-if="!defaultOptions.length" class="mt-1 text-gray-400 text-sm">
          请先勾选可开方种类
        </div>
      </FormItem>
    </Form>
  </Modal>
</template>
