const Parse = getApp().Parse;
const app = getApp();
const company = getApp().globalData.company;
let navigationBarHeight = getApp().globalData.statusBarHeight + 44;
const qiniuUploader = require("../../../../../../utils/qiniuUploader");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pageType: 'add',
        routeId: '0ePMS1OGU7',
        roomId: null,
        storeId: null,
        oldimages:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let {
            roomId,
            storeId
        } = options
        console.log(roomId);
        if (!storeId && !roomId) {
            wx.navigateTo({
                url: `/nova-tourism/pages/index/index`
            })
        }
        if (!storeId && roomId) {
            let pageType = 'edit'
            let store = wx.getStorageSync('store')
            this.setData({
                roomId,
                storeId: store.objectId,
                pageType
            })
        } else {
            this.setData({
                roomId,
                storeId
            })
        }
        this.initData()


    },
    async initData() {
        let store;
        let room;
        let formData;
        let route = await this.getRoute()
        if (this.data.pageType == 'add') {
            store = await this.getStore()
        } else if (this.data.pageType == 'edit') {
            room = await this.getRoom()
        }
        if (!store && !room) {
            wx.showToast({
                title: '该店铺/房型不存在',
                icon: 'none'
            })
            setTimeout(() => {
                wx.navigateTo({
                    url: `/nova-tourism/pages/my/merchant/room-manage/room-edit/index`
                })
            }, 1000)
        }
        this.setData({
            store,
            route,
            room,
        })
        formData = route['editFields'].reduce((obj, cur, index) => {
            // obj[cur["key"]] = cur;
            switch (cur["type"]) {
                case 'String':
                    obj[cur["key"]] = room ? room[cur["key"]] : '';
                    break;
                case 'Number':
                    obj[cur["key"]] = room ? room[cur["key"]] : 0;
                    break;
                case 'Boolean':
                    obj[cur["key"]] = room ? room[cur["key"]] : false;
                    break;
                case 'Array':
                    obj[cur["key"]] = room ? room[cur["key"]] : [];
                    if (cur["view"] == 'edit-filemanager') {
                        obj[cur["key"]] = [];
                        if (room) {
                            room[cur["key"]].forEach(item => {
                                obj[cur["key"]].push({
                                    "url": item
                                })
                            })
                        }
                    }
                    break;
                case 'GeoPoint':
                    obj[cur["key"]] = room ? room[cur["key"]] : null;
                    break;
                case 'Pointer':
                    obj[cur["key"]] = room ? room[cur["key"]] : null;

                    break;
                default:
                    break;
            }

            return obj;
        }, {});
        this.setData({
            formData
        })
        // 富文本回显
        if (this.data.room) {
            this.data.route['editFields'].forEach(field => {
                if (field["view"] == 'editor-tinymce') {
                    // this.selectComponent(`#editor${field["key"]}`).setHtml(room[field["key"]] || '');
                }
            })
        }
        // 获取七牛参数
        this.getQiniuOption()

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    async getQiniuOption() {
        let uploadData = await this.getUptoken()
        if (uploadData) {
            this.setData({
                uploadURL: uploadData.zoneUrl,
                domain: uploadData.domain,
                uptokenURL: uploadData.uptoken,
            })
        }
    },
    getUptoken() {
        return Parse.Cloud.run('qiniu_uptoken', {
            company: company
        })
    },
    async getStore() {
        let Store = new Parse.Query('ShopStore')
        let store = await Store.get(this.data.storeId)
        if (store && store.id) {
            store = store.toJSON()
            return store;
        } else {
            return false;
        }
    },
    async getRoom() {
        let Room = new Parse.Query('ShopRoom')
        let room = await Room.get(this.data.roomId)
        if (room && room.id) {
            room = room.toJSON()
            console.log('房间', room);
            return room;
        } else {
            return false;
        }
    },
    async getRoute() {
        let DevRoute = new Parse.Query('DevRoute')
        let route = await DevRoute.get(this.data.routeId)
        if (route && route.id) {
            route = route.toJSON()
            return route;
        } else {
            return false;
        }
    },
    onChange(event) {
        let field = event.currentTarget.dataset.field;
        let type = event.currentTarget.dataset.type;
        let value = event.detail.value;
        switch (type) {
            case 'String':
                this.data.formData[field] = value;
                break;
            case 'Number':
                this.data.formData[field] = +value;
                break;
            case 'Boolean':
                this.data.formData[field] = event.detail;
                this.setData({
                    formData: this.data.formData
                });
                break;
            default:
                break;
        }
    },
    showTagEdit(event) {
        let field = event.currentTarget.dataset.field;
        let name = event.currentTarget.dataset.name;
        let that = this;
        wx.showModal({
            title: `添加${name}`,
            content: ``,
            editable: true,
            success(res) {
                if (res.confirm) {
                    that.data.formData[field].push(res.content)
                    that.setData({
                        formData: that.data.formData
                    })
                    console.log('用户点击确定')
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    tagClose(event) {
        let field = event.currentTarget.dataset.field;
        let index = event.currentTarget.dataset.index;
        this.data.formData[field].splice(index, 1)
        this.setData({
            formData: this.data.formData
        })
    },
    changeFile(event) {
        let field = event.currentTarget.dataset.field;
        let fileList = event.detail
        fileList = fileList.map(file => file.url)
        this.data.formData[field] = fileList;
    },
    chooseGeoPoint(event) {
        let field = event.currentTarget.dataset.field;
        wx.chooseLocation({
            latitude: 0,
            longitude: 0,
            success: (res) => {
                let {
                    latitude,
                    longitude,
                    address,
                    name
                } = res;
                let locations = new Parse.GeoPoint(latitude, longitude)
                this.data.formData[field] = locations
                this.data.formData['address'] = address + name
                //   this.data.formData['address'] = address
                this.setData({
                    formData: this.data.formData,
                })
            }
        })
    },
    // getHtml(event) {
    //     let field = event.currentTarget.dataset.field;
    //     let html = event.detail.content.html;
    //     this.data.formData[field] = html;
    // },
    // insertImage(event) {
    //     let field = event.currentTarget.dataset.field;
    //     let that = this;
    //     wx.chooseImage({
    //         count: 1,
    //         success(res) {
    //             // 本地测试图片插入
    //             // this.selectComponent('#hf_editor').insertSrc(res.tempFilePaths[0]);
    //             // that.selectComponent(`#editor${field}`).insertSrc(res.tempFilePaths[0])
    //             let tempFilePaths = res.tempFilePaths[0];
    //             qiniuUploader.upload(
    //                 tempFilePaths,
    //                 (res) => {
    //                     let img = res.imageURL;
    //                     that.selectComponent(`#editor${field}`).insertSrc(img); //调用组件insertSrc方法
    //                 },
    //                 (error) => {
    //                     console.log("error: " + error);
    //                 }, {
    //                     region: "SCN",
    //                     uploadURL: that.data.uploadURL,
    //                     domain: that.data.domain,
    //                     uptoken: that.data.uptokenURL,
    //                 }
    //             );
    //         }
    //     })
    // },
    async submit() {
        let checked = await this.checkForm()
        if (!checked) {
            return
        }
        //当没有更新图片时执行
        this.data.formData.images.forEach((img)=>{
            if(img.url){
                this.data.oldimages.push(img.url)
            }
        })
        if (this.data.oldimages.length != 0) {
            this.data.formData['images'] = this.data.oldimages; // 保持原有图片
        }
        let room = await this.setRoom()
        console.log(room);
        if (room && room.id) {
            wx.showToast({
                title: '操作成功',
                icon: 'none'
            })
            setTimeout(()=>{
                wx.navigateBack({
                    delta: 1 // 返回上一页
                });
            },1000)
        }
    },
    async checkForm() {
        let formData = this.data.formData;
        let editFields = this.data.route.editFields;
        for (let index = 0; index < editFields.length; index++) {
            const field = editFields[index];
            if (field.required && (!formData[field.key] || formData[field.key] == '' || formData[field.key] == [])) {
                wx.showToast({
                    title: `请填写${field.name}`,
                    icon: 'none'
                })
                return false;
            }
        }

        return true;
    },
    async setRoom() {
        let Room
        if (this.data.roomId) {
            let ShopRoom1 = new Parse.Query('ShopRoom');
            ShopRoom1.equalTo('company', company);
            ShopRoom1.equalTo('objectId', this.data.roomId);
            Room = await ShopRoom1.first();
        } else {
            let ShopRoom = Parse.Object.extend("ShopRoom");
            Room = new ShopRoom()
        }
        Room.set('isEnabled',true)
        Room.set(this.data.formData)
        Room.set("shop", {
            "__type": "Pointer",
            "className": "ShopStore",
            "objectId": this.data.storeId
        })
        Room.set("company", {
            "__type": "Pointer",
            "className": "Company",
            "objectId": company
        })
        return await Room.save()
    },


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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})