// package_A/pages/volunteer-page/index.js
import { getOssAuth } from '../../../api/uploadOss.js'
import { Base64 } from 'js-base64'
const crypto = require('crypto-js')
import { applyVolunteer } from '../../../api/volunteer-service.js'
import {isPositiveInteger, isNoCharacters} from '../../../utils/check.js'
Page({

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

/**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getOssAuthForm()
        const openid = wx.getStorageSync('openid')
        let form = this.data.form
        form.openid = openid
        this.setData({form})
    },
    /* 获取图片上传鉴权 */
    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;
    },
    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)
        }
        }) 
    },
    // 输入
    bindValue(e) {
        let name = e.currentTarget.dataset.name;
        let form = this.data.form;
        form[name] = e.detail.value;
        this.setData({
          form,
        })
        this.validate(name)
    },
    // 选择时间
    selectDate(e) {
        let form = this.data.form
        form.activityDate = e.detail.value
        this.setData({form})
    },
    /* 表单上传 */
    submit(){
        if(this.data.checkAgree) {
            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 => {
                        // 设置文件上传路径
                        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.photoUrl = res.join(',')
                        applyVolunteer(form).then(res => {
                            if (res.code === 0) {
                                wx.showModal({
                                    title: '提交成功',
                                    confirmColor: '#3175E8',
                                    showCancel: false,
                                    content: '等待审核，审核通过后就可以获得积分。',
                                    success(res) {
                                        if(res.confirm) {
                                            wx.navigateBack()
                                        }
                                    }
                                })
                            }
                        }).finally(()=>{
                            wx.hideLoading();
                        })
                    }).catch(()=> {
                        wx.hideLoading()
                    })
                }
            })
        } else {
            wx.showToast({
                icon: 'none',
                title: '请先勾选用户服务协议以及隐私政策！',
            })
        }
    },
    /**
     * 同意用户协议
     */
    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',
        })
    }
})