<template>
  <view class="publish-container">
    <view class="content-body">
      <view class="text-area">
        <u--textarea
          v-model="formData.title"
          placeholder="请输入标题..."
          maxLength="20"
          border="none"
          height="20"
        ></u--textarea>
        <view class="line"></view>
      </view>
      <view class="content-area">
        <u--textarea
          v-model="formData.content"
          placeholder="记录美好生活时刻..."
          maxLength="300"
          border="none"
          height="150"
          count
        ></u--textarea>
      </view>
      <view class="media-area">
        <view v-if="formData.videoUrl">
          <uni-icons
            class="icon iconfont icon-cuo"
            type="trash-filled"
            size="20"
            @tap="delectVideo"
          ></uni-icons>
          <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/discover/ic_upload.png"
          deleteImg="/static/discover/ic_delete.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">
      <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="返回"
        shape="circle"
        customStyle="height: 38px; font-size: 18px; margin-right: 20rpx;"
        @click="cancel"
      ></u-button>
      <u-button
        text="立即发布"
        color="linear-gradient(80deg,#02f6c1 0%,#07cdc4 100%)"
        shape="circle"
        customStyle="height: 38px; font-size: 18px;"
        @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>
  </view>
</template>

<script>
import { baseUrl } from '@/common/config.js'
import { dynamicPublish, dynamicEdit, dynamicDetail } from '@/api/dynamic'
import clUpload from '@/components/cl-upload/cl-upload/cl-upload.vue'
export default {
  components: { clUpload },
  data() {
    return {
      loading: false,
      showScopePicker: false,
      popShow: false,
      type: '',
      formData: {
        title: '',
        content: '',
        location: '',
        address: '',
        latitude: '',
        longitude: '',
        visibleRange: '',
        videoUrl: '',
        videoCoverUrl: '',
        imageUrls: [],
      },
      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)
    }
  },
  methods: {
    // 获取动态详情
    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 || '',
            visibleRange: data.visibleRange === 1 ? '公开' : '',
          }
          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)
            } 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')
        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'
      }
    },
    // 处理媒体类型取消事件
    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
      }
    },
    popClose() {
      this.popShow = false
      uni.navigateBack()
    },
    save() {
      this.popShow = false
      this.submit('draft')
    },
    async submit(type) {
      if (
        type == 'publish' &&
        (!this.formData.title ||
          !this.formData.content ||
          !this.formData.location ||
          (this.mediaType == 1 && this.fileList.length === 0) ||
          (this.mediaType == 2 && !this.formData.videoUrl) ||
          !this.formData.visibleRange)
      ) {
        uni.showToast({ title: '请完善动态内容', icon: 'none' })
        return
      } else if (type == 'draft') {
        if (!this.formData.title) {
          uni.showToast({ title: '动态标题不能为空', icon: 'none' })
          return
        }
        if (!this.formData.visibleRange) {
          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 : 1,
          imageUrls: this.fileList,
          visibleRange: this.formData.visibleRange ? 1 : '',
        }

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

        // 调用发布接口
        const api = this.type === 'edit' ? dynamicEdit : dynamicPublish
        const res = await api(postData)

        // 接口调用成功
        if (res.data.code == 200) {
          uni.showToast({
            title: type === 'publish' ? '发布成功，等待审核' : '保存草稿成功',
            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>
.publish-container {
  height: 100vh;
  padding: 32rpx 32rpx 150rpx;
  background: #f8f8f8;
  box-sizing: border-box;
  overflow: scroll;
  font-family: PingFang SC, PingFang SC;

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

    .text-area {
      font-weight: 500;
      font-size: 32rpx;
      color: #999999;

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

    .content-area {
      ::v-deep .uni-textarea-wrapper {
        font-size: 24rpx;
      }
    }

    .media-area {
      margin: 20rpx 0 20rpx;
      justify-content: space-between;
      position: relative;

      .icon-cuo {
        position: absolute;
        left: 295upx;
        top: 5upx;
        color: #ffffff !important;
        z-index: 999;
        border-top-right-radius: 20upx;
        border-bottom-left-radius: 20upx;
      }

      .video-container {
        width: 340upx;
        height: 240upx;
        border-radius: 12rpx;
      }
    }

    .tips {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 20rpx;
    }
  }

  .location-cell {
    background: #fff;
    border-radius: 20rpx;
    padding: 12rpx 2rpx;
  }

  .footer-bar {
    background: #f8f8f8;
    box-shadow: none;
    padding: 0 32rpx 20rpx;
  }
}

::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;

      ._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;
    }
  }
}
</style>