<!--
 * @Author: ysh
 * @Date: 2025-03-18 11:14:52
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-03-19 14:05:47
-->
<template>
  <view>
    <view class="btn">
      <uv-button @click="chooseFile" text="+ 选择文件" type="primary" :disabled="!showBtn"></uv-button>
    </view>
    <view v-if="fileName" class="file-box">
      <view class="link">
        <uv-link :href="`${fileUrl + fileName}`" :text="docName" color="#19be6b" line-color="#19be6b"></uv-link>
      </view>
      <view class="delete" v-if="showBtn">
        <uv-icon name="trash" color="#f56c6c" size="18px" @click="deleteFile()"></uv-icon>
      </view>
    </view>
    <text v-if="showBtn">只能上传1个文件,重复上传将覆盖原文件</text>
  </view>
</template>
<script>
import config from '@/config';
import { getToken } from '@/utils/auth'
import { getFileName } from '@/utils/common';
import upload from '@/utils/upload'
export default {
  props: {
    fileType: String,
    fileName: String,
    showBtn: Boolean
  },
  data() {
    return {
      value: [],
      tempFilePath: '',
      fileUrl: config.baseUrl + '/profile/upload',
      docName: ''
    }
  },
  watch: {
    fileName(newval) {
      this.docName = getFileName(newval);
    }
  },
  created() {
  },
  methods: {
    chooseFile() {
      uni.chooseFile({
        count: 1,
        type: 'all',
        success: (res) => {
          this.tempFilePath = res.tempFiles[0].path;
          let params = {
            url: '/common/upload',
            filePath: this.tempFilePath,
            name: 'file',
            formData: { // 附加表单数据
              fileType: this.fileType
            },
          }
          //上传文件
          upload(params).then(res => {
            if (res.code == 200) {
              let fileName = '/' + this.fileType + '/' + res.newFileName
              this.$modal.msgSuccess(res.msg);
              this.$emit('success', fileName)
            }
          })
        },
        fail: (err) => {
          console.error('选择文件失败：', err);
        }
      });
    },
    deleteFile() {
      uni.showModal({
        title: '提示',
        content: '是否删除文件？',
        success: (res) => {
          if (!res.confirm) {
            return;
          }
          // 继续执行后续代码
          this.$emit('deleteFile')
        }
      });
    }
  },
}
</script>

<style lang="scss" scoped>
.file-box {
  display: flex;
  height: 60px;
  align-items: center;
  border: 1px solid #ececec;
  padding: 10px;
  .link {
    flex: 1;

  }
}

.btn {
  width: 100px;
  height: 40px;
}

</style>