<script lang="ts" setup>
/**
 * 门店仓库药品编辑弹窗
 * 绑定配送仓不可改价；有底价/最高价时提示改价区间
 */
import { computed, ref } from 'vue';

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

import { Alert, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

import {
  createWarehouseDrugManagementStore,
  updateWarehouseDrugManagementStore,
} from '../api';
import { modalFormProps } from '../config/form';
import { getDrugUseList } from '#/views/doctor/doctor-reception/api';

const drugTime = ref([]);
const drugType = ref([]);
const drugUnit = ref([]);
const drugFrequency = ref([]);
getDrugUseList().then((res) => {
  drugTime.value = res.drug_time.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  drugType.value = res.drug_use_type.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  drugUnit.value = res.drug_unit.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  drugFrequency.value = res.drug_use_frequency.map((item) => {
    return {
      label: item.name,
      value: item.id,
    };
  });
  return res;
});

const isUpdate = ref(false);
const gridApi = ref();
/** 是否绑定配送仓（不可改价） */
const priceLocked = ref(false);
/** 改价区间展示文案 */
const priceRangeTip = ref('');

const [Form, formApi] = useVbenForm(modalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (priceLocked.value) {
      message.warning('该商品不可改价');
      return;
    }
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value
          ? updateWarehouseDrugManagementStore
          : createWarehouseDrugManagementStore;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      formApi.updateSchema([
        {
          componentProps: {
            options: drugTime.value,
          },
          fieldName: 'time_id',
        },
        {
          componentProps: {
            options: drugUnit.value,
          },
          fieldName: 'unit_id',
        },
        {
          componentProps: {
            options: drugType.value,
          },
          fieldName: 'type_id',
        },
        {
          componentProps: {
            options: drugFrequency.value,
          },
          fieldName: 'frequency_id',
        },
      ]);
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values) {
        isUpdate.value = update;
        // 从列表行带入配送仓标记与价格区间（drug 嵌套字段展平到表单）
        const hasDelivery =
          Number(values.has_delivery_warehouse) === 1 ||
          Number(values.drug?.has_delivery_warehouse) === 1;
        priceLocked.value = hasDelivery;
        const min = Number(
          values.min_adjust_price ?? values.drug?.min_adjust_price ?? 0,
        );
        const max = Number(
          values.max_adjust_price ?? values.drug?.max_adjust_price ?? 0,
        );
        if (min > 0 || max > 0) {
          const minTxt = min > 0 ? `￥${min.toFixed(2)}` : '不限';
          const maxTxt = max > 0 ? `￥${max.toFixed(2)}` : '不限';
          priceRangeTip.value = `改价区间：${minTxt} ~ ${maxTxt}`;
        } else {
          priceRangeTip.value = '';
        }
        formApi.setValues({
          ...values,
          has_delivery_warehouse: hasDelivery ? 1 : 0,
          min_adjust_price: min || null,
          max_adjust_price: max || null,
        });
      }
    } else {
      priceLocked.value = false;
      priceRangeTip.value = '';
    }
  },
});

const modalTitle = computed(() =>
  isUpdate.value === true ? '编辑仓库药品' : '新增仓库药品',
);
</script>
<template>
  <Modal :title="modalTitle" class="w-[80%] md:w-[50%] lg:w-[30%] h-[60%]">
    <Alert
      v-if="priceLocked"
      type="warning"
      show-icon
      class="mb-3"
      message="该商品不可改价"
      description="已绑定配送仓库，商家侧不允许修改售价。"
    />
    <Alert
      v-else-if="priceRangeTip"
      type="info"
      show-icon
      class="mb-3"
      :message="priceRangeTip"
      description="售价必须落在平台设置的底价～最高价区间内。"
    />
    <Form />
  </Modal>
</template>
