<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑' : '添加'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <div class="content">
        <SelectFile
          :placeholder="`请选择图片`"
          :limit="9"
          :data="images"
          @done="chooseFile"
          @del="onDeleteItem"
        />
        <!--        <ele-image-upload-->
        <!--          v-model:value="images"-->
        <!--          :limit="6"-->
        <!--          :drag="true"-->
        <!--          :item-style="{ width: '150px', height: '267px' }"-->
        <!--          :upload-handler="uploadHandler"-->
        <!--          @upload="onUpload"-->
        <!--        />-->
        <small class="ele-text-placeholder">
          请上传应用截图(最多9张)，建议宽度300*533像素，小于2M/张
        </small>
      </div>
    </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 { addApp, updateApp } from '@/api/oa/app';
  import type { App } from '@/api/oa/app/model';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFileLocal } from '@/api/system/file';
  import { TOKEN_STORE_NAME } from '@/config/setting';
  import { FileRecord } from '@/api/system/file/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;

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

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 当期时间
  const logo = ref<ItemType[]>([]);
  const appQrcode = ref<ItemType[]>([]);
  const images = ref<ItemType[]>([]);
  const content = ref('');
  const requirement = ref('');

  const token = localStorage.getItem(TOKEN_STORE_NAME);
  const formRef = ref<FormInstance | null>(null);

  // 用户信息
  const form = reactive<App>({
    // 应用id
    appId: undefined,
    // 应用截图
    images: ''
  });

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

  const { resetFields } = useForm(form);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          content: content.value,
          requirement: requirement.value,
          search: form.search ? 1 : 0,
          images: JSON.stringify(images.value)
          // appTypeMultiple: JSON.stringify(form.appTypeMultiple)
        };
        const saveOrUpdate = isUpdate.value ? updateApp : addApp;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 上传事件 */
  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;
    uploadFileLocal(file, props.data?.appId)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: data.url,
          status: 'done'
        });
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

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

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

  const reload = () => {
    loading.value = true;
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        content.value = '';
        requirement.value = '';
        logo.value = [];
        images.value = [];
        appQrcode.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.appIcon) {
            logo.value.push({
              uid: 0,
              url: props.data.appIcon,
              status: 'done'
            });
          }
          if (props.data.appQrcode) {
            appQrcode.value.push({
              uid: 0,
              url: props.data.appQrcode,
              status: 'done'
            });
          }
          if (props.data.companyId) {
            console.log(props.data);
          }
          if (props.data.images) {
            const arr = JSON.parse(props.data.images);
            arr.map((d, i) => {
              images.value.push({
                uid: d.uid,
                url: d.url,
                status: 'done'
              });
            });
          }
          if (props.data.search) {
            form.search = props.data.search == 1 ? true : 0;
          }
          if (props.data.content) {
            content.value = props.data.content;
          }
          if (props.data.requirement) {
            requirement.value = props.data.requirement;
          }
          isUpdate.value = true;
          reload();
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
