<!-- 编辑弹窗 -->
<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: 5, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="VIP卡名称" name="name">
        <a-input
          allow-clear
          placeholder="请输入会员卡名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="VIP卡等级类型" name="vipType">
        <a-radio-group v-model:value="form.vipType">
          <a-radio :value="1">特殊vip卡</a-radio>
          <a-radio :value="2">普通vip卡</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="卡类型" name="cardType">
        <a-radio-group v-model:value="form.cardType">
          <a-radio :value="1">成人卡</a-radio>
          <a-radio :value="2">儿童卡</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="VIP卡类型" name="type">
        <a-radio-group v-model:value="form.type">
          <a-radio :value="1">年卡</a-radio>
          <a-radio :value="2">次卡</a-radio>
          <a-radio :value="3">月卡</a-radio>
          <a-radio :value="4">季卡</a-radio>
          <a-radio :value="5">VIP充值卡</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="是否赠送积分" name="isIntegral">
        <a-radio-group v-model:value="form.isIntegral">
          <a-radio :value="1">赠送</a-radio>
          <a-radio :value="2">不赠送</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="可选场馆" name="sid">
        <ThinkSelectSiteMultiple v-model:value="sites" />
      </a-form-item>
      <a-form-item label="会员卡价格" name="price">
        <a-input
          allow-clear
          placeholder="请输入会员卡价格"
          v-model:value="form.price"
        />
      </a-form-item>
      <a-form-item label="会员卡介绍" name="desc">
        <a-input
          allow-clear
          placeholder="请输入会员卡介绍"
          v-model:value="form.desc"
        />
      </a-form-item>
      <a-form-item label="会员卡说明" name="info">
        <a-input
          allow-clear
          placeholder="请输入会员卡说明"
          v-model:value="form.info"
        />
      </a-form-item>
      <a-form-item label="折扣率" name="discount">
        <a-input
          allow-clear
          placeholder="请输入折扣率"
          v-model:value="form.discount"
        />
      </a-form-item>
      <a-form-item label="使用次数" name="count">
        <a-input
          allow-clear
          placeholder="请输入使用次数"
          v-model:value="form.count"
        />
      </a-form-item>
      <a-form-item label="每使用一次减少的金额" name="eachMoney">
        <a-input
          allow-clear
          placeholder="请输入每使用一次减少的金额"
          v-model:value="form.eachMoney"
        />
      </a-form-item>
      <a-form-item label="年限" name="term">
        <a-input
          allow-clear
          placeholder="请输入年限"
          v-model:value="form.term"
        />
      </a-form-item>
      <a-form-item label="月限" name="month">
        <a-input
          allow-clear
          placeholder="请输入月限"
          v-model:value="form.month"
        />
      </a-form-item>
      <a-form-item label="日限" name="day">
        <a-input
          allow-clear
          placeholder="请输入日限"
          v-model:value="form.day"
        />
      </a-form-item>
      <a-form-item label="排序" name="sort">
        <a-input-number
          :min="0"
          :max="9999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sort"
        />
      </a-form-item>
      <a-form-item label="特殊卡开发凭证图" name="pic">
        <a-avatar :src="`${IMG_URL}${form.pic}`" :size="120" />
      </a-form-item>
      <a-form-item label="VIP充值卡价格组" name="prices">
        {{ form.prices }}
      </a-form-item>
      <a-form-item label="是否有效" name="isUse">
        <a-radio-group v-model:value="form.isIntegral">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="2">否</a-radio>
        </a-radio-group>
      </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 { addThinkVip, updateThinkVip } from '@/api/think/thinkVip';
  import { ThinkVip } from '@/api/think/thinkVip/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';
  import { ThinkSite } from '@/api/think/thinkSite/model';
  import { IMG_URL } from '@/config/setting';

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ThinkVip | 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 sites = ref<ThinkSite[]>([]);

  // 用户信息
  const form = reactive<ThinkVip>({
    id: undefined,
    sid: undefined,
    name: undefined,
    price: undefined,
    desc: undefined,
    info: undefined,
    discount: undefined,
    count: undefined,
    eachMoney: undefined,
    term: 1,
    month: undefined,
    day: undefined,
    type: 1,
    cardType: 1,
    vipType: 2,
    pic: undefined,
    prices: undefined,
    isIntegral: 2,
    isUse: undefined
  });

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

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请填写名称',
        trigger: 'blur'
      }
    ]
  });

  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 join = sites.value.map((d) => d.id).join(',');
        const formData = {
          ...form,
          sid: join
        };
        const saveOrUpdate = isUpdate.value ? updateThinkVip : addThinkVip;
        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 = [];
        sites.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.sid) {
            const split = props.data.sid.split(',');
            split.map((id) => {
              sites.value.push({
                id: Number(id)
              });
            });
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
