<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="900"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :confirm-loading="loading"
    :title="isUpdate ? '规则设置' : '添加水票'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 5, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600">基本信息</span>
      </a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="关联商品" name="goodsId">
            <a-select
              v-model:value="form.goodsId"
              placeholder="请选择关联商品"
              show-search
              :filter-option="false"
              :loading="goodsLoading"
              @search="searchGoods"
              @change="onGoodsChange"
              @dropdown-visible-change="onDropdownVisibleChange"
            >
              <a-select-option
                v-for="goods in goodsList"
                :key="goods.goodsId"
                :value="goods.goodsId"
              >
                <div class="goods-option">
                  <span>{{ goods.name }}</span>
                  <a-tag color="blue" style="margin-left: 8px"
                    >¥{{ goods.price || 0 }}</a-tag
                  >
                </div>
              </a-select-option>
              <a-select-option v-if="goodsList.length === 0" disabled>
                <div style="text-align: center; color: #999">
                  {{ goodsLoading ? '加载中...' : '暂无商品数据' }}
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="水票名称" name="name">
            <a-input
              allow-clear
              :maxlength="50"
              placeholder="请输入水票名称"
              v-model:value="form.name"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="启用" name="enabled">
            <a-switch
              v-model:checked="form.enabled"
              checked-children="启用"
              un-checked-children="停用"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="单位名称" name="unitName">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="如：桶/张/次"
              v-model:value="form.unitName"
            />
          </a-form-item>
        </a-col>

        <a-col :span="24" v-if="selectedGoods">
          <a-form-item label="已选商品">
            <a-space>
              <span>{{ selectedGoods.name }}</span>
              <a-tag color="blue">¥{{ selectedGoods.price || 0 }}</a-tag>
              <a-tag v-if="selectedGoods.goodsId" color="default"
                >ID: {{ selectedGoods.goodsId }}</a-tag
              >
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider orientation="left">
        <span style="color: #1890ff; font-weight: 600">发放规则</span>
      </a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="最小购买数量" name="minBuyQty">
            <a-input-number
              :min="1"
              :max="999999"
              class="ele-fluid"
              placeholder="请输入最小购买数量"
              v-model:value="form.minBuyQty"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="起始发送数量" name="startSendQty">
            <a-input-number
              :min="0"
              :max="999999"
              class="ele-fluid"
              placeholder="支付成功后起始发放数量"
              v-model:value="form.startSendQty"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="买赠倍率" name="giftMultiplier">
            <a-input-number
              :min="0"
              :max="999999"
              class="ele-fluid"
              placeholder="买1送4 => 4"
              v-model:value="form.giftMultiplier"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="计入购买量" name="includeBuyQty">
            <a-switch
              v-model:checked="form.includeBuyQty"
              checked-children="是"
              un-checked-children="否"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="每期释放数量" name="monthlyReleaseQty">
            <a-input-number
              :min="0"
              :max="999999"
              class="ele-fluid"
              placeholder="默认每月释放10"
              v-model:value="form.monthlyReleaseQty"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="释放期数" name="releasePeriods">
            <a-input-number
              :min="0"
              :max="999999"
              class="ele-fluid"
              placeholder=">0则按期数平均分摊"
              v-model:value="form.releasePeriods"
            />
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="首期释放时机" name="firstReleaseMode">
            <a-radio-group v-model:value="form.firstReleaseMode">
              <a-radio :value="0">支付成功当刻</a-radio>
              <a-radio :value="1">下个月同日</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item label="排序" name="sortNumber">
            <a-input-number
              :min="0"
              :max="9999"
              class="ele-fluid"
              placeholder="数字越小越靠前"
              v-model:value="form.sortNumber"
            />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="备注" name="comments">
            <a-textarea
              :rows="4"
              :maxlength="200"
              placeholder="请输入备注"
              v-model:value="form.comments"
              show-count
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import {
    addGltTicketTemplate,
    updateGltTicketTemplate
  } from '@/api/glt/gltTicketTemplate';
  import type { GltTicketTemplate } from '@/api/glt/gltTicketTemplate/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { listShopGoods, getShopGoods } from '@/api/shop/shopGoods';
  import type { ShopGoods } from '@/api/shop/shopGoods/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: GltTicketTemplate | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  const formRef = ref<FormInstance | null>(null);

	  const defaultForm: GltTicketTemplate = {
	    id: undefined,
	    goodsId: undefined,
	    name: '',
	    enabled: true,
	    unitName: '',
	    minBuyQty: 1,
	    startSendQty: 0,
	    giftMultiplier: 0,
	    includeBuyQty: false,
	    monthlyReleaseQty: 10,
	    releasePeriods: 0,
	    firstReleaseMode: 0,
    userId: undefined,
    sortNumber: 100,
    comments: '',
    status: 0,
    deleted: 0,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined
  };

  // 表单数据
  const form = reactive<GltTicketTemplate>({ ...defaultForm });

  // 商品列表/选中商品（参考 shopGiftEdit.vue 的关联商品功能）
  const goodsList = ref<ShopGoods[]>([]);
  const goodsLoading = ref(false);
  const selectedGoods = ref<ShopGoods | null>(null);

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    goodsId: [{ required: true, message: '请选择关联商品', trigger: 'change' }],
    name: [
      { required: true, message: '请输入水票名称', trigger: 'blur' },
      { min: 2, max: 50, message: '名称长度应在2-50个字符之间', trigger: 'blur' }
    ]
  });

	  const { resetFields } = useForm(form, rules);

	  const normalizeBoolean = (v: any, fallback = false): boolean => {
	    if (v === true || v === false) return v;
	    // Spring/Jackson Boolean only accepts true/false; never send "1"/"0".
	    if (v === 1 || v === '1' || v === 'true') return true;
	    if (v === 0 || v === '0' || v === 'false') return false;
	    return fallback;
	  };

	  const normalizeNumber = (v: any): number | undefined => {
	    if (v === undefined || v === null || v === '') return undefined;
	    const n = Number(v);
	    return Number.isFinite(n) ? n : undefined;
	  };

	  const normalizeFormTypes = () => {
	    form.goodsId = normalizeNumber(form.goodsId);
	    form.enabled = normalizeBoolean(form.enabled, true);
	    form.includeBuyQty = normalizeBoolean(form.includeBuyQty, false);
	    form.minBuyQty = normalizeNumber(form.minBuyQty) ?? 1;
	    form.startSendQty = normalizeNumber(form.startSendQty) ?? 0;
	    form.giftMultiplier = normalizeNumber(form.giftMultiplier) ?? 0;
	    form.monthlyReleaseQty = normalizeNumber(form.monthlyReleaseQty) ?? 10;
	    form.releasePeriods = normalizeNumber(form.releasePeriods) ?? 0;
	    form.firstReleaseMode = normalizeNumber(form.firstReleaseMode) ?? 0;
	    form.sortNumber = normalizeNumber(form.sortNumber) ?? 100;
	  };

  const ensureSelectedGoodsLoaded = async (goodsId?: number) => {
    if (!goodsId) {
      selectedGoods.value = null;
      return;
    }
    const hit = goodsList.value.find((g) => g.goodsId === goodsId);
    if (hit) {
      selectedGoods.value = hit;
      return;
    }
    try {
      const goods = await getShopGoods(goodsId);
      if (goods) {
        goodsList.value = [goods, ...goodsList.value];
        selectedGoods.value = goods;
      }
    } catch {
      selectedGoods.value = null;
    }
  };

  const getGoodsList = async () => {
    if (goodsLoading.value) return;
    goodsLoading.value = true;
    try {
      const res = await listShopGoods({ limit: 50 });
      goodsList.value = res || [];
    } catch {
      goodsList.value = [];
    } finally {
      goodsLoading.value = false;
    }
  };

  /* 搜索商品 */
  const searchGoods = async (value: string) => {
    const keywords = value?.trim();
    if (!keywords) return;

    goodsLoading.value = true;
    try {
      const res = await listShopGoods({ keywords, limit: 50 });
      goodsList.value = res || [];
    } catch {
      goodsList.value = [];
    } finally {
      goodsLoading.value = false;
    }
  };

  /* 下拉框显示状态改变 */
  const onDropdownVisibleChange = (open: boolean) => {
    if (open && goodsList.value.length === 0) {
      getGoodsList();
    }
  };

  /* 商品选择改变 */
  const onGoodsChange = (goodsId: number) => {
    const hit = goodsList.value.find((g) => g.goodsId === goodsId) || null;
    selectedGoods.value = hit;
    if (!hit) {
      ensureSelectedGoodsLoaded(goodsId);
    }
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) return;

    formRef.value
      .validate()
      .then(() => {
        normalizeFormTypes();
        loading.value = true;
        const formData: GltTicketTemplate = { ...form };
        const saveOrUpdate = isUpdate.value
          ? updateGltTicketTemplate
          : addGltTicketTemplate;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    async (visible) => {
      if (visible) {
        await getGoodsList();
        if (props.data) {
          assignObject(form, props.data);
          normalizeFormTypes();
          await ensureSelectedGoodsLoaded(form.goodsId);
          isUpdate.value = true;
        } else {
          Object.assign(form, { ...defaultForm });
          selectedGoods.value = null;
          isUpdate.value = false;
        }
      } else {
        resetFields();
        selectedGoods.value = null;
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
  .goods-option {
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      color: #666;
      font-size: 12px;
    }
  }
</style>
