<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑会员卡' : '添加会员卡'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <!--      <a-form-item label="选择场馆" name="merchantName">-->
      <!--        <SelectMerchant-->
      <!--          :placeholder="`选择场馆`"-->
      <!--          class="input-item"-->
      <!--          v-model:value="form.merchantName"-->
      <!--          @done="chooseMerchantId"-->
      <!--        />-->
      <!--      </a-form-item>-->
      <a-form-item label="适用场馆" name="merchants">
        <MerchantSelect v-model:value="merchants" />
      </a-form-item>
      <a-form-item label="会员卡名称" name="cardName">
        <a-input
          allow-clear
          placeholder="请输入会员卡名称"
          v-model:value="form.cardName"
        />
      </a-form-item>
      <a-form-item label="会员卡类型" name="type">
        <a-select
          v-model:value="form.type"
          placeholder="会员卡类型"
          :style="`width: 200px`"
        >
          <a-select-option :value="1">年卡</a-select-option>
          <a-select-option :value="2">次卡</a-select-option>
          <a-select-option :value="3">月卡</a-select-option>
          <a-select-option :value="4">会员IC卡</a-select-option>
          <a-select-option :value="5">充值卡</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="会员卡分组" name="cardCode">
        <DictSelect
          dict-code="cardPlanId"
          :placeholder="`会员卡分组`"
          style="width: 200px"
          v-model:value="form.cardCode"
        />
      </a-form-item>
      <a-form-item label="价格" name="price">
        <a-input-number
          allow-clear
          placeholder="请输入价格"
          style="width: 200px"
          v-model:value="form.price"
        />
      </a-form-item>
      <a-form-item label="次数" name="number" v-if="form.cardCode == '次卡'">
        <a-input-number
          allow-clear
          placeholder="请输入次数"
          style="width: 200px"
          v-model:value="form.number"
        />
      </a-form-item>
      <a-form-item label="月份" name="month" v-if="form.cardCode == '月/年卡'">
        <a-input
          allow-clear
          placeholder="请输入月份"
          v-model:value="form.month"
        />
      </a-form-item>
      <a-form-item
        label="折扣"
        name="discount"
        v-if="form.cardCode == '充值卡'"
      >
        <a-input-number
          allow-clear
          placeholder="请输入折扣"
          style="width: 200px"
          max="10"
          min="0"
          v-model:value="form.discount"
        />
      </a-form-item>
      <a-form-item label="成人/儿童" name="cardType">
        <a-select
          allow-clear
          v-model:value="form.cardType"
          placeholder="成人/儿童"
          :style="`width: 200px`"
        >
          <a-select-option :value="1">成人</a-select-option>
          <a-select-option :value="2">儿童</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="卡片背景" name="image">
        <SelectFile
          :placeholder="`请选择图片`"
          :limit="1"
          :data="images"
          @done="chooseImage"
          @del="onDeleteItem"
        />
      </a-form-item>
      <a-form-item label="会员卡说明" name="content">
        <!-- 编辑器 -->
        <tinymce-editor
          v-model:value="content"
          :init="config"
          placeholder="会员卡说明"
        />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">显示</a-radio>
          <a-radio :value="1">隐藏</a-radio>
        </a-radio-group>
      </a-form-item>
      <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-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addCard, updateCard } from '@/api/booking/card';
  import { Card } from '@/api/booking/card/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';
  import { Merchant } from '@/api/shop/merchant/model';
  import gfm from '@bytemd/plugin-gfm';
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  import highlight from '@bytemd/plugin-highlight';
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import MerchantSelect from '@/views/booking/account/components/merchant-select.vue';
  import { listMerchant } from '@/api/shop/merchant';

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Card | 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 images = ref<ItemType[]>([]);
  const content = ref('');
  const merchants = ref<Merchant[]>([]);

  // 用户信息
  const form = reactive<Card>({
    cardId: undefined,
    cardName: '',
    cardCode: undefined,
    type: undefined,
    cardType: undefined,
    image: '',
    price: undefined,
    number: 0,
    month: 0,
    discount: 1,
    content: '',
    userId: 0,
    merchantId: 0,
    merchantName: '',
    comments: '',
    status: 0,
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    merchants: [
      {
        required: true,
        type: 'string',
        message: '请选择可适用的场馆',
        trigger: 'blur',
        validator: async (_rule: RuleObject) => {
          if (merchants.value.length == 0) {
            return Promise.reject('请选择可适用的场馆');
          }
          return Promise.resolve();
        }
      }
    ],
    merchantName: [
      {
        required: true,
        type: 'string',
        message: '请选择场馆',
        trigger: 'blur'
      }
    ],
    cardName: [
      {
        required: true,
        type: 'string',
        message: '请填写会员卡名称',
        trigger: 'blur'
      }
    ],
    type: [
      {
        required: true,
        type: 'number',
        message: '请选择会员卡类型',
        trigger: 'blur'
      }
    ],
    cardCode: [
      {
        required: true,
        type: 'string',
        message: '请选择会员卡分组',
        trigger: 'blur'
      }
    ],
    price: [
      {
        required: true,
        type: 'number',
        message: '请填写会员卡价格',
        trigger: 'blur'
      }
    ],
    discount: [
      {
        required: true,
        type: 'number',
        message: '请填写会员卡折扣',
        trigger: 'blur'
      }
    ]
  });

  // 插件
  const plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

  const config = ref({
    height: 500
  });

  const chooseImage = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.image = data.path;
  };

  const onDeleteItem = (index: number) => {
    images.value.splice(index, 1);
    form.image = '';
  };

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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          comments: content.value,
          merchantIds: merchants.value?.map((d) => d.merchantId).join(',')
        };
        const saveOrUpdate = isUpdate.value ? updateCard : addCard;
        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,
    (visible) => {
      if (visible) {
        images.value = [];
        merchants.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.image) {
            images.value.push({
              uid: uuid(),
              url: props.data.image,
              status: 'done'
            });
          }
          if (props.data.merchantIds) {
            listMerchant({ merchantIds: props.data.merchantIds }).then(
              (list) => {
                merchants.value = list;
              }
            );
          }
          if (props.data.comments) {
            content.value = props.data.comments;
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
