// package_mine/pages/userInfo/index.js
import {Base64} from 'js-base64'
import {getOssAuth} from '../../../api/uploadOss.js'
const crypto = require('crypto-js')
import {uploadUserInfo} from '../../../api/mine.js'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        ossForm: {},
        form: {},
        image: '',
        formRules: {
            nickname: {
                validator: function (value) {
                  return value;
                },
                warning: false
            },
            headimgurl: {
                validator: function (value) {
                  return value;
                },
                warning: false
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const form = wx.getStorageSync('userInfo')
        this.setData({form})
    },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getOssAuthForm()
    },
    /**
     * 获取上传oss参数
     */
    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})
        })
    
    },

    // 表单项验证
    validate(name) {
        let formRules = this.data.formRules;
        let validator = formRules[name].validator
        let 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)
    },

    // 点击相机
    uploadAvatar() {
        wx.chooseMedia({
            count: 1, // 最多可以选择的图片张数，默认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 form = this.data.form
                form.headimgurl = list[0]
                this.setData({ form, image: list[0] })
                this.validate('headimgurl')
            },
            fail: (e) => {
                console.log(e, '取消选择');
            }
        })
    },
    /**
     * 图片上传oss
     */
    uploadToOss(url) {
        const ossForm = this.data.ossForm
        // 设置文件上传路径
        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: url,
                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('图片上传失败')
                }
            })
        })
    },

    /* 表单上传 */
    submit(){
        this.validateForm().then(res => {
            if(res) {
                const image = this.data.image
                let params = {}
                params.id = this.data.form.id
                params.nickname = this.data.form.nickname
                if (image) {
                    wx.showLoading({title:"上传中",mask:true})
                    this.uploadToOss(image).then(item=> {
                        params.headimgurl = item
                        uploadUserInfo(params).then(i => {
                            if (i.code === 0) {
                                wx.switchTab({
                                    url: '/pages/mine/index',
                                })
                            }
                        }).finally(()=>{
                            wx.hideLoading();
                        })
                    }).catch(()=> {
                        wx.hideLoading();
                    })
                } else {
                    uploadUserInfo(params).then(i => {
                        if (i.code === 0) {
                            wx.switchTab({
                                url: '/pages/mine/index',
                            })
                        }
                    }).finally(()=>{
                        wx.hideLoading();
                    })
                }
            }
        })
    }

})