<template>
  <div class="animate-card animate-card-50" :class="{ 'active': showForm }" :style="{ height: componentHeight }"
    style="width: 100%;">
    <!-- 下拉按钮 -->
    <el-button class="animate-card__layer" type="primary" @click="toggleForm">
      <el-icon v-if="showForm">
        <ArrowUp />
      </el-icon>
      <div v-else>
        <el-icon>
          <ArrowDown />
        </el-icon>
        发帖
      </div>
    </el-button>

    <!-- 表单部分，使用 v-show 控制显示 -->
    <div class="animate-card__sublayer" style="align-items: center; width: 100%;">
      <el-form v-show="showForm" :model="form" ref="formRef" class="form-container">
        <el-form-item label="内容" prop="content" :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]"
          style="width: 80%;">
          <el-input v-model="form.content" type="textarea" placeholder="有什么新鲜事..." rows=4 />
        </el-form-item>


        <div>
          <el-upload action="#" list-type="picture" :auto-upload="false" :limit="1" :on-exceed="handleExceed"
            ref="postimage" style="position: fixed; left: 12%;display: flex; align-items: center;"
            @change="handleFileChange">
            <!-- @success="handleUploadSuccess" -->


            <el-icon size="30px">
              <Picture />
            </el-icon>图片
            <br>


          </el-upload>

        </div>

        <el-radio-group v-model="radio" fill="#FE4E96" size="small">
          <el-radio-button label="日常动态"></el-radio-button>
          <el-radio-button label="家族故事"></el-radio-button>
        </el-radio-group>




        <div class="button-container">
          <el-button type="primary" @click="submitPost" :disabled="!form.content.trim()"
            style="position:fixed; right:11% ;background-color:#FE4E96">发布</el-button>
        </div>

      </el-form>
    </div>

  </div>
</template>

<script>
  import { defineComponent } from 'vue';
  import axios from '@/utils/axiosConfig';
  import {getUserId} from '@/token/auth';



  export default defineComponent({
    name: 'PostForm',
    components: {


    },
    data() {
      return {
        userid: getUserId(),
        showForm: false,  // 控制表单是否显示
        radio: '日常动态',
        form: {
          content: ''
        },
        fileList: [],
        imageUrl: '',
        loadurl:'',
        componentHeight: '3%'
      };
    },
    methods: {
      async handleFileChange(file) {
        // 当文件被选中时触发
        this.file = file;
        if (file.raw) {
          // 创建预览图片的URL

          this.imageUrl = URL.createObjectURL(file.raw);
         if (file.raw.size / 1024 / 1024 > 2) {
        this.$message.error('成本有限 只能上传1mb以内的照片')
        }

        }
      },
      handleExceed() {
        this.$message.error("目前仅支持添加一张图片");
      },
      // 切换表单显示/隐藏
      toggleForm() {
        this.showForm = !this.showForm;
        if (this.componentHeight == '3%')
          this.componentHeight = '25%';
        else
          this.componentHeight = '3%';
      },
      beforeUpload(file) {
        const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isImage) {
          this.$message.error('只能上传JPG/PNG格式的图片');
        }
        return isImage;
      },
      async handleUploadSuccess(response, file, fileList) {

        this.imageUrl = URL.createObjectURL(file.raw); // 创建临时 URL 以预览图片

        this.$message("创建图片" + this.imageUrl);
        this.fileList = fileList;
      },
      handleRemove(file, fileList) {
        this.imageUrl = ''; // 删除时清空图片预览
        this.fileList = fileList;
      },
      async submitPost() {
        this.$refs.postimage.submit();
        if (!this.form.content.trim()) {
          this.$message.error('内容不能为空');
          return;
        }

      

        try {
          const formData = new FormData();

        formData.append('file', this.file.raw);
        // 使用 axios 来发送请求

        const response = await axios.post('/posts/addphoto', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });

        this.loadurl=response;
          
        } catch (error) {
          this.$message.error("图片上传失败");
          console.log(error);
          return;
        }

        const newPost = {
          userid: getUserId(),
          username: '用户',
          avatarurl: 'https://via.placeholder.com/50',
          timestamp: new Date().toLocaleString(),
          content: this.form.content,
          imageurl: this.loadurl,
          likecount: 0,
          commentcount: 0,
          isfamilystory: this.radio === '家族故事' ? true : false,
          postid: 999,
        };

       
        



        try {
          const response = await axios.post('/posts/addpost', newPost, {
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            }
          });
          if (response.startsWith("增加动态成功！")) {
            const postid = response.replace("增加动态成功！", '').trim();
            this.$message.success("增加动态成功！");
            newPost.postid = postid;
            newPost.imageurl=this.imageUrl;
            this.$emit('post-submitted', newPost);

            this.form.content = '';
            this.imageUrl = '';
            this.fileList = [];

          }
          else {
            console.error(response);
          }

        } catch (error) {
          console.error('发布动态失败:', error);
          this.$message.error('发布动态失败，请刷新后再试');
        }



      },
    }
  });
</script>

<style scoped>
  /* 覆盖选中时的颜色 */
  .el-radio.is-checked .el-radio__inner {
    border-color: #FE4E96 !important;
  }

  .el-radio.is-checked .el-radio__label {
    color: #FE4E96 !important;
  }

  .el-radio .el-radio__inner {
    border-color: #FE4E96 !important;
  }

  .el-radio .el-radio__label {
    color: #FE4E96 !important;
  }

  .form-container {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

  }

  .el-upload-list__item-thumbnail {
    width: 60px;
    /* 修改为你想要的缩略图宽度 */
    height: 60px;
    /* 修改为你想要的缩略图高度 */
    object-fit: cover;
    /* 保证缩略图不会变形 */
  }


  .el-form-item {
    margin-bottom: 15px;
  }

  .upload-demo {
    margin-top: 10px;
  }

  .animate-card {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .animate-card-50 {
    display: flex;
    height: 10%;
    justify-content: center;
    /* 横向居中 */
    transition: height 0.7s ease-in-out;
  }

  .animate-card__layer {
     height: 16px;
    width: 7%;
    font-size: 14px;
    background-color: #FE4E96;
    border: none;
  }

  .animate-card__layer:hover {
    transform: translateY(50%);
    background-color: #FEB2D7;
  }

  .animate-card-50 .animate-card__sublayer {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;

    transform: translateY(-100%);
    text-align: center;
    background-color: #fff;
    color: #000;
    opacity: 0;

  }

  /* 点击后触发动画 */
  .animate-card-50.active .animate-card__layer {
    position: relative;
    transform: scale(0.9) translateY(800%);
    border: 6px solid rgba(255, 255, 255, 0.9);
    z-index: 9;
  }

  .animate-card-50.active .animate-card__sublayer {
    transform: translateY(0px);
    opacity: 1;
  }
</style>