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

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

import { Alert, Form, FormItem, Input, message, Select, Spin } from 'ant-design-vue';

import {
  getSelectableBankCards,
  getStoreBankCardReportDetail,
} from '../api';
import {
  LABEL_UPDATE_STORE_BANK_CARD,
  STORE_BANK_ACCOUNT_TYPE_OPTIONS,
} from '../config/constants';
import {
  buildCurrentStoreReportOption,
  mapReportPayloadToStoreBankForm,
  mergeSelectableBankCardOptions,
  type BankCardSelectableOption,
} from '../utils/bankCardImport';
import { getStoreInfo, updateStoreBankInfoApi } from '#/views/system/store/api';

const storeId = ref(0);
const storeName = ref('');
const loading = ref(false);
const saving = ref(false);
const gridApiRef = ref<any>(null);
const selectableOptions = ref<BankCardSelectableOption[]>([]);
const selectedCardKey = ref<string | undefined>();
const importedFromReport = ref(false);

const formState = ref({
  bank_user_name: '',
  bank_card: '',
  bank_name: '',
  bank_account_type: 2,
  bank_no: '',
});

const modalTitle = computed(() =>
  storeName.value
    ? `${LABEL_UPDATE_STORE_BANK_CARD} - ${storeName.value}`
    : LABEL_UPDATE_STORE_BANK_CARD,
);

/** 下拉搜索过滤 */
function filterSelectableOption(input: string, option: { label?: string }) {
  return (option?.label ?? '').toLowerCase().includes(input.toLowerCase());
}

/** 加载可导入的已报备银行卡列表 */
async function loadSelectableCards() {
  if (!storeId.value) {
    selectableOptions.value = [];
    return;
  }
  try {
    const [selectableRes, detailRes] = await Promise.all([
      getSelectableBankCards(storeId.value),
      getStoreBankCardReportDetail(storeId.value).catch(() => null),
    ]);
    const currentOption = buildCurrentStoreReportOption(detailRes);
    selectableOptions.value = mergeSelectableBankCardOptions(
      currentOption,
      selectableRes?.options ?? [],
    );
  } catch {
    selectableOptions.value = [];
  }
}

/** 加载门店当前银行卡信息 */
async function loadStoreBankInfo() {
  if (!storeId.value) return;
  loading.value = true;
  try {
    const info = await getStoreInfo(storeId.value);
    formState.value = {
      bank_user_name: info?.bank_user_name ?? '',
      bank_card: info?.bank_card ?? '',
      bank_name: info?.bank_name ?? '',
      bank_account_type: Number(info?.bank_account_type ?? 2) || 2,
      bank_no: info?.bank_no ?? '',
    };
  } catch {
    message.error('加载门店银行卡信息失败');
  } finally {
    loading.value = false;
  }
}

/** 选择已报备记录后填充表单 */
function handleSelectExistingCard(value: string | undefined) {
  if (!value) {
    importedFromReport.value = false;
    return;
  }
  const option = selectableOptions.value.find((item) => item.value === value);
  if (!option) {
    importedFromReport.value = false;
    return;
  }
  formState.value = mapReportPayloadToStoreBankForm(option.payload);
  importedFromReport.value = true;
}

function resetImportState() {
  selectedCardKey.value = undefined;
  selectableOptions.value = [];
  importedFromReport.value = false;
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (!storeId.value) return;
    saving.value = true;
    try {
      await updateStoreBankInfoApi({
        id: storeId.value,
        ...formState.value,
      });
      message.success('门店银行卡信息已保存');
      gridApiRef.value?.query?.();
      gridApiRef.value?.reload?.();
      modalApi.close();
    } finally {
      saving.value = false;
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{
        storeId: number;
        storeName?: string;
        gridApi?: any;
      }>();
      storeId.value = data?.storeId ?? 0;
      storeName.value = data?.storeName ?? '';
      gridApiRef.value = data?.gridApi ?? null;
      resetImportState();
      loadStoreBankInfo();
      loadSelectableCards();
      return;
    }
    storeId.value = 0;
    storeName.value = '';
    gridApiRef.value = null;
    resetImportState();
    formState.value = {
      bank_user_name: '',
      bank_card: '',
      bank_name: '',
      bank_account_type: 2,
      bank_no: '',
    };
  },
});
</script>

<template>
  <Modal :title="modalTitle" class="w-[520px]" :confirm-loading="saving">
    <Alert
      type="info"
      show-icon
      class="mb-4"
      message="仅修改系统门店银行卡信息，不会提交易票联报备。"
    />
    <div v-if="selectableOptions.length > 0" class="mb-4">
      <div class="mb-2 text-sm text-gray-600 dark:text-gray-400">
        从已报备银行卡导入
      </div>
      <Select
        v-model:value="selectedCardKey"
        allow-clear
        show-search
        class="w-full"
        :filter-option="filterSelectableOption"
        :options="selectableOptions"
        placeholder="选择历史报备记录（可跨门店）"
        @change="handleSelectExistingCard"
      />
    </div>
    <Alert
      v-if="importedFromReport"
      type="success"
      show-icon
      class="mb-4"
      message="已从报备记录导入卡信息，确认后仅写入系统门店，不会提交易票联报备。"
    />
    <Spin :spinning="loading">
      <Form layout="vertical">
        <FormItem label="开户人姓名" required>
          <Input
            v-model:value="formState.bank_user_name"
            placeholder="请输入开户人姓名"
          />
        </FormItem>
        <FormItem label="银行卡号" required>
          <Input v-model:value="formState.bank_card" placeholder="请输入银行卡号" />
        </FormItem>
        <FormItem label="开户银行名称" required>
          <Input v-model:value="formState.bank_name" placeholder="请输入开户银行名称" />
        </FormItem>
        <FormItem label="银行账户类型" required>
          <Select
            v-model:value="formState.bank_account_type"
            :options="STORE_BANK_ACCOUNT_TYPE_OPTIONS"
            placeholder="请选择银行账户类型"
          />
        </FormItem>
        <FormItem label="银行联行号">
          <Input
            v-model:value="formState.bank_no"
            placeholder="对公/存折或非62开头卡号时必填"
          />
        </FormItem>
      </Form>
    </Spin>
  </Modal>
</template>
