<!-- 编辑弹窗 -->
<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="type">
        <a-select
          v-model:value="form.type"
          placeholder="页面"
          :style="`width: 200px`"
        >
          <a-select-option :value="2">首页</a-select-option>
          <a-select-option :value="3">商城</a-select-option>
          <a-select-option :value="1">订单</a-select-option>
          <a-select-option :value="0">我的</a-select-option>
          <a-select-option :value="4">管理</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="菜单名称" name="title">
        <a-input
          allow-clear
          placeholder="请输入菜单名称"
          v-model:value="form.title"
        />
      </a-form-item>
      <a-form-item label="路由地址" name="path">
        <a-input
          allow-clear
          placeholder="请输入路由地址"
          v-model:value="form.path"
        />
      </a-form-item>
      <a-form-item label="菜单图标" name="icon">
        <SelectFile
          :placeholder="`请选择图片`"
          :limit="1"
          :data="images"
          @done="chooseFile"
          @del="onDeleteItem"
        />
      </a-form-item>
      <a-form-item label="图标颜色" name="color">
        <ele-color-picker
          :show-alpha="true"
          v-model:value="form.color"
          :predefine="predefineColors"
        />
      </a-form-item>
      <a-form-item label="所在行" name="rows">
        <a-input-number
          :min="0"
          :max="3"
          class="ele-fluid"
          placeholder="请输入所在行"
          v-model:value="form.rows"
        />
      </a-form-item>
      <a-form-item label="打开方式" name="target">
        <DictSelect
          dict-code="navType"
          class="form-item"
          placeholder="请选择链接方式"
          v-model:value="form.target"
        />
      </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 { addMpMenu, updateMpMenu } from '@/api/cms/mp-menu';
  import { MpMenu } from '@/api/cms/mp-menu/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';

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 类型 0服务 1订单
    type?: number;
    // 修改回显的数据
    data?: MpMenu | 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 form = reactive<MpMenu>({
    menuId: undefined,
    parentId: 0,
    title: '',
    type: 2,
    rows: 0,
    isMpWeixin: true,
    path: undefined,
    component: undefined,
    target: undefined,
    icon: '',
    color: undefined,
    hide: undefined,
    position: undefined,
    active: undefined,
    userId: 0,
    home: undefined,
    sortNumber: 100,
    comments: '',
    status: 0
  });

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

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

  const chooseFile = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.thumbnail,
      status: 'done'
    });
    form.icon = data.thumbnail;
  };

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

  // 预设颜色
  const predefineColors = ref([
    '#40a9ff',
    '#9254de',
    '#36cfc9',
    '#73d13d',
    '#f759ab',
    '#cf1313',
    '#ff4d4f',
    '#ffa940',
    '#ffc53d',
    '#f3d3d3',
    '#1b1b1b',
    '#363636',
    '#4d4d4d',
    '#737373',
    '#a6a6a6',
    '#d9d9d9',
    '#e6e6e6',
    '#f2f2f2',
    '#f7f7f7',
    '#fafafa'
  ]);

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

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateMpMenu : addMpMenu;
        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 = [];
        if (props.type) {
          form.type = props.type;
        }
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.icon) {
            images.value.push({
              uid: uuid(),
              url: props.data.icon,
              status: 'done'
            });
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
