<template>
  <view class="publish-container">
    <view class="content-body">
      <view class="text-area">
        <u--textarea class="textareaDef" v-model="formData.title" placeholder="请输入标题..." maxLength="30" border="none"
          height="20"></u--textarea>
        <view class="line"></view>
      </view>
      <view class="content-area">
        <u--textarea class="textareaDef" v-model="formData.content" placeholder="
此刻你想要分享" maxLength="500" border="none" height="150" count></u--textarea>
      </view>
      <view class="media-area" :style="{width: formData.videoUrl ? '340rpx' : '100%' }">
        <view v-if="formData.videoUrl">
          <view class="icon iconfont icon-cuo">
            <image src="/static/login/close2.png" mode="" style="width: 32rpx;height: 32rpx;" @tap="delectVideo">
            </image>
          </view>

          <video ref="myVideo" :src="formData.videoUrl" class="video-container" controls></video>
        </view>
        <clUpload v-else v-model="fileList" :action="uploadApi" :headers="headers" :count="maxCount" :listStyle="{
          columnGap: '20rpx',
          rowGap: '20rpx',
          width: '130rpx',
          radius: '12rpx',
        }" :imageFormData="{
                          count: 9,
                          size: 2,
                        }" :videoFromData="{
                          count: 1,
                          size: 50,
                        }" :maxVideo="1" :fileType="mediaType" addImg="/static/login/cameraIcon.png"
          deleteImg="/static/login/cameraIcon.png" @onSuccess="onSuccess" @onMediaTypeSelect="selectMediaType"
          @onError="onCancel">


        </clUpload>
      </view>

      <view class="tips">
        <text v-if="fileList.length === 0">支持上传图片(最多9张)或视频(1个)</text>
      </view>
    </view>
    <view class="location-cell">
      <image src="/static/workbench/locationIcon.png" style="width: 32rpx;height: 32rpx;"></image>
      <u-cell-group :border="false">

        <u-cell title="地点" :value="formData.location || '请选择'" isLink :border="true" @click="selectLocation">
        </u-cell>
        <!-- <u-cell
          title="可见范围"
          :value="formData.visibleRange || '请选择'"
          isLink
          :border="true"
          @click="showScopePicker = true"
        >
        </u-cell> -->
      </u-cell-group>
    </view>
    <view class="footer-bar">
      <u-button text="存为草稿" customStyle="width: 311rpx;height: 88rpx;background: rgba(51,51,53,0.05);
border-radius: 60rpx 60rpx 60rpx 60rpx;" @click="submit('draft')"></u-button>
      <u-button text="发布动态" color="linear-gradient(80deg,#02f6c1 0%,#07cdc4 100%)" shape="circle" customStyle="width: 311rpx;height: 88rpx;background: #333335;
border-radius: 60rpx 60rpx 60rpx 60rpx;" @click="submit('publish')"></u-button>
    </view>
    <!-- 可见范围 -->
    <u-picker title="请选择" :show="showScopePicker" :columns="scopeList" confirmColor="#1ecbc3" @confirm="confirmScope"
      @cancel="showScopePicker = false"></u-picker>


    <!-- 确认返回 -->
    <u-popup :show="popShow" mode="center" :round="12">
      <view class="popup-content">
        <view class="popup-title">确认返回</view>
        <view class="popup-desc">
          <text>是否存入草稿箱?</text>
        </view>
        <view class="popup-btn">
          <u-button text="不保存" shape="circle"
            customStyle="width: 225rpx; height: 68rpx; font-size: 28px; color: #1BD6CD; border-color: #1BD6CD;"
            @click="popClose"></u-button>
          <u-button text="保存" color="linear-gradient( 90deg, #1AD7CE 0%, #21C9C1 100%)" shape="circle"
            customStyle="width: 225rpx; height: 68rpx; font-size: 28px;" @click="save('draft')"></u-button>
        </view>
      </view>
    </u-popup>
    <!-- 草稿提示弹窗 -->
    <u-popup :show="popShow1" mode="center" class='popShow1' :round="12">
      <view class="popup-content1">
        <view class="popup-title">您有一篇未发布的草稿，要继续写吗？</view>

        <view class="popup-desc">
          <text>简单描述《春秋笔法》在的应用场景</text>
        </view>
        <view class="popup-btn1">
          <view class="btn" @click="goOnFun">继续编辑</view>
          <view class="btn" @click="popClose">重新写</view>
          <view class="btn" @click="deleteFun">删除草稿</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { baseUrl } from '@/common/config.js'
import { dynamicPublish, dynamicDetail, draftList, dynamicEdit } from '@/api/dynamic'
import clUpload from '@/components/cl-upload/cl-upload/cl-upload.vue'
export default {
  components: { clUpload },
  data() {
    return {
      draftObj: {},
      popShow1: false,
      loading: false,
      showScopePicker: false,
      popShow: false,
      type: '',
      formData: {
        title: '',
        content: '',
        location: '',
        address: '',
        latitude: '',
        longitude: '',
        //visibleRange: '',
        videoUrl: '',
        videoCoverUrl: '',
      },
      headers: {
        Authorization: `tf: ${uni.getStorageSync('access-token')}`,
      },
      scopeList: [['公开']],
      fileList: [],
      mediaType: 'all', // 默认为图片模式，上传第一个文件后确定类型
      uploadApi: baseUrl + '/common/upload', // 默认使用图片上传接口
    }
  },
  computed: {
    maxCount() {
      return this.mediaType === 'video' ? 1 : 9
    },
  },
  onLoad(options) {
    const { momentId, type } = options
    this.type = type
    if (momentId) {//编辑
      this.getDynamicDetail(momentId)
    } else {
      this.draftDynamicListFun()
    }

  },
  methods: {
    //获取草稿箱列表
    draftDynamicListFun() {
      draftList({
        pageNum: 1,
        pageSize: 10,
      }).then(res => {
        if (res.data.code === 200) {
          if (res.data.data.records.length > 0) {
            this.popShow1 = true
          }
          const data = res.data.data.records
          this.draftObj = data
        } else {
          uni.showToast({ title: res.message || '获取草稿箱失败', icon: 'none' })
        }
      })

    },
    // 获取动态详情
    async getDynamicDetail(id) {
      this.loading = true
      try {
        const params = {
          momentId: id,
          // latitude: uni.getStorageSync('latitude'),
          // longitude: uni.getStorageSync('longitude'),
        }
        const res = await dynamicDetail(params)
        if (res.data.code === 200) {
          const data = res.data.data
          // 回显表单数据
          const resData = {
            momentId: data.id,
            title: data.title || '',
            content: data.content || '',
            location: data.location || '',
            address: data.address || '',
            latitude: data.latitude || '',
            longitude: data.longitude || '',
          }
          this.formData = { ...this.formData, ...resData }
          // 回显媒体文件
          if (data.mediaList && data.mediaList.length > 0) {
            const mediaType = data.mediaList[0].mediaType
            if (mediaType === 1) {
              // 图片类型
              this.mediaType = 'image'
              this.uploadApi = baseUrl + '/common/uploads'
              this.fileList = data.mediaList.map(item => item.mediaUrl)
              console.log(this.fileList)
            } else if (mediaType === 2) {
              // 视频类型
              this.mediaType = 'video'
              this.uploadApi = baseUrl + '/common/uploadVi'
              this.formData.videoUrl = data.mediaList[0].mediaUrl
              this.formData.videoCoverUrl = data.coverUrl
            }
          }
        } else {
          uni.showToast({ title: res.message || '获取详情失败', icon: 'none' })
        }
      } catch (error) {
        uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    onSuccess(reslut) {
      // 把服务端返回的图片地址添加到list中与组件数据同步
      if (reslut.code === 200) {
        const isVideo =
          reslut.url.endsWith('.mp4') ||
          reslut.url.endsWith('.mov') ||
          reslut.url.endsWith('.mkv') ||
          reslut.url.endsWith('.wmv')
        console.log(isVideo, 'isVideo')
           console.log(reslut, 'reslut')
        if (isVideo) {
       
          this.formData.videoUrl = baseUrl + reslut.url
          this.formData.videoCoverUrl = baseUrl + reslut.coverUrl
        } else {
          this.fileList.push(baseUrl + reslut.url)
        }
      } else {
        this.mediaType = 'all'
      }
    },
    // 确定媒体类型
    selectMediaType(type) {
      if (type === 'image') {
        this.uploadApi = baseUrl + '/common/uploads'
        this.mediaType = 'image'
      } else if (type === 'video') {
        this.uploadApi = baseUrl + '/common/uploadVi'
        this.mediaType = 'video'
      } else if (type === 'audio') {
        this.uploadApi = baseUrl + '/common/uploadVi'
        this.mediaType = 'audio'
      }
    },
    // 处理媒体类型取消事件
    onCancel() {
      this.uploadApi = baseUrl + '/common/uploads'
      this.mediaType = 'all'
    },
    delectVideo() {
      uni.showModal({
        title: '提示',
        content: '是否要删除此视频',
        success: res => {
          if (res.confirm) {
            this.formData.videoUrl = ''
            //this.formData.videoCoverUrl = ''
            // 重置媒体类型
            this.mediaType = 'all'
          }
        },
      })
    },
    // 选择发布地
    selectLocation() {
      uni.chooseLocation({
        success: res => {
          // console.log('选择的位置信息:', res)
          const locationData = {
            location: res.name,
            address: res.address,
            latitude: res.latitude,
            longitude: res.longitude,
          }
          this.formData = {
            ...this.formData,
            ...locationData,
          }
        },
      })
    },
    // 选择可见范围
    confirmScope(e) {
      this.formData.visibleRange = e.value[0]
      this.showScopePicker = false
    },
    // 检查是否有未保存的内容
    hasUnsavedContent() {
      return (
        this.formData.title ||
        this.formData.content ||
        this.fileList.length > 0 ||
        this.formData.videoUrl ||
        this.formData.location ||
        this.formData.visibleRange
      )
    },
    // 保存草稿
    cancel() {
      if (!this.hasUnsavedContent()) {
        uni.navigateBack()
        return
      } else {
        this.popShow = true
      }
    },
    //继续写
    goOnFun() {
      console.log(this.draftObj)
      const data = this.draftObj[0]
      // 回显表单数据
      const resData = {
        momentId: data.id,
        title: data.title || '',
        content: data.content || '',
        location: data.location || '',
        address: data.address || '',
        latitude: data.latitude || '',
        longitude: data.longitude || '',
      }
      this.formData = { ...this.formData, ...resData }

      // 回显媒体文件

      if (data.mediaType === 1) {
        // 图片类型
        this.mediaType = 'image'
        this.uploadApi = baseUrl + '/common/uploads'
        if (data.coverUrl.includes(',')) {
          this.fileList = data.coverUrl.split(',')

        } else {
          this.fileList = [data.coverUrl]
        }
      } else if (data.mediaType === 2) {
        // 视频类型
        this.mediaType = 'video'
        this.uploadApi = baseUrl + '/common/uploadVi'
        this.formData.videoUrl = data.coverUrl
        this.formData.videoCoverUrl = data.coverUrl
      }
      this.popShow1 = false

    },
    //重新写
    popClose() {
      this.popShow1 = false
      this.draftObj = {}
    },
    //删除草稿
    deleteFun() {

      this.popShow1 = false
      uni.showToast({ title: '草稿已删除', icon: 'none' })
    },
    // 提交动态
    async submit(type) {
      console.log(type)
      if (
        type == 'publish' &&
        (!this.formData.title ||
          !this.formData.content ||
          !this.formData.location 
        )//!this.formData.visibleRange
      
          // ||(this.mediaType == 1 && this.fileList.length === 0) ||
         // (this.mediaType == 2 && !this.formData.videoUrl)
      ) {
        uni.showToast({ title: '请完善动态内容', icon: 'none' })
        return
      } else if (type == 'draft') {
        if (!this.formData.title) {
          uni.showToast({ title: '动态标题不能为空', icon: 'none' })
          return
        }
      }

      // 检查是否有文件正在上传
      const uploadingFiles = this.fileList.filter(
        file => file.status === 'uploading'
      )
      if (uploadingFiles.length > 0) {
        uni.showToast({ title: '文件上传中，请稍候', icon: 'none' })
        return
      }

      this.loading = true

      try {
        // 提交数据
        const postData = {
          ...this.formData,
          isDraft: type == 'draft' ? 1 : 0,
          mediaType: this.formData.videoUrl ? 2 : this.fileList.length > 0 ? 1 : 3,
          imageUrls: this.fileList,
        }

        console.log('提交数据:', postData)

        // 调用发布接口
        let api = dynamicPublish
        if (this.formData.momentId) {
          api = dynamicEdit
        }
        const res = await api(postData)

        // 接口调用成功
        if (res.data.code == 200) {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
          })

          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            })
          }, 800)
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }
      } catch (error) {
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none',
        })
      } finally {
        this.loading = false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.media-area {
  
    margin: 20rpx 0 0 0;
    justify-content: space-between;
    position: relative;
    .add-image{
      border: 1px solid #f80000;
    }

    .icon-cuo {
        background-color: #0000009c;
        width: 40rpx;
        height: 40rpx;
        position: absolute;
        right: 0;
        top: 0;
        z-index: 999;
        border-bottom-left-radius: 12rpx;
        border-top-right-radius: 12rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        
    }



    .video-container {
        width: 340upx;
        height: 240upx;
        border-radius: 12rpx;
    }
}
.text-area {
  .textareaDef {
    padding: 24rpx 0 !important;

    .uni-textarea-placeholder {
      font-weight: 400;
      font-size: 28rpx;
      color: #86909C !important;

    }
  }


  .line {
    border-bottom: 1px solid #e5e5e5;
    background: #cccccc;
    border-radius: 4rpx;
  }
}

.content-area {
  .textareaDef {
    padding: 24rpx 0 !important;

    .uni-textarea-placeholder {
      font-weight: 400;
      font-size: 28rpx;
      color: #C9CDD4 !important;
      margin-top: -40rpx;
      text-align: left;

    }
  }


  ::v-deep .uni-textarea-wrapper {
    font-size: 28rpx;
    color: #1D2129;
  }
}

::v-deep .location-cell {
  border-top: 1px solid #E7E7E7;
  height: 88rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 12rpx 2rpx;
  display: flex;
  align-items: center;



  .u-cell__body {
    margin-left: 8rpx;
    padding: 0 !important;
  }

  .u-cell__title-text {
    font-weight: 400 !important;
    font-size: 28rpx !important;
    color: #1D2129 !important;

  }

  .u-cell__value {
    font-weight: 400 !important;
    font-size: 28rpx !important;
    color: #1D2129 !important;
  }

  .u-icon__icon--info {
    font-size: 28rpx !important;
    color: #86909C !important;
  }
}

.publish-container {
  height: 100vh;
  padding: 32rpx 32rpx 150rpx;
  background: #fff;
  box-sizing: border-box;
  overflow: scroll;
  font-family: PingFang SC, PingFang SC;

  .content-body {
    background: #fff;
    border-radius: 20rpx;
    margin-bottom: 24rpx;

    .tips {
      margin-top: 8rpx;
      margin-bottom: 24rpx;

      font-weight: 400;
      font-size: 24rpx;
      color: #C9CDD4;
    }
  }



  .footer-bar {
    width: 750rpx;
    height: 136rpx;
    background: #FFFFFF;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

::v-deep {
  .u-line {
    border: none !important;
  }

  .u-button__text {
    font-weight: 500;
    font-size: 32rpx;
  }

  .u-upload__wrap__preview {
    border-radius: 12rpx;
  }

  .cl-updata {
    .file-list .add-image {
      border: none;
      background-color: #F7F8FA;
      border-radius: 16rpx;

      ._image {
        width: 100%;
      }
    }

    .file-list-row .remove {
      background-color: transparent !important;

      .image[data-v-0b7ccd9e] {
        width: 24rpx;
        height: 24rpx;
        position: absolute;
        right: 4rpx;
        top: 4rpx;
      }
    }
  }
}

.popup-content {
  width: 630rpx;
  height: 380rpx;

  .popup-title {
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: bold;
    font-size: 32rpx;
    color: #000000;
    height: 92rpx;
    background: #e6f8f7;
    border-radius: 24rpx 24rpx 0rpx 0rpx;
  }

  .popup-desc {
    height: 168rpx;
    font-weight: 500;
    font-size: 28rpx;
    color: #333333;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .popup-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 120rpx;
    padding: 24rpx 60rpx;
    border-top: 2rpx solid #eeeeee;

    ::v-deep .u-botton {
      width: 225rpx;
      height: 68rpx;
    }
  }
}

::v-deep .popShow1 {
  .u-transition {
    background-color: rgba(0, 0, 0, 0.6) !important;
  }
}

.popup-content1 {

  width: 590rpx;

  //height: 380rpx;
  .popup-title {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 48rpx 48rpx 0rpx 48rpx;
    width: 590rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 500;
    font-size: 32rpx;
    color: #1D2129;
  }

  .popup-desc {
    margin-top: 20rpx;
    padding: 0rpx 48rpx;
    font-weight: 400;
    font-size: 28rpx;
    color: #86909C;
    text-align: left;
  }

  .popup-btn1 {
    margin-top: 32rpx;

    //height: 120rpx;
    //padding: 24rpx 60rpx;
    //border-top: 2rpx solid #eeeeee;
    .btn {
      border-top: 1rpx solid #E7E7E7;
      width: 100%;
      height: 90rpx;
      display: flex;
      justify-content: center;
      align-items: center;

      font-weight: 400;
      font-size: 30rpx;
      color: #1D2129;
    }
  }
}
</style>