import {
    getLoraList,
    createAiImg,
    getTaskResult,
} from '~/api/avatar'
import {
    userEvent
} from '~/api/global'
Page({
    data: {
        templates: [],
        loading: false,
        active: '',
        artistic: '',
        original: ''
    },
    onLoad() {
        getLoraList().then(res => {
            this.setData({
                templates: res.loras,
                active: res.loras[0] ? res.loras[0].lora_id : ''
            })
        })
        userEvent({
            action: 'AI_LOGIN'
        })
    },
    async selectTemplate({
        currentTarget
    }) {
        if (this.data.loading) {
            return
        }
        this.setData({
            active: currentTarget.dataset.id
        })
        if (this.data.original) {
            this.createAiImg()
        }
        await userEvent({
            action: "AI_STYLE",
            targetContent: currentTarget.dataset.name
        })
    },
    uploadImg() {
        if (this.data.loading) {
            return
        }
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sizeType: ['compressed'], //  original 原图；compressed 压缩图
            sourceType: ['album', 'camera'],
            camera: 'back',
            success: (res) => {
                this.cropper = this.selectComponent("#cropper");
                this.cropper.init({
                    imgPath: res.tempFiles[0].tempFilePath, //imgPath是需要裁剪图片的图片路径，只支持本地或临时路径
                    success: (imgUrl) => {
                        wx.getFileSystemManager().readFile({
                            filePath: imgUrl,
                            encoding: "base64",
                            success: res => {
                                //返回base64格式
                                var base64Str = 'data:image/png' + ';base64,' + res.data
                                this.setData({
                                    artistic: base64Str,
                                    original: base64Str
                                })
                                this.createAiImg()
                                userEvent({
                                    action: "AI_PHOTO"
                                })
                            },
                            fail: err => {
                                console.log(err)
                            }
                        })
                    },
                    fail(error) {
                        console.log(error) //有两种:cancel代表点击了叉，fail代表wx.canvasToTempFilePath生成图片失败
                    }
                });
            }
        })
    },
    createAiImg() {
        if (!this.data.original || this.data.loading) {
            return
        }
        this.setData({
            loading: true
        })
        createAiImg({
            "width": 512, //生成图片宽度
            "height": 512, //生成图片高度
            "n_samples": 1, //生成图片数量
            "controlnet_input_image_base64": this.data.original, //控制图片base64编码
            "style_id": this.data.active //控制风格id
        }).then(res => {
            this.getAiImg(res.uuid)
        }).catch(() => {
            this.setData({
                loading: false
            })
            wx.showToast({
                title: '网络异常请重试',
                icon: 'none',
                duration: 2500
            })
        })
    },
    async getAiImg(uuid) {
        let res = await getTaskResult({
            uuid
        })
        if (res.data.status != 2) {
            setTimeout(() => {
                this.getAiImg(uuid)
            }, 2500)
        } else {
            this.setData({
                loading: false,
                artistic: res.data.generated_imgs[0]
            })
        }
    },
    downloadImg() {
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.writePhotosAlbum']) {
                    this.base64ToImg()
                } else {
                    wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success: () => {
                            this.base64ToImg()
                        },
                        fail(res) {
                            wx.showModal({
                                title: '无法保存到相册',
                                content: '点击右上角浮点按钮->设置，进行授权',
                                confirmText: '我知道了',
                                showCancel: false,
                            })
                        }
                    })
                }
            }
        })
    },
    base64ToImg() {
        const base64 = this.data.artistic; //base64格式图片
        if (!base64 || this.data.loading) {
            return
        }
        const time = new Date().getTime();
        const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "" + ".png";
        //如果图片字符串不含要清空的前缀,可以不执行下行代码.
        const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
        const file = wx.getFileSystemManager();
        file.writeFileSync(imgPath, imageData, "base64");
        wx.saveImageToPhotosAlbum({
            filePath: imgPath,
            success: async (res) => {
                wx.showModal({
                    title: '照片已保存至相册',
                    content: '快去分享给小伙伴吧',
                    confirmText: '我知道了',
                    showCancel: false,
                })
                await userEvent({
                    action: 'AI_SAVE'
                })
            }
        })
    },
    onShareAppMessage() {
        userEvent({
            action: 'AI_SHARE'
        })
        return {
            title: '玩转AI头像',
            path: '/pages/index/index',
        }
    }
})