<template>
  <!-- 新增编辑 -->
  <a-modal
    :width="524"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    :title="isUpdate ? '编辑应用链接分类' : '新建应用链接分类'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="应用链接分类名称:" name="categoryName">
        <a-input v-model:value="form.categoryName" allow-clear placeholder="请输入应用链接分类名称" />
      </a-form-item>
      <a-form-item label="图标类型:" name="iconType">
        <a-radio-group v-model:value="form.iconType">
          <a-radio :value="1">文件</a-radio>
          <a-radio :value="2">选择图标</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="应用链接分类图标:" name="iconList" v-if="form.iconType == 1">
        <a-upload
          name="file"
          :multiple="false"
          v-model:file-list="form.iconList"
          :default-file-list="form.iconList"
          :maxCount="1"
          :action="fileUploadUrl"
          list-type="picture-card"
          :headers="headers"
          :before-upload="beforeUpload"
          accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
          @preview="handlePreviewPhoto"
          @download="downloadPhoto"
          @change="linkIconFileIdChange"
          :showUploadList="{
            showDownloadIcon: true
          }"
        >
          <plus-outlined style="font-size: 28px; font-weight: 200" v-if="form.iconList.length == 0" />
        </a-upload>
      </a-form-item>
      <a-form-item label="应用链接分类图标:" name="iconCode" v-if="form.iconType == 2">
        <icon-select v-model:value="form.iconCode" placeholder="请选择应用链接分类图标"></icon-select>
      </a-form-item>
      <a-form-item label="分类排序:" name="fldSort">
        <a-input-number
          v-model:value="form.fldSort"
          :min="0"
          style="width: 100%"
          placeholder="请输入分类排序"
          allow-clear
          autocomplete="off"
        />
      </a-form-item>
    </a-form>

    <!-- 图标预览弹框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script setup name="NewTypeAddEdit">
import { ref, onMounted, reactive } from 'vue';
import { message, Upload } from 'ant-design-vue';
import { AppLinkTypeApi } from '../api/AppLinkTypeApi';
import { getToken } from '@/utils/token-util';
import { API_BASE_PREFIX } from '@/config/setting';
import { FileApi, FileUploadUrl as fileUploadUrlPrefix } from '@/views/system/backend/file/api/FileApi';

const props = defineProps({
  visible: Boolean,
  data: Object
});

const emits = defineEmits(['update:visible', 'done']);
// 弹框加载
const loading = ref(false);
// 是否是编辑状态
const isUpdate = ref(false);
// 表单数据
const form = ref({
  fldSort: 100,
  iconType: 2,
  iconList: []
});
// 验证规则
const rules = reactive({
  categoryName: [{ required: true, message: '请输入应用链接分类名称', type: 'string', trigger: 'blur' }],
  iconType: [{ required: true, message: '请选择图标类型', type: 'number', trigger: 'blur' }],
  iconList: [{ required: true, message: '请选择应用链接分类图标', type: 'array', trigger: 'blur' }],
  iconCode: [{ required: true, message: '请选择应用链接分类图标', type: 'string', trigger: 'change' }],
  fldSort: [{ required: true, message: '请输入分类排序', type: 'number', trigger: 'blur' }]
});
// ref
const formRef = ref(null);

// 上传文件的url
const fileUploadUrl = ref(`${API_BASE_PREFIX}${fileUploadUrlPrefix}?secretFlag=N`);
// 上传文件时候要带header
const headers = ref({
  Authorization: getToken()
});

// 是否展示图片预览
const previewVisible = ref(false);
// 图片地址
const previewImage = ref(null);

onMounted(async () => {
  if (props.data) {
    isUpdate.value = true;
    getDetail();
  } else {
    isUpdate.value = false;
  }
});

const getDetail = async () => {
  const res = await AppLinkTypeApi.detail({ categoryId: props.data.categoryId });
  form.value = Object.assign({}, res);
  form.value.iconList = [];
  if (res.categoryIconFileId && res?.iconType == 1) setFileList('iconList', [res.categoryIconFileId]);
};

// 设置文件列表
const setFileList = (name, fileIdList) => {
  FileApi.getAntdVInfoBatch({ fileIdList: fileIdList }).then(res => {
    res.data.forEach((item, index) => {
      item.fileId = fileIdList[index];
      item.uid = item.fileId;
    });
    form.value[name] = [...res.data];
  });
};

//上传之前的回调
const beforeUpload = file => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/tif' ||
    file.type === 'image/jfif' ||
    file.type === 'image/webp' ||
    file.type === 'image/pjp' ||
    file.type === 'image/apng' ||
    file.type === 'image/pjpeg' ||
    file.type === 'image/avif' ||
    file.type === 'image/ico' ||
    file.type === 'image/tiff' ||
    file.type === 'image/bmp' ||
    file.type === 'image/xbm' ||
    file.type === 'image/jxl' ||
    file.type === 'image/svgz' ||
    file.type === 'image/gif' ||
    file.type === 'image/svg';
  if (!isJpgOrPng) {
    message.error('只能上传图片!');
    return Upload.LIST_IGNORE; //阻止列表展现
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
  }
  return isJpgOrPng && isLt5M;
};

// 点击预览图片
const handlePreviewPhoto = async file => {
  previewImage.value = file.url || file.preview || file.thumbUrl;
  previewVisible.value = true;
};

//下载图片
const downloadPhoto = file => {
  let id = file.response ? file.response.data.fileId : file.uid;
  FileApi.download({ token: getToken(), fileId: id });
};

const linkIconFileIdChange = info => {
  if (info.file.status === 'done') {
    // 设置临时fileList的值
    form.value.iconList = [info.file];
    // 将文件属性名和文件编码存入数组中
    message.success(`${info.file.name} 图片上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 图片上传失败`);
  }
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  await formRef.value.validate();
  if (form.value.iconList?.length) {
    form.value.categoryIconFileId = form.value.iconList[0]?.response?.data?.fileId
      ? form.value.iconList[0]?.response?.data?.fileId
      : form.value.iconList[0]?.uid;
  }
  // 修改加载框为正在加载
  loading.value = true;

  let result = null;

  // 执行编辑或修改
  if (isUpdate.value) {
    result = AppLinkTypeApi.edit(form.value);
  } else {
    result = AppLinkTypeApi.add(form.value);
  }
  result
    .then(async result => {
      // 移除加载框
      loading.value = false;

      // 提示添加成功
      message.success(result.message);
      // 关闭弹框，通过控制visible的值，传递给父组件
      updateVisible(false);

      // 触发父组件done事件
      emits('done');
    })
    .catch(() => {
      loading.value = false;
    });
};
</script>

<style></style>
