let Parse = getApp().Parse;
const company = getApp().globalData.company
const qiniuUploader = require("../../../../../../utils/qiniuUploader");
Page({

    /**
     * 页面的初始数据
     */
    data: {

        imageList: [], //商店首页
        licenseList: [], //店铺图片
        merchant: null,
        store: null,
        stores: null,
        perCapita: null,
        cover: '',
        image: [],
        storeName: null,
        perCapita: null,
        desc: null,
        name: null,
        workingTime: null,
        uploadURL: null,
        domain: null,
        uptokenURL: null,
        html: null,
        content: null,
        id: null,
        address: '',
        locations: null,
    },
    // getHtml(e) { //从组件获取值
    //     let html = e.detail.content.html
    //     console.log(html);
    //     // this.setData({ html: html })
    //     // let field = event.currentTarget.dataset.field;
    //     // let html = event.detail.content.html;
    //     this.setData({
    //         html: html
    //     })
    // },

    // insertImage() { //图片上传插入示例
    //     let that = this
    //     wx.chooseImage({
    //         count: 1,
    //         success(res) {
    //             // 本地测试图片插入
    //             // this.selectComponent('#hf_editor').insertSrc(res.tempFilePaths[0]);
    //             // console.log(res.tempFilePaths[0]);
    //             let tempFilePaths = res.tempFilePaths[0];
    //             console.log(tempFilePaths);


    //             qiniuUploader.upload(
    //                 tempFilePaths,
    //                 (res) => {
    //                     let img = res.imageURL;
    //                     that.selectComponent('#hf_editor').insertSrc(img); //调用组件insertSrc方法
    //                 },
    //                 (error) => {
    //                     console.log("error: " + error);
    //                 }, {
    //                     region: "SCN",
    //                     uploadURL: that.data.uploadURL,
    //                     domain: that.data.domain,
    //                     uptoken: that.data.uptokenURL,
    //                 }
    //             );
    //         }
    //     })
    // },

    changeFile(e) {
        if (e.detail && e.detail.length > 0) {
            this.setData({
                cover:`${e.detail[0].url}`
            })
        } else {
            this.setData({
                cover: ''
                // cover:this.data.imageList[0].url
            })
        }
    },
    changeFiles(e) {
        if (e.detail && e.detail.length > 0) {
            this.setData({
                image: e.detail
            })
            console.log('图片', this.data.image);
        } else {
            this.setData({
                image: []
            })
        }
    },

    blur(e) {
        let name = e.currentTarget.dataset.name
        this.setData({
            [name]: e.detail.value
        })
    },
    mobile() {
        let id = this.data.store.objectId
        console.log(id);
        wx.navigateTo({
            url: '../account/mobile/index?id=' + id
        });

    },
    password() {
        let id = this.data.store.objectId
        console.log(id);
        wx.navigateTo({
            url: '../account/password/index?id=' + id
        });
    },
    async determine() {
        let image = []
        if (this.data.image[0].url) {
            for (let index = 0; index < this.data.image.length; index++) {
                let item = this.data.image[index];
                image.push(item.url)
            }
            // 设置图片格式判断
            console.log('店铺图片', image);
        } else {
            image = this.data.image
        }
        console.log(this.data.name, image, this.data.storeName, this.data.perCapita, this.data.desc, this.data.workingTime, this.data.html, this.data.locations);
        let query = new Parse.Query("ShopStore")

        let ShopStore = await query.get(this.data.id)
        // ShopStore.set("perCapita", this.data.perCapita)
        ShopStore.set("name", this.data.name)
        ShopStore.set("cover", this.data.cover)
        ShopStore.set("image", image)
        if (this.data.locations&&this.data.address) {
            ShopStore.set("location", this.data.locations)
            ShopStore.set("storeAddress", this.data.address)
        } else {
            wx.showToast({
                title: '请选择民宿地址',
                icon: 'none'
            })
            return
        }
        ShopStore.set("storeName", this.data.storeName)
        if (Number(this.data.perCapita)) {
            ShopStore.set("perCapita", Number(this.data.perCapita))
        } else {
            wx.showToast({
                title: '请输入正确人均消费',
                icon: 'none'
            })
            return
        }
        ShopStore.set("desc", this.data.desc)
        ShopStore.set("workingTime", this.data.workingTime)
        // ShopStore.set("content", this.data.html)
        ShopStore.save().then(res => {
            console.log(res)
            wx.showToast({
                title: '修改成功',
                icon: 'none'
            })
            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                });
            }, 1000)
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {



        let merchant = wx.getStorageSync('merchant'); //用户
        let ShopStore = new Parse.Query('ShopStore')
        ShopStore.notEqualTo('isDeleted', "true")
        ShopStore.equalTo('company', company)
        ShopStore.include('user')
        ShopStore.equalTo('user', merchant.objectId)
        let store = await ShopStore.first()
        store = store.toJSON()
        console.log(store);
        let imageList = []
        let licenseList = []
        // store.cover[0].forEach(i => {
        imageList.push({
            url: store.cover
        })
        // })
        console.log(imageList);
        store.image.forEach(i => {
            licenseList.push({
                url: i
            })
        })
        this.setData({
            imageList: imageList,
            store: store,
            cover: store.cover,
            image: store.image,
            // perCapita: store.perCapita,
            storeName: store.storeName,
            perCapita: store.perCapita,
            desc: store.desc,
            name: store.name,
            workingTime: store.workingTime,
            html: store.content,
            id: store.objectId,
            licenseList: licenseList,
            locations: store.location,
            address:store.storeAddress
        })
        console.log('首页', this.data.locations);
        // this.Getlocation()
        // this.selectComponent('#hf_editor').setHtml(this.data.html);
        this.getQiniuOption()
    },
    async getQiniuOption() {
        let uploadData = await this.getUptoken()
        if (uploadData) {
            this.setData({
                uploadURL: uploadData.zoneUrl,
                domain: uploadData.domain,
                uptokenURL: uploadData.uptoken,

            })
        }
        console.log(this.data.uploadURL, this.data.domain, this.data.uptokenURL);
    },
    getUptoken() {
        return Parse.Cloud.run('qiniu_uptoken', {
            company: company
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },
    //选择地理位置
    chooseGeoPoint() {
        wx.chooseLocation({
            // latitude: 28.8025354729244,
            // longitude: 115.921421511343,
            success: (res) => {
                let {
                    latitude,
                    longitude,
                    address,
                    name
                } = res;
                let locations = new Parse.GeoPoint(latitude, longitude);
                this.setData({
                    locations,
                    address: address
                });
                console.log(locations);
                console.log(address + name);
            },
            fail: (error) => {
                // 处理选择位置失败的情况
                console.error('选择位置失败:', error);
                wx.showToast({
                    title: '选择位置失败，请重试',
                    icon: 'none'
                });
            }
        });
    },
    //解析地理位置
    Getlocation() {
        // 假设 this.storeList[0].location 是一个 Parse.GeoPoint 对象
        // if (this.data.locations) {
        //     const storeLocation = this.data.locations;

        //     // 从 GeoPoint 对象中获取经纬度
        //     const latitude = storeLocation.latitude; // 纬度
        //     const longitude = storeLocation.longitude; // 经度

        //     console.log('获取到的经纬度:', latitude, longitude); // 添加日志

        //     // 调用 API 解析地址
        //     wx.request({
        //         url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=sHZTomd7grslfP7sPKB8tRgT49FK9TEu&output=json&coordtype=gcj02&location=' + latitude + ',' + longitude,
        //         data: {},
        //         header: {
        //             'Content-Type': 'application/json'
        //         },
        //         success: (ops) => { // 使用箭头函数
        //             console.log(ops);
        //             const address = ops.data.result.formatted_address;
        //             this.setData({
        //                 address: address,
        //             });
        //             console.log(this.data.address);
        //         },
        //         fail: function (resq) {
        //             wx.showModal({
        //                 title: '信息提示',
        //                 content: '请求失败',
        //                 showCancel: false,
        //                 confirmColor: '#f37938'
        //             });
        //         },
        //         complete: function () {}
        //     });
        // }

    },
})