import type { Ref } from 'vue';

import type {
  MemberMessageReachDetailDto,
  MemberMessageReachStatsDto,
} from '#/api/member/message-reach';
import type {
  MessageReachFilterForm,
  MessageReachPager,
  MessageTemplateFilterForm,
  MessageTemplatePager,
} from '#/views/member/message-reach/types';

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

import {
  estimateMemberMessageAudienceApi,
  getMemberMessageReachDetailApi,
  getMemberMessageReachListApi,
  getMemberMessageReachStatsApi,
  getMemberMessageTemplateListApi,
} from '#/api/member/message-reach';

import { mapMessageFilterToQuery, mapTemplateFilterToQuery } from './helpers';

interface CreateDataActionsOptions {
  audienceEstimateCount: Ref<number>;
  detail: Ref<MemberMessageReachDetailDto | null>;
  isDetailLoading: Ref<boolean>;
  isEstimatingAudience: Ref<boolean>;
  isMessageLoading: Ref<boolean>;
  isStatsLoading: Ref<boolean>;
  isTemplateLoading: Ref<boolean>;
  messageFilterForm: MessageReachFilterForm;
  messagePager: Ref<MessageReachPager>;
  stats: Ref<MemberMessageReachStatsDto>;
  templateFilterForm: MessageTemplateFilterForm;
  templatePager: Ref<MessageTemplatePager>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  function resetMessagePager() {
    options.messagePager.value = {
      ...options.messagePager.value,
      items: [],
      totalCount: 0,
    };
  }

  function resetTemplatePager() {
    options.templatePager.value = {
      ...options.templatePager.value,
      items: [],
      totalCount: 0,
    };
  }

  async function loadStats() {
    options.isStatsLoading.value = true;
    try {
      options.stats.value = await getMemberMessageReachStatsApi();
    } catch (error) {
      console.error(error);
      message.error('加载消息统计失败');
    } finally {
      options.isStatsLoading.value = false;
    }
  }

  async function loadMessageList() {
    options.isMessageLoading.value = true;
    try {
      const query = mapMessageFilterToQuery(options.messageFilterForm);
      const result = await getMemberMessageReachListApi({
        page: options.messagePager.value.page,
        pageSize: options.messagePager.value.pageSize,
        ...query,
      });
      options.messagePager.value = {
        items: result.items ?? [],
        page: result.page,
        pageSize: result.pageSize,
        totalCount: result.totalCount,
      };
    } catch (error) {
      console.error(error);
      resetMessagePager();
      message.error('加载消息列表失败');
    } finally {
      options.isMessageLoading.value = false;
    }
  }

  async function loadTemplateList() {
    options.isTemplateLoading.value = true;
    try {
      const query = mapTemplateFilterToQuery(options.templateFilterForm);
      const result = await getMemberMessageTemplateListApi({
        page: options.templatePager.value.page,
        pageSize: options.templatePager.value.pageSize,
        ...query,
      });
      options.templatePager.value = {
        items: result.items ?? [],
        page: result.page,
        pageSize: result.pageSize,
        totalCount: result.totalCount,
      };
    } catch (error) {
      console.error(error);
      resetTemplatePager();
      message.error('加载模板列表失败');
    } finally {
      options.isTemplateLoading.value = false;
    }
  }

  async function loadMessageDetail(messageId: string) {
    options.isDetailLoading.value = true;
    try {
      const result = await getMemberMessageReachDetailApi({ messageId });
      options.detail.value = result;
      return result;
    } catch (error) {
      console.error(error);
      options.detail.value = null;
      message.error('加载消息详情失败');
      return null;
    } finally {
      options.isDetailLoading.value = false;
    }
  }

  async function estimateAudience(audienceType: 'all' | 'tag', tags: string[]) {
    options.isEstimatingAudience.value = true;
    try {
      const result = await estimateMemberMessageAudienceApi({
        audienceType,
        tags,
      });
      options.audienceEstimateCount.value = result.reachCount ?? 0;
      return options.audienceEstimateCount.value;
    } catch (error) {
      console.error(error);
      options.audienceEstimateCount.value = 0;
      message.error('估算触达人数失败');
      return 0;
    } finally {
      options.isEstimatingAudience.value = false;
    }
  }

  return {
    estimateAudience,
    loadMessageDetail,
    loadMessageList,
    loadStats,
    loadTemplateList,
  };
}
