<template>
  <view class="sharePosts">
    <zs-header title="研学心得" color="#000"></zs-header>
    <view class="inputPosts">
      
      <u--input border="none" fontSize="44rpx" placeholderClass="placeholderClass" :customStyle="{
        borderBottom: '1px solid #f0f0f0',
        height: '120rpx'
      }" placeholder="请填写标题" v-model="form.communityTitle"></u--input>

      <u--textarea autoHeight border="none" v-model="form.communityDetail" placeholder="快来记录你的心路历程"></u--textarea>
     
      <u-upload uploadIcon="plus" width="164" height="164" :fileList="fileList" @afterRead="afterRead"
        @delete="deletePic" name="1" :maxCount="9" @deletePic="deletePic" @oversize="oversize" accept="image"
        :maxSize="10485760" previewImage="true"></u-upload>
    </view>
    <view class="buy-box">
      <button class="buy-btn" :loading="loading" type="default" @click="handleUpLoad">确定</button>
    </view>
  </view>
</template>

<script>
import {
  uploadImg, finishUploadImg,
} from '@/api/common.js';
import { goodsSaveCommunityItem,goodsCommunityItemDetail } from "@/api/study"
import crypto from 'crypto-js';
import { Base64 } from 'js-base64';
export default {
  data() {
    return {
      fileList: [],
      loading: false,
      form: {
        id: '',
        orderNo: '',
        communityTitle: '',
        communityDetail: '',
        urls: []
      }
    };
  },
  methods: {
    oversize() {
      uni.showToast({
        title: '图片过大',
        icon: 'none'
      });
    },
    async afterRead(event) {
      console.log(event)
      const { file } = event
      this.fileList.push(
        {
          ...file,
          status: 'uploading',
          message: '上传中'
        }
      )

      uploadImg({
        "fineName": file.url.substr(file.url.lastIndexOf('/') + 1)
      }).then(res => {
        if (res.state == 'Success') {

          const date = new Date();
          date.setHours(date.getHours() + 1);
          const policyText = {
            expiration: date.toISOString(), // 设置policy过期时间。
            conditions: [
              // 限制上传大小。
              ["content-length-range", 0, 1024 * 1024 * 1024],
            ],
          };

          let fileName = file.url.substr(file.url.lastIndexOf('/') + 1);
          const host = 'https://' + res.content.bucket + '.' + res.content.endPoint;
          const policy = Base64.encode(JSON.stringify(policyText));
          const signature = crypto.enc.Base64.stringify(crypto.HmacSHA1(policy, res.content.token.accessKeySecret));;
          const filePath = file.url; // 待上传文件的文件路径。
          let paths = res.content.paths[0]
          // paths.pop()
          uni.uploadFile({
            url: host, // 开发者服务器的URL。
            filePath: filePath,
            name: 'file', // 必须填file。
            formData: {
              key: paths.join('/'),
              policy,
              success_action_status: '200', //让服务端返回200,不然，默认会返回204
              OSSAccessKeyId: res.content.token.accessKeyId,
              signature,
              'x-oss-security-token': res.content.token.securityToken // 使用STS签名时必传。
            },
            success: (res1) => {
              if (res1.statusCode === 200) {
                console.log('上传成功');
                // 告知服务器上传成功地址
                finishUploadImg(
                  [{
                    path: res.content.paths[0]
                  }]).then(msg => {
                    this.fileList.forEach((item, index) => {
                      if (item.thumb == file.thumb) {
                        this.fileList[index].status = 'success'
                        this.fileList[index].message = ''
                        this.fileList[index].url = host + '/' + paths.join('/')
                      }
                    })
                    console.log(this.fileList)
                  })
              }
            },
            fail: err => {
              console.log(err);
            }
          });
        }
      })


    },
    deletePic({ index }) {
      this.fileList.splice(index, 1)
    },
    handleUpLoad() {
      if (this.form.communityTitle && this.form.communityDetail) {
        this.form.urls = this.fileList.map(item => item.url)
        this.loading = true
        uni.showLoading({
          title: '保存中'
        });
        goodsSaveCommunityItem({
          ...this.form,
          urls: this.fileList.map(e => e.url)
        }).then(res => {
          this.loading = false
          uni.hideLoading();
          if (res.state == 'Success') {
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          }
        })

      } else {
        uni.showToast({
          title: '请填写标题和内容',
          icon: 'none'
        });
      }
    },
    getPostDetail(id,orderNo){
      goodsCommunityItemDetail(id).then(res=>{
        if(res.state == 'Success'){
          this.form = res.content
          this.form.id = id
          this.form.orderNo = orderNo
          this.fileList = res.content.urls.map(e=>{
            return {
              url:e,
              status:'success'
            }
          })
        } 
      })
    }
  },
  onLoad({ orderNo,id }) {
    this.form.orderNo = orderNo;
    if(id){
      this.getPostDetail(id,orderNo)
    }
  }
};
</script>

<style lang="scss" scoped>
.sharePosts {
  background: #FFFFFF;

  .inputPosts {
    margin-top: 174rpx;
    padding: 20rpx;
    border-top: 1px solid #f0f0f0;
  }
}

/deep/ .placeholderClass {
  color: #AAAAAA;
  font-size: 44rpx;
}

/deep/ .u-textarea {
  padding: 40rpx 0 !important;
}

.buy-box {
  position: fixed;
  bottom: 0%;
  left: 0%;
  width: 100%;
  background: #fff;
  padding: 10rpx 24rpx env(safe-area-inset-bottom);
  box-sizing: border-box;

  .buy-btn {
    width: 702rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: #3B83FF;
    border-radius: 40rpx;
    font-weight: 600;
    font-size: 28rpx;
    color: #FFFFFF;
  }

}
</style>
