// nova-shopAdmin/pages/goods/goods.js

const company = getApp().globalData.company
const Parse = getApp().Parse;
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */

    data: {
        merchant: null,
        services: [],
        service: "",
        goods: {},
        id: "",
        category: {}, //商品分类
        value: '',
        checked: true, //上架状态
        check: false, //推荐状态
        twoModal: false,
        name: "", //商品名称
        price: "", //价格
        originalPrice: "", //原价
        top: "", //排序
        images: [], //商品轮播图
        html: "", //富文本
        // image: "https://file-cloud.fmode.cn/lb486SzXLP/20220326/7fibag051234.png", //商品首图
        Introduction: "",
        image: [],
        sales: "",
        total: '',
        imageList: [],
        licenseList: [],
    },
    blur(e) {
        let name = e.currentTarget.dataset.name
        this.setData({
            [name]: e.detail.value
        })
    },
    // shopsubmit() {
    //     this.setData({
    //         twoModal: true
    //     })
    // },
    onChangeos(event) {
        console.log(event)
        const { picker, value, index } = event.detail;
        picker.setColumnValues(1, citys[value[0]]);
    },

    onCancel() {
        this.setData({
            twoModal: false
        })
    },

    onChange({ detail }) {
        // 需要手动对 checked 状态进行更新
        this.setData({ checked: detail });
    },
    oChange({ detail }) {
        // 需要手动对 checked 状态进行更新
        this.setData({ check: detail });
    },
    specifications() {
        wx.navigateTo({
            url: '/nova-shop/pages/nova-shopadmin/pages/goods/specifications/index'

        });

    },
    goodsimage() {
        // let details = this.data.goods.details
        // let img = this.data.goods.images.join(',');

        // console.log(details, 123, img);
        let id = this.data.id
        wx.navigateTo({
            url: `/nova-shop/pages/nova-shopadmin/pages/goods/goods-image/index?id=${id}`

        });
    },

    showCategory() {
        this.setData({
            showPicker: true
        })
    },
    onConfirm(event) {
        const { value, index } = event.detail;
        console.log(value, index, event.detail)
        this.setData({
            pickerIndex: index,
            category: {
                name: value.name,
                value: {
                    __type: "Pointer",
                    className: "Category",
                    objectId: value.objectId
                }
            },
            showPicker: false
        })
    },
    changeFile(e) {
        if (e.detail && e.detail.length > 0) {
            this.setData({
                image: [e.detail[0].url]
            })
        } else {
            this.setData({
                image: []
            })
        }
    },

    onCancel() {
        console.log('取消')
        this.setData({
            showPicker: false
        })
    },
    getCategory() {
        let Category = new Parse.Query("Category")
        Category.equalTo("company", company)
        Category.equalTo("type", "shop")
        Category.ascending('index')
        Category.select('name')
        Category.find().then(res => {
            let columns = []
            res.forEach(item => {
                let category = item.toJSON()
                columns.push(category)
            })
            this.setData({
                columns
            })
        })
    },



    // 新建商品
    async submit() {
        console.log(this.data.html, this.data.images);
        const _this = this
        let ShopStore = new Parse.Query('ShopStore')
        ShopStore.equalTo('user', this.data.merchant.objectId)
        let res = await ShopStore.first()
        let id = res.toJSON().objectId
        console.log(this.data.name, this.data.price, this.data.originalPrice, id, this.data.top, this.data.sales, this.data.html, this.data.image[0])
        if (!this.data.name || !this.data.price || !this.data.originalPrice || !this.data.top || !this.data.image) {
            wx.showToast({
                title: '请填写完整信息',
                icon: 'none'
            })
            return
        }
        let shopGoods
        if (this.data.id) {
            let query = new Parse.Query("ShopGoods")
            shopGoods = await query.get(this.data.id)
        } else {
            let ShopGoods = Parse.Object.extend("ShopGoods")
            shopGoods = new ShopGoods()
            shopGoods.set("company", {
                __type: "Pointer",
                className: "Company",
                objectId: company
            })
        }
        shopGoods.set("user", {
            __type: "Pointer",
            className: "_User",
            objectId: Parse.User.current().id
        })
        shopGoods.set("name", this.data.name)
        if (this.data.html) {
            shopGoods.set("details", this.data.html)
        }
        if (!this.data.html) {
            shopGoods.set("details", this.data.goods.details)
        }


        shopGoods.set("price", Number(this.data.price))
        shopGoods.set("originalPrice", Number(this.data.originalPrice))
        shopGoods.set("top", Number(this.data.top))
        // shopGoods.set("image", this.data.image)
        shopGoods.set("image", this.data.image[0])
        if (this.data.images) {
            shopGoods.set("images", this.data.images)
        }
        if (!this.data.images) {
            shopGoods.set("images", this.data.goods.images)
        }
        shopGoods.set("status", this.data.checked)
        shopGoods.set("isRecom", this.data.check)
        shopGoods.set("type", "meal")
        shopGoods.set("services", this.data.services)
        shopGoods.set("total", Number(this.data.total))
        shopGoods.set("sales", Number(this.data.sales))
        shopGoods.set("shopStore", {
            __type: "Pointer",
            className: "ShopStore",
            objectId: id
        })

        shopGoods.save().then(res => {
            console.log(res)
            if (this.data.id) {
                wx.showToast({

                    title: '修改成功',
                    icon: 'none'
                })
            } else {
                wx.showToast({
                    title: '创建成功',
                    icon: 'none'
                })
            }

            wx.setStorageSync('images', undefined)
            wx.setStorageSync('html', undefined)
            _this.setData({
                name: '',
                images: [],
                image: '',
                price: '',
                originalPrice: '',
                total: '',
                category: '',
                Introduction: "",

            })

            wx.navigateBack({
              delta: 1,
            })
            // ({
            //     url: '/nova-tourism/pages/my/merchant/merchant-home/package/index'

            // });

        })
    },
    //从本地获取数据

    getGoodsList() {
        let ShopGoods = new Parse.Query("ShopGoods")
        console.log(this.data.id);
        ShopGoods.equalTo("objectId", this.data.id)
        ShopGoods.include("shopStore")
        ShopGoods.first().then(res => {
            let goods = res.toJSON()
            // order.orderTime = dateF.formatTime("YYYY-mm-dd ", order.createdAt)

            console.log(goods);
            this.setData({
                goods: goods,
                services: goods.services,
                // image: goods.image,
                // images: goods.images,
                checked: goods.status,
                check: goods.isRecom,
                top: goods.top,
                sales: goods.sales,
                total: goods.total,
                name: goods.name,
                price: goods.price,
                originalPrice: goods.originalPrice,

            })
        })
    },
    showPopup() {

        this.setData({ show: true })
    },
    images() {
        console.log(wx.getStorageSync('images'))
        let images = wx.getStorageSync('images')
        let html = wx.getStorageSync('html')
        this.setData({
            images: images,
            html: html
        });
        console.log(html);
    },
    onClose: function () {
        this.setData({ show: false })
    },
    twoonConfirm: function () {
        let item = this.data.services
        let service = this.data.service
        console.log(service);
        item.push({
            'check': false,
            'value': service,
        })
        console.log(item)
        this.setData({

            service: null,
        })
        console.log(service);
        this.setData({
            show: false,
            services: item
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        let merchant = wx.getStorageSync('merchant'); //用户
        this.setData({ merchant: merchant })
        const _this = this
        this.getCategory()
        let id = (options.id)
        console.log(id)
        this.setData({ id: id });
        // id && this.getGoodsList()
        if (id) {
            let imageList = []
            let ShopGoods = new Parse.Query("ShopGoods")
            console.log(id);
            ShopGoods.include("shopStore")
            let Goods = await ShopGoods.get(id)

            let goods = Goods.toJSON()
            // order.orderTime = dateF.formatTime("YYYY-mm-dd ", order.createdAt)
            imageList.push({
                url: goods.image
            })

            console.log(imageList);
            this.setData({
                goods: goods,
                services: goods.services,
                // image: goods.image,
                images: goods.images,
                checked: goods.status,
                check: goods.isRecom,
                top: goods.top,
                sales: goods.sales,
                total: goods.total,
                name: goods.name,
                price: goods.price,
                originalPrice: goods.originalPrice,
                imageList: imageList,
            })
        }

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})