<!-- 编辑弹窗 -->
<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="name">
        <a-input
          allow-clear
          placeholder="请输入套餐名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="副标题" name="subName">
        <a-input
          allow-clear
          placeholder="请输入副标题"
          v-model:value="form.subName"
        />
      </a-form-item>
      <a-form-item label="会员角色" name="roleName">
        <SelectRole
          :placeholder="`请选择会员角色`"
          v-model:value="form.roleName"
          @done="chooseRoleId"
        />
      </a-form-item>
      <a-form-item label="会员等级" name="gradeName">
        <SelectGrade
          :placeholder="`请选择会员角色`"
          v-model:value="form.gradeName"
          @done="chooseGradeName"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入备注"
          v-model:value="form.comments"
        />
      </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-item label="图标" name="icon">
        <ele-image-upload
          v-model:value="images"
          :limit="1"
          :drag="true"
          :item-style="{ width: '60px', height: '60px' }"
          :upload-handler="uploadHandler"
          @upload="onUpload"
        />
      </a-form-item>
      <PriceList :plan-id="form.planId" v-model:value="form.price" />
      <IconList :plan-id="form.planId" v-model:value="form.icons" />
    </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 { addUserPlan, updateUserPlan } from '@/api/love/plan';
  import { UserPlan } from '@/api/love/plan/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import PriceList from './price-list.vue';
  import IconList from './icon-list.vue';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFile } from '@/api/system/file';
  import { Role } from '@/api/system/role/model';
  import { Grade } from "@/api/user/grade/model";

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

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

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

  // 提交状态
  const loading = ref(false);
  // 已上传数据
  const images = ref<ItemType[]>([]);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);

  // 用户信息
  const form = reactive<UserPlan>({
    planId: undefined,
    name: '',
    subName: '',
    roleId: 0,
    roleName: '',
    gradeId: 0,
    gradeName: '',
    status: 0,
    comments: '',
    price: [],
    icons: [],
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请输入套餐名称',
        trigger: 'blur'
      }
    ],
    roleName: [
      {
        required: true,
        type: 'string',
        message: '请选择会员角色',
        trigger: 'blur'
      }
    ],
    gradeName: [
      {
        required: true,
        type: 'string',
        message: '请选择会员等级',
        trigger: 'blur'
      }
    ]
  });

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

  const chooseRoleId = (data: Role) => {
    form.roleId = data.roleId;
    form.roleName = data.roleName;
  };

  const chooseGradeName = (data: Grade) => {
    console.log(data);
    form.gradeId = data.gradeId;
    form.gradeName = data.name;
  };

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return;
    }
    onUpload(item);
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: data.thumbnail,
          status: 'done'
        });
        form.icon = data.thumbnail;
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateUserPlan : addUserPlan;
        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) {
        if (props.data) {
          assignObject(form, props.data);
          images.value = [];
          if (props.data.icon) {
            images.value.push({
              uid: Number(props.data.planId),
              url: props.data.icon,
              status: 'done'
            });
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
  .upload-text {
    margin-right: 70px;
  }
  .icon-bg {
    width: 50px;
    height: 50px;
    display: block;
    border-radius: 50px;
    background: url('data:image/svg+xml;charset=utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20version%3D%221.1%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%221%22%20x1%3D%220%22%20x2%3D%221%22%20y1%3D%220%22%20y2%3D%220%22%20gradientTransform%3D%22matrix(6.123233995736766e-17%2C%201%2C%20-0.024693877551020406%2C%206.123233995736766e-17%2C%200.5%2C%200)%22%3E%3Cstop%20stop-color%3D%22%230a060d%22%20stop-opacity%3D%221%22%20offset%3D%220%22%3E%3C%2Fstop%3E%3Cstop%20stop-color%3D%22%23660061%22%20stop-opacity%3D%221%22%20offset%3D%220.95%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22url(%231)%22%3E%3C%2Frect%3E%3C%2Fsvg%3E');
  }
</style>
