// package_A/work/index.js
import {getOssAuth} from '../../../api/uploadOss.js'
import {feedbackPosition} from '../../../api/feeddback.js'
import {Base64} from 'js-base64'
import {isPositiveInteger} from '../../../utils/check.js'
const crypto = require('crypto-js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        checkAgree: false, // 是否勾选用户协议
        form: {},
        ossForm: {},
        imagePreviewList: [], // 上传图片预览列表
        imageList: [], // 图片列表
        // 表单验证
        formRules: {
            location: {
                validator: function (value) {
                    return value;
                },
                warning: false
            },
            feedbackDesc: {
                validator: function (value) {
                  return value;
                },
                warning: false
            },
            feedbackName: {
                validator: function (value) {
                  return value;
                },
                warning: false
            },
            feedbackPhone: {
                validator: function (value) {
                  return value && isPositiveInteger(value);
                },
                warning: false
            },
            imageList: {
                validator: function (value) {
                  return value.length!=0;
                },
                warning: false
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let data = JSON.parse(options.data)
        let form = this.data.form
        form.streamName = data.name
        form.streamId = data.id
        this.setData({form})
    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getOssAuthForm()
        const openid = wx.getStorageSync('openid')
        let form = this.data.form
        form.openid = openid
        this.setData({form})
    },
    bindValue(e) {
        let name = e.currentTarget.dataset.name;
        let form = this.data.form;
        form[name] = e.detail.value;
        this.setData({
          form,
        })
        this.validate(name, e.detail.value)
      },
      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
      },
      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)
          }
        })
      },
    /* 获取图片上传鉴权 */
    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.chooseImage({
          count: 5 - this.data.imageList.length, // 最多可以选择的图片张数，默认9
          mediaType: ['image'], // 图片
          sizeType: ['original'], // original 原图，compressed 压缩图，默认二者都有
          sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
          success:(res) =>{
              // success
              let imagePreviewList = this.data.imagePreviewList.concat(res.tempFilePaths)
              let imageList = this.data.imageList.concat(res.tempFilePaths);
              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;
    },

    /**
     * 选择位置
     */
    selectLocation() {
        let location = wx.getStorageSync('location')
        wx.chooseLocation({
          latitude: location.latitude,
          longitude: location.longitude,
          success: (res)=>{
              let form = this.data.form
              form.location = res.address
              form.latitude = res.latitude
              form.longitude = res.longitude
              this.setData({form})
              this.validate('location')
          },
          fail(e) {
              console.log(e);
          }
        })
    },
    /**
     * 同意用户协议
     */
    checkBoxChange() {
        let checkAgree = this.data.checkAgree
        this.setData({
            checkAgree: !checkAgree
        })
    },
    // 用户服务协议
    showAgree() {
        wx.navigateTo({
          url: '/package_A/pages/agree/index',
        })
    },
    // 隐私政策
    showConceal() {
        wx.navigateTo({
            url: '/package_A/pages/conceal/index',
        })
    },
    /**
     * 图片上传到oss
     */
    /* 表单上传 */
    submit(){
        this.validateForm().then(res => {
            if(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 => {
                        // 设置文件上传路径
                        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)
                                    } else {
                                        wx.showToast({
                                            title: '图片上传失败',
                                        })
                                        reject('图片上传失败')
                                    }
                                },
                                fail: (e)=> {
                                    console.log(e);
                                    reject('图片上传失败')
                                }
                            })
                        })
                    })
                    Promise.all(temp).then((res)=> {
                        let form = this.data.form
                        form.feedbackUrl = res.join(',')
                        feedbackPosition(form).then(res => {
                            if (res.code === 0) {
                                wx.reLaunch({
                                    url: '/package_A/pages/submitSuccess/index',
                                })
                            }
                        }).finally(()=>{
                            wx.hideLoading();
                        })
                          
        
                    }).catch(()=> {
                        wx.hideLoading()
                    })
                }
            }
        })
    
        
    }
    
})