<template>

<div style="margin: 0">
    <a-textarea
      v-model:value="content"
      placeholder="这一刻的想法..."
      :auto-size="{ minRows: 5, maxRows: 10 }"
      class="moment-content"
    />
</div>

<div class="media-container" style="width: 250px;">

    <div v-if="images != null && images.length > 0">
        <div v-for="image in images" class="moment-image">
            <img :src="image">
        </div>
    </div>
    <div v-if="video != null">
        <video 
            autoplay
            style="max-height: 250px; float: left; max-width: 100%;"
            controls 
            :poster="video" 
        >
            <source :src="video" type="video/mp4">
        </video>
    </div>
    <button class="uploadMediaButton" @click="uploadMedia" v-if="uploadBtnVidible">
        <PlusOutlined />
    </button>
    <!-- 隐藏的文件上传input -->
    <input 
        type="file"
        ref="mediaUpload"
        accept="image/png, image/jpeg, image/jpg, video/mp4"
        style="display: none;"
        @change="handleFileUpload"
    />
    <div style="clear: both;"></div>
</div>

<div class="button-container" style="margin-top: 60px;">
    <button class="cancelButton" @click="cancelPublish">
        取消
    </button>
    <button class="publishButton" @click="publish">
        发表
    </button>
</div>

</template>

<script>
  import axios from 'axios';
  import { inject, defineComponent, ref, onMounted, onUnmounted, watch } from 'vue';
  import { message } from 'ant-design-vue';
  export default defineComponent({
    props: {
        
    },
    components: {
        
    },
    setup(props, { emit }) {

      const loginUser = ref(inject('loginUser'));
      const mediaUpload = ref(null);
      const uploadUrl = `/client-service/chat/file/upload`; // 上传API
      const images = ref([]); 
      const video = ref(null);
      const content = ref("");
      const uploadBtnVidible = ref(true);
      

      const uploadMedia = () => {
        mediaUpload.value.click();
      }

       // 处理文件选择
       const handleFileUpload = async (e) => {
            const file = e.target.files[0];
            if (!file) return;
             // 验证文件类型（兼容浏览器绕过 accept 的情况）
            const allowedTypes = ['image/png', 'image/jpeg', 'video/mp4'];
            if (!allowedTypes.includes(file.type)) {
                alert('仅支持 PNG、JPEG 图片和 MP4 视频');
                return;
            }
            // 校验文件大小（示例限制2MB）
            if (file.size > 20 * 1024 * 1024) {
                message.error('图片大小不能超过20MB');
                return;
            }
            // 方式2：上传到服务器（示例使用axios）
            try {
                const formData = new FormData();
                formData.append('file', file);
                const response = await axios.post(uploadUrl, formData, {
                    headers: {
                    'Content-Type': 'multipart/form-data',
                    'origin-url': window.location.href,
                    'upload-path': 'moment/media'
                    }
                });
                if (response.data.code === 40001) {
                    window.location.href = response.data.redirect_url;
                }
                // 预览红包封面图
                if (response.data.data.type == 'IMAGE') {
                    video.value = null;
                    images.value.push(response.data.data.url);
                } else  if (response.data.data.type == 'VIDEO') {
                    images.value = [];
                    video.value = response.data.data.url;
                }
                if(images.value.length == 9 || video.value != null) {
                    uploadBtnVidible.value = false;
                } else {
                    uploadBtnVidible.value = true;
                }
            } catch (error) {
                message.error('上传失败');
                console.error('Upload error:', error);
            }
        };
      

      const publish = async () => {
            if (!content.value || (video == null && images.length == 0)) {
                message.error("内容为空");
                return ;
            }
            try {
                // 调用接口发送登录请求
                const response = await axios.post(`/client-service/moment/publish`, 
                {
                    content: content.value,
                    images: images.value,
                    video: video.value
                });
                if (response.data.code === 40001) {
                    window.location.href = response.data.redirect_url;
                } else if (response.data.code != 200) {
                    message.error(response.data.msg);
                }
                // 发布成功
                message.info("动态已发布，审核中");
                emit('success');
            } catch (error) {
                message.error("发布异常", error);
            }

      }

      const cancelPublish = () => {
        emit('cancel');
        // 可选：清空已上传内容
        content.value = '';
        images.value = [];
        video.value = null;
      }
      onMounted(() => {
        
      });
      onUnmounted(() => {
        
      });
      
      return {
        uploadBtnVidible,
        content,
        images,
        video,
        mediaUpload,
        cancelPublish,
        uploadMedia,
        handleFileUpload,
        publish
      };
    }
  });

</script>


<style scoped>
/* 穿透组件作用域，覆盖内部样式 */
.moment-content  {
  border: none !important;
  box-shadow: none !important;
}
.moment-image {
    width: 70px;
    height: 70px;
    border: none;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
    overflow: hidden;
}
.moment-image img {
    width: 100%;
    min-height: 100%;
}
.uploadMediaButton {
    width: 70px;
    height: 70px;
    border: none;
    background-color: whitesmoke;
}
.uploadMediaButton:hover {
    cursor: pointer;
    background-color: rgb(233, 232, 232);
}
.button-container {
    display: flex;
    justify-content: center;
    gap: 20px; /* 或使用 margin-right 兼容方案 */
    margin-top: 60px;
}
/* 保持原有按钮样式 */
.cancelButton, .publishButton {
    width: 80px; 
    height: 30px;
    border-radius: 5px;
    border: 0px;
    /* 添加过渡效果提升交互 */
    transition: all 0.3s;
}
.publishButton {
    background-color: rgb(59, 206, 59);
    color: white;
}
.cancelButton:hover {
    cursor: pointer;
    background-color: rgba(19, 158, 19, 0.1);
}
.publishButton:hover {
    cursor: pointer;
    background-color: rgb(36, 175, 36);
}
</style>