<script setup lang="ts">
import type { MemberTierEditorForm } from '../types';

import { computed, ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Checkbox,
  Drawer,
  Input,
  InputNumber,
  Segmented,
  Spin,
  Switch,
  Tag,
} from 'ant-design-vue';

import {
  MEMBER_TIER_COLOR_OPTIONS,
  MEMBER_TIER_ICON_OPTIONS,
  MEMBER_TIER_RULE_OPTIONS,
} from '../composables/member-page/constants';
import {
  resolveTierIcon,
  resolveTierTagStyle,
} from '../composables/member-page/helpers';

interface Props {
  canManage: boolean;
  couponLabelMap: Record<string, string>;
  loading: boolean;
  model: MemberTierEditorForm | null;
  open: boolean;
  submitting: boolean;
  title: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'close'): void;
  (
    event: 'openCouponPicker',
    target: 'birthday' | 'monthly',
    selectedIds: string[],
  ): void;
  (event: 'submit', form: MemberTierEditorForm): void;
}>();

const localForm = ref<MemberTierEditorForm | null>(null);

const segmentedOptions = MEMBER_TIER_RULE_OPTIONS.map((item) => ({
  label: item.label,
  value: item.value,
}));

const canSubmit = computed(() => {
  if (!props.canManage || !localForm.value) {
    return false;
  }

  return localForm.value.name.trim().length > 0;
});

watch(
  () => [props.open, props.model],
  () => {
    if (!props.open || !props.model) {
      localForm.value = null;
      return;
    }

    localForm.value = structuredClone(props.model);
  },
  { immediate: true },
);

function removeCoupon(target: 'birthday' | 'monthly', couponId: string) {
  if (!localForm.value) {
    return;
  }

  if (target === 'birthday') {
    localForm.value.benefits.birthday.couponTemplateIds =
      localForm.value.benefits.birthday.couponTemplateIds.filter(
        (item) => item !== couponId,
      );
    return;
  }

  localForm.value.benefits.monthlyCoupon.couponTemplateIds =
    localForm.value.benefits.monthlyCoupon.couponTemplateIds.filter(
      (item) => item !== couponId,
    );
}

function openCouponPicker(target: 'birthday' | 'monthly') {
  if (!localForm.value) {
    return;
  }

  const selectedIds =
    target === 'birthday'
      ? localForm.value.benefits.birthday.couponTemplateIds
      : localForm.value.benefits.monthlyCoupon.couponTemplateIds;

  emit('openCouponPicker', target, selectedIds);
}

function handleSubmit() {
  if (!localForm.value || !canSubmit.value) {
    return;
  }

  emit('submit', structuredClone(localForm.value));
}

function resolveCouponLabel(couponId: string) {
  return props.couponLabelMap[couponId] || couponId;
}
</script>

<template>
  <Drawer
    :open="props.open"
    width="560"
    :title="props.title"
    @close="emit('close')"
  >
    <Spin :spinning="props.loading">
      <template v-if="localForm">
        <div class="mm-editor-form">
          <div class="mm-form-row">
            <div class="mm-form-label required">等级名称</div>
            <Input
              :value="localForm.name"
              :maxlength="64"
              :disabled="!props.canManage"
              placeholder="如：金卡会员"
              @update:value="(value) => (localForm!.name = String(value ?? ''))"
            />
          </div>

          <div class="mm-form-row">
            <div class="mm-form-label">等级图标</div>
            <div class="mm-icon-group">
              <button
                v-for="icon in MEMBER_TIER_ICON_OPTIONS"
                :key="icon.value"
                type="button"
                class="mm-icon-pill"
                :class="{ active: localForm.iconKey === icon.value }"
                :disabled="!props.canManage"
                @click="localForm.iconKey = icon.value"
              >
                <IconifyIcon :icon="resolveTierIcon(icon.value)" />
                <span>{{ icon.label }}</span>
              </button>
            </div>
          </div>

          <div class="mm-form-row">
            <div class="mm-form-label">等级颜色</div>
            <div class="mm-color-group">
              <button
                v-for="color in MEMBER_TIER_COLOR_OPTIONS"
                :key="color"
                type="button"
                class="mm-color-dot"
                :class="{ active: localForm.colorHex === color }"
                :style="{ backgroundColor: color }"
                :disabled="!props.canManage"
                @click="localForm.colorHex = color"
              ></button>
            </div>
          </div>

          <div class="mm-form-row">
            <div class="mm-form-label required">升级规则</div>
            <div class="mm-rule-panel">
              <Segmented
                :value="localForm.rule.upgradeRuleType"
                :options="segmentedOptions"
                :disabled="!props.canManage"
                @update:value="
                  (value) =>
                    (localForm!.rule.upgradeRuleType =
                      (value as MemberTierEditorForm['rule']['upgradeRuleType']) ||
                      'amount')
                "
              />

              <div
                v-if="
                  ['amount', 'both'].includes(localForm.rule.upgradeRuleType)
                "
                class="mm-rule-row"
              >
                <span>累计消费满</span>
                <InputNumber
                  :value="localForm.rule.upgradeAmountThreshold"
                  :min="0"
                  :precision="2"
                  :disabled="!props.canManage"
                  @update:value="
                    (value) =>
                      (localForm!.rule.upgradeAmountThreshold =
                        value === null ? undefined : Number(value))
                  "
                />
                <span>元</span>
              </div>

              <div
                v-if="
                  ['count', 'both'].includes(localForm.rule.upgradeRuleType)
                "
                class="mm-rule-row"
              >
                <span>消费满</span>
                <InputNumber
                  :value="localForm.rule.upgradeOrderCountThreshold"
                  :min="0"
                  :precision="0"
                  :disabled="!props.canManage"
                  @update:value="
                    (value) =>
                      (localForm!.rule.upgradeOrderCountThreshold =
                        value === null ? undefined : Number(value))
                  "
                />
                <span>次</span>
              </div>

              <div class="mm-rule-row">
                <span>降级观察期</span>
                <InputNumber
                  :value="localForm.rule.downgradeWindowDays"
                  :min="30"
                  :max="365"
                  :precision="0"
                  :disabled="!props.canManage"
                  @update:value="
                    (value) =>
                      (localForm!.rule.downgradeWindowDays = Number(
                        value || 90,
                      ))
                  "
                />
                <span>天</span>
              </div>
            </div>

            <div class="mm-rule-hint">
              达到条件自动升级；连续
              {{ localForm.rule.downgradeWindowDays }}
              天未达标自动降一级
            </div>
          </div>

          <div class="mm-form-row">
            <div class="mm-form-label">等级权益</div>

            <div class="mm-benefit-card">
              <div class="mm-benefit-head">
                <span>折扣权益</span>
                <Switch
                  :checked="localForm.benefits.discount.enabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) => (localForm!.benefits.discount.enabled = !!value)
                  "
                />
              </div>
              <div
                v-if="localForm.benefits.discount.enabled"
                class="mm-benefit-body"
              >
                <span>全场</span>
                <InputNumber
                  :value="localForm.benefits.discount.discountRate"
                  :min="0.1"
                  :max="10"
                  :step="0.1"
                  :precision="1"
                  :disabled="!props.canManage"
                  @update:value="
                    (value) =>
                      (localForm!.benefits.discount.discountRate =
                        value === null ? undefined : Number(value))
                  "
                />
                <span>折</span>
              </div>
            </div>

            <div class="mm-benefit-card">
              <div class="mm-benefit-head">
                <span>积分倍率</span>
                <Switch
                  :checked="localForm.benefits.pointMultiplier.enabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) =>
                      (localForm!.benefits.pointMultiplier.enabled = !!value)
                  "
                />
              </div>
              <div
                v-if="localForm.benefits.pointMultiplier.enabled"
                class="mm-benefit-body"
              >
                <span>消费积分</span>
                <InputNumber
                  :value="localForm.benefits.pointMultiplier.multiplier"
                  :min="0.1"
                  :max="10"
                  :step="0.1"
                  :precision="1"
                  :disabled="!props.canManage"
                  @update:value="
                    (value) =>
                      (localForm!.benefits.pointMultiplier.multiplier =
                        value === null ? undefined : Number(value))
                  "
                />
                <span>倍</span>
              </div>
            </div>

            <div class="mm-benefit-card">
              <div class="mm-benefit-head">
                <span>生日特权</span>
                <Switch
                  :checked="localForm.benefits.birthday.enabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) => (localForm!.benefits.birthday.enabled = !!value)
                  "
                />
              </div>
              <div
                v-if="localForm.benefits.birthday.enabled"
                class="mm-benefit-body col"
              >
                <Checkbox
                  :checked="localForm.benefits.birthday.doublePointsEnabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) =>
                      (localForm!.benefits.birthday.doublePointsEnabled =
                        !!value)
                  "
                >
                  生日双倍积分
                </Checkbox>

                <div class="mm-coupon-box">
                  <Tag
                    v-for="couponId in localForm.benefits.birthday
                      .couponTemplateIds"
                    :key="`birthday-${couponId}`"
                    :closable="props.canManage"
                    @close="removeCoupon('birthday', couponId)"
                  >
                    {{ resolveCouponLabel(couponId) }}
                  </Tag>
                  <Button
                    size="small"
                    type="link"
                    :disabled="!props.canManage"
                    @click="openCouponPicker('birthday')"
                  >
                    + 选券
                  </Button>
                </div>
              </div>
            </div>

            <div class="mm-benefit-card">
              <div class="mm-benefit-head">
                <span>每月赠券</span>
                <Switch
                  :checked="localForm.benefits.monthlyCoupon.enabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) =>
                      (localForm!.benefits.monthlyCoupon.enabled = !!value)
                  "
                />
              </div>
              <div
                v-if="localForm.benefits.monthlyCoupon.enabled"
                class="mm-benefit-body col"
              >
                <div class="mm-rule-row">
                  <span>每月</span>
                  <InputNumber
                    :value="localForm.benefits.monthlyCoupon.grantDay"
                    :min="1"
                    :max="28"
                    :precision="0"
                    :disabled="!props.canManage"
                    @update:value="
                      (value) =>
                        (localForm!.benefits.monthlyCoupon.grantDay = Number(
                          value || 1,
                        ))
                    "
                  />
                  <span>日自动发放</span>
                </div>

                <div class="mm-coupon-box">
                  <Tag
                    v-for="couponId in localForm.benefits.monthlyCoupon
                      .couponTemplateIds"
                    :key="`monthly-${couponId}`"
                    :closable="props.canManage"
                    @close="removeCoupon('monthly', couponId)"
                  >
                    {{ resolveCouponLabel(couponId) }}
                  </Tag>
                  <Button
                    size="small"
                    type="link"
                    :disabled="!props.canManage"
                    @click="openCouponPicker('monthly')"
                  >
                    + 选券
                  </Button>
                </div>
              </div>
            </div>

            <div class="mm-benefit-card">
              <div class="mm-benefit-head">
                <span>免配送费</span>
                <Switch
                  :checked="localForm.benefits.freeDelivery.enabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) =>
                      (localForm!.benefits.freeDelivery.enabled = !!value)
                  "
                />
              </div>
              <div
                v-if="localForm.benefits.freeDelivery.enabled"
                class="mm-benefit-body"
              >
                <span>每月免配送费</span>
                <InputNumber
                  :value="localForm.benefits.freeDelivery.monthlyFreeTimes"
                  :min="0"
                  :precision="0"
                  :disabled="!props.canManage"
                  @update:value="
                    (value) =>
                      (localForm!.benefits.freeDelivery.monthlyFreeTimes =
                        Number(value || 0))
                  "
                />
                <span>次</span>
              </div>
            </div>

            <div class="mm-benefit-inline">
              <div class="item">
                <span>优先配送</span>
                <Switch
                  :checked="localForm.benefits.priorityDeliveryEnabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) =>
                      (localForm!.benefits.priorityDeliveryEnabled = !!value)
                  "
                />
              </div>
              <div class="item">
                <span>专属客服</span>
                <Switch
                  :checked="localForm.benefits.exclusiveServiceEnabled"
                  :disabled="!props.canManage"
                  @update:checked="
                    (value) =>
                      (localForm!.benefits.exclusiveServiceEnabled = !!value)
                  "
                />
              </div>
            </div>
          </div>

          <div class="mm-form-row">
            <div class="mm-form-label">预览</div>
            <Tag :style="resolveTierTagStyle(localForm.colorHex)">
              <IconifyIcon :icon="resolveTierIcon(localForm.iconKey)" />
              {{ localForm.name || '等级名称' }}
            </Tag>
          </div>
        </div>
      </template>
    </Spin>

    <template #footer>
      <div class="mm-editor-footer">
        <Button @click="emit('close')">取消</Button>
        <Button
          type="primary"
          :disabled="!canSubmit"
          :loading="props.submitting"
          @click="handleSubmit"
        >
          保存
        </Button>
      </div>
    </template>
  </Drawer>
</template>
