// package_first/pages/AddPicture/index.js
import {api_TiktokAdd} from  '../../../api/attention.js';
import {getOssAuth} from '../../../api/uploadOss.js'
import {Base64} from 'js-base64'
const crypto = require('crypto-js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        ossForm: {},
        imageList:[],
        imagePreviewList: [],
        formRules: {
            imageList: {
                validator: function (value) {
                  return value.length!=0;
                },
                warning: false
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getOssAuthForm()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    // 表单项验证
    validate(name) {
        let formRules = this.data.formRules;
        let validator = formRules[name].validator
        let result
        if(name === 'imageList') {
            result = validator ? !validator(this.data.imageList) : false
        } else {
            result = validator ? !validator(this.data.form[name]) : false;
        }
        formRules[name].warning = result
        this.setData({formRules})
        return result
    },
       /* 获取图片上传鉴权 */
       getOssAuthForm() {
        let that = this
        getOssAuth().then((res)=> {
            let client = {
                region: 'oss-cn-shanghai',
                secure: true,
                accessKeyId: res.accessKeyId,
                accessKeySecret: res.accessKeySecret,
                securityToken: res.securityToken,
                bucket: 'ta-tech-image'
            }
            // 计算签名
            function computeSignature(accessKeySecret, canonicalString) {
                return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
            }
            const date = new Date();
            date.setHours(date.getHours() + 1);
            const policyText = {
                expiration: date.toISOString(), // 设置policy过期时间。
                conditions: [
                    // 限制上传大小。
                    ["content-length-range", 0, 1024 * 1024 * 1024],
                ],
            };
            // 获取签名
            const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
            const signature = computeSignature(client.accessKeySecret, policy)
            let ossForm = that.data.ossForm
            ossForm = {
                OSSAccessKeyId: client.accessKeyId,
                signature,
                policy,
                SecurityToken: client.securityToken 
            }
            that.setData({ossForm})
        })
    
    },
    /* 上传图片 */
    uploadImage(){
        wx.chooseMedia({
          count: 5 - this.data.imageList.length, // 最多可以选择的图片张数，默认9
          mediaType: ['image'], // 图片
          sizeType: ['original'], // original 原图，compressed 压缩图，默认二者都有
          sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
          success:(res) =>{
              const list = res.tempFiles.map((item)=> {
                  return item.tempFilePath
              })
              // success
              let imagePreviewList = this.data.imagePreviewList.concat(list)
              let imageList = this.data.imageList.concat(list);
              this.setData({ imageList, imagePreviewList })
            //   this.validate('imageList')
          },
          fail: (e) => {
              console.log(e);
          }
        })
    },
    // 删除图片
    deleteImage(e) {
        let index = this.getCurrentData(e);
        let imageList = this.data.imageList
        imageList.splice(index, 1)
        let imagePreviewList = this.data.imagePreviewList
        imagePreviewList.splice(index, 1)
        this.setData({ imageList, imagePreviewList })
        this.validate('imageList')
    },
    getCurrentData(e) {
        return e.currentTarget.dataset.current;
    },
// 表单验证
validateForm() {
    return new Promise((resolve, reject) => {
      try {
        let formRules = this.data.formRules;
        let result = false;
        for (let key in formRules) {
          let temp = this.validate(key)
          if (temp) {
            result = temp
          }
        }
        resolve(!result)
      } catch (e) {
        reject(e)
      }
    })
},
    /* 表单上传 */
    submit(){
        this.validateForm().then(res => {
            let ossForm = this.data.ossForm
            let temp = []
            if (this.data.imageList.length > 0) {
                wx.showLoading({title:"上传中",mask:true})
                temp = this.data.imageList.map(item => {
                    console.log(item);
                    // 设置文件上传路径
                    const randomString = Math.random().toString(36).slice(2)
                    const timestamp = new Date().getTime()
                    const key = `imagedir/${randomString}_${timestamp}.png`
                    // 上传图片
                    return new Promise((resolve, reject)=> {
                        wx.uploadFile({
                            url: 'https://ta-tech-image.oss-cn-shanghai.aliyuncs.com',
                            filePath: item,
                            name: 'file',
                            formData: {
                                key,
                                OSSAccessKeyId: ossForm.OSSAccessKeyId,
                                signature: ossForm.signature,
                                policy: ossForm.policy,
                                'x-oss-security-token': ossForm.SecurityToken 
                            },
                            success: (res)=> {
                                if(res.statusCode === 204) {
                                    // 上传成功，将图片路径resolve出去
                                    resolve(key)
                                    wx.showToast({
                                        title: '您的图片已提交',
                                        icon:'none'
                                    })
                                    setTimeout(()=>{
                                        wx.redirectTo({
                                          url: '../../pages/AttentionMethod/index',
                                        })
                                    },2000)
                                } else {
                                    wx.showToast({
                                        title: '图片上传失败',
                                    })
                                    reject('图片上传失败')
                                }
                            },
                            fail: (e)=> {
                                console.log(e);
                                reject('图片上传失败')
                            }
                        })
                    })
                })
                Promise.all(temp).then((res)=> {
                    let tenantObj = wx.getStorageSync('tenant')
                    let openid = wx.getStorageSync('openid')
                    let data = {
                        openid:openid,
                        imageUrl:res.join(','),
                        tenantId:tenantObj.tenantId
                    }
                    api_TiktokAdd(data).then(res => {
                        if (res.code === 0) {
                            wx.showToast({
                                title: '您的图片已提交',
                                icon:'none'
                            })
                            setTimeout(()=>{
                                wx.navigateBack()
                            },2000)
                        }
                    }).finally(()=>{
                        wx.hideLoading();
                    })
                }).catch(()=> {
                    wx.hideLoading()
                })
            }
        })
    }
    
})