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

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

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

import { useVbenForm } from '#/adapter/form';
import {
  getPlatformStoreOptionsApi,
  platformSalespersonCreateApi,
  salespersonCreateApi,
  salespersonUpdateApi,
  saveDrugCommissionApi,
} from '#/views/business/store/settings/api';
import SalespersonDrugCommissionEditor from '#/views/business/store/settings/components/SalespersonDrugCommissionEditor.vue';

import { salespersonModalFormProps } from '../config/form';

const isUpdate = ref(false);
const isPlatformMode = ref(false);
const splitType = ref(0);
const salespersonId = ref(0);
const storeId = ref<number | undefined>();
const storeOptions = ref<{ label: string; value: number }[]>([]);
const storeLoading = ref(false);
let storeSearchTimer: ReturnType<typeof setTimeout> | undefined;
const editorRef = ref<InstanceType<typeof SalespersonDrugCommissionEditor>>();

const isFixedAmount = computed(() => Number(splitType.value) === 0);
const modalClass = computed(() =>
  isFixedAmount.value ? 'w-[960px]' : 'w-[480px]',
);

watch(splitType, (val) => {
  if (Number(val) === 0) {
    nextTick(() => editorRef.value?.loadList());
  } else {
    editorRef.value?.resetDirty();
  }
});

const [Form, formApi] = useVbenForm({
  ...salespersonModalFormProps,
  handleValuesChange(values: Record<string, any>) {
    if (values.split_type !== undefined) {
      splitType.value = Number(values.split_type);
    }
  },
});

async function fetchStoreOptions(keyword = '') {
  storeLoading.value = true;
  try {
    const res = await getPlatformStoreOptionsApi({ keyword });
    storeOptions.value = (res ?? []).map((item) => ({
      label: item.position ? `${item.name}（${item.position}）` : item.name,
      value: item.id,
    }));
  } finally {
    storeLoading.value = false;
  }
}

function handleStoreSearch(keyword: string) {
  if (storeSearchTimer) {
    clearTimeout(storeSearchTimer);
  }
  storeSearchTimer = setTimeout(() => {
    fetchStoreOptions(keyword.trim());
  }, 300);
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;

    if (isPlatformMode.value && !isUpdate.value && !storeId.value) {
      message.warning('请选择诊所');
      return;
    }

    const values = await formApi.getValues();
    const payload = { ...values };
    if (Number(payload.split_type) === 0) {
      payload.split = 0;
    }
    if (isPlatformMode.value && !isUpdate.value) {
      payload.store_id = storeId.value;
    }

    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      const submitApi = isUpdate.value
        ? salespersonUpdateApi
        : isPlatformMode.value
          ? platformSalespersonCreateApi
          : salespersonCreateApi;
      const res = await submitApi(payload);
      const spId = isUpdate.value
        ? Number(payload.id)
        : Number(res?.id ?? res);

      if (!isUpdate.value && res?.admin_account_created === false) {
        message.warning(
          '推广员已创建，后台账号开通失败，请手动点击开通后台',
        );
      }

      if (Number(payload.split_type) === 0 && spId > 0) {
        const dirtyItems = editorRef.value?.getDirtyItems() ?? [];
        if (dirtyItems.length > 0) {
          await saveDrugCommissionApi({
            salesperson_id: spId,
            items: dirtyItems,
          });
        }
      }

      message.success('保存成功');
      modalApi.getData()?.getList?.();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      editorRef.value?.resetDirty();
      storeId.value = undefined;
      storeOptions.value = [];
      return;
    }
    const { values, update, mode } = modalApi.getData<Record<string, any>>() || {};
    isUpdate.value = !!update;
    isPlatformMode.value = mode === 'platform';
    if (values) {
      formApi.setValues(values);
      splitType.value = Number(values.split_type ?? 0);
      salespersonId.value = Number(values.id ?? 0);
    } else {
      formApi.resetForm();
      splitType.value = 0;
      salespersonId.value = 0;
    }
    if (isPlatformMode.value && !isUpdate.value) {
      fetchStoreOptions('');
    }
  },
});
</script>

<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}推广员`" :class="modalClass">
    <div v-if="isPlatformMode && !isUpdate" class="mb-4">
      <div class="mb-2 text-sm font-medium">所属诊所</div>
      <Select
        v-model:value="storeId"
        allow-clear
        class="w-full"
        :filter-option="false"
        :loading="storeLoading"
        :options="storeOptions"
        placeholder="搜索诊所名称/拼音首拼"
        show-search
        @search="handleStoreSearch"
      />
    </div>
    <Form />
    <p
      v-if="isFixedAmount && !isUpdate"
      class="mb-2 text-sm text-gray-500"
    >
      可先选择已有推广员复制药品分成，再微调后保存。
    </p>
    <SalespersonDrugCommissionEditor
      v-if="isFixedAmount"
      ref="editorRef"
      :salesperson-id="salespersonId"
      :exclude-salesperson-id="salespersonId"
      class="mt-4"
    />
  </Modal>
</template>
