<template>
  <a-upload
    name="file"
    :multiple="itemMultipleChoiceFlag"
    :action="fileUploadUrl"
    :headers="headers"
    list-type="file"
    :maxCount="itemMultipleChoiceFlag ? 10000000 : 1"
    :disabled="props.readonly || props.disabled"
    v-model:file-list="fileList"
    @change="handleFileChange"
  >
    <a-button type="primary" v-if="props.isDesgin || !(props.readonly || props.disabled)">
      <upload-outlined />
      上传附件
    </a-button>
    <template #itemRender="{ file }">
      <div class="ant-upload-list-item ant-upload-list-item-done ant-upload-list-item-list-type-text">
        <div class="ant-upload-list-item-info">
          <span class="ant-upload-span">
            <div class="ant-upload-text-icon">
              <paper-clip-outlined class="actions-icon" />
            </div>
            <a class="ant-upload-list-item-name">{{ file.name }}</a>
            <span class="ant-upload-list-item-card-actions">
              <a-space>
                <fund-view-outlined class="actions-icon" title="预览" @click="preview(file)" />
                <cloud-download-outlined class="actions-icon" title="下载" @click="downloadFile(file)" />
                <delete-outlined
                  @click="remove(file)"
                  title="删除"
                  class="actions-icon"
                  v-if="props.isDesgin || !(props.readonly || props.disabled)"
                />
              </a-space>
            </span>
          </span>
        </div>
      </div>
    </template>
  </a-upload>
</template>

<script setup name="UploadFileComponent">
import { ref, onMounted, watch, computed } from 'vue';
import { message } from 'ant-design-vue';
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';
import { deepClone } from '@/utils/common/util';

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  //是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object,
    default: {}
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  // 是否正常保存，不是转json格式
  normal: {
    type: Boolean,
    default: false
  },
  // 是否是设计
  isDesgin: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:value', 'onChange']);

// fileList
const fileList = ref([]);

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

// 选中的值
const dataValue = ref([]);

// 是否自己改变值
const isOwnChange = ref(false);

// 是否多选
const itemMultipleChoiceFlag = computed(() => {
  if (props.record?.itemMultipleChoiceFlag || props.multiple) {
    return true;
  }
  return false;
});

onMounted(() => {
  setDataValue();
  getFileList();
});

// 设置选中的值
const setDataValue = () => {
  if (props.value) {
    if (itemMultipleChoiceFlag.value) {
      dataValue.value = props.normal ? props.value : JSON.parse(props.value);
    } else {
      dataValue.value = [props.value];
    }
  } else {
    dataValue.value = [];
  }
};

// 获取文件详情列表
const getFileList = () => {
  if (isOwnChange.value) return;
  if (dataValue.value?.length == 0) return;
  FileApi.getAntdVInfoBatch({ fileIdList: dataValue.value }).then(res => {
    res.data.forEach((item, index) => {
      item.fileId = dataValue.value[index];
    });
    fileList.value = deepClone(res.data);
  });
  isOwnChange.value = false;
};

/**
 * 上传文件改变时的状态
 *
 * @param info 组件回调原有参数
 * @param fieldCode 文件表单字段名称
 * @author fengshuonan
 * @date 2021/12/29 14:25:18
 */
const handleFileChange = info => {
  if (info.file.status === 'done') {
    info.file.fileId = info.file.response.data.fileId;
    message.success(`${info.file.name} 图片上传成功`);
    if (itemMultipleChoiceFlag.value) {
      dataValue.value.push(info.file.response.data.fileId);
    } else {
      dataValue.value = [info.file.response.data.fileId];
    }

    isOwnChange.value = true;
    dataValueChange();
  }
};

// 更改值
const dataValueChange = () => {
  let data;
  if (itemMultipleChoiceFlag.value) {
    data = props.normal ? dataValue.value : JSON.stringify(dataValue.value);
  } else {
    data = dataValue.value[0] ?? '';
  }

  emits('update:value', data);
  emits('onChange', props.record);
};

// 预览
const preview = file => {
  let url = `${API_BASE_PREFIX}/documentPreview?fileId=${file.fileId}&token=${getToken()}`;
  window.open(url, '_blank');
};
// 下载
const downloadFile = file => {
  FileApi.download({ token: getToken(), fileId: file.fileId });
};

// 删除文件
const remove = file => {
  let fileId = file.fileId;
  if (fileId) {
    // 查找需要删除的文件所在文件数组中的索引
    let findIndex = fileList.value.findIndex(item => item.fileId === fileId);
    if (findIndex !== -1) {
      fileList.value.splice(findIndex, 1);
      dataValue.value.splice(findIndex, 1);
      isOwnChange.value = true;
      dataValueChange();
    }
  }
};

watch(
  () => props.value,
  val => {
    setDataValue();
    getFileList();
  },
  { deep: true }
);
</script>

<style scoped lang="less">
.ant-upload-span {
  width: calc(100% - 75px);
  .actions-icon {
    font-size: 20px;
    cursor: pointer;
    color: #00000073;
  }
}
.ant-upload-list-item {
  height: 40px !important;
  line-height: 40px;
}
.ant-upload-list-item-name {
  font-size: 16px;
  line-height: 40px !important;
}
.ant-upload-list-item-info .ant-upload-text-icon .anticon {
  top: 12px !important;
}
.ant-space {
  line-height: 45px !important;
}
</style>
