// 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: "", //原价
        desc: null, //排序
        image: null,
        sales: "",
        total: '',
        imageList: [],
        showPicker: false,
        item: null,
    },
    blur(e) {
        let name = e.currentTarget.dataset.name
        this.setData({
            [name]: e.detail.value
        })
    },

    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'

        });

    },

    showCategory() {
        this.setData({
            showPicker: true
        })
    },
    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
            })
        })
    },

    onConfirm(event) {
        const { value, index } = event.detail;
        console.log(event.detail)
        this.setData({
            time: value.objectId,
            category: {
                name: value.name,
                value: {
                    __type: "Pointer",
                    className: "Category",
                    objectId: value.objectId
                }
            },
            showPicker: false
        })
    },

    // 新建商品
    async submit() {
        const _this = this
        let id = this.data.store.objectId
        console.log(this.data.name, this.data.price, this.data.originalPrice, id, this.data.image, this.data.desc)
        if (!this.data.name || !this.data.price || !this.data.originalPrice || !this.data.image || !this.data.desc) {
            wx.showToast({
                title: '请填写完整信息',
                icon: 'none'
            })
            return
        }
        if(!this.data.category) {
            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("name", this.data.name)
        shopGoods.set("price", Number(this.data.price))
        shopGoods.set("originalPrice", Number(this.data.originalPrice))
        shopGoods.set("image", this.data.image)
        shopGoods.set("status", this.data.checked)
        shopGoods.set("isRecom", this.data.check)
        shopGoods.set("type", "shop")
        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.set("category", this.data.category.value)
        shopGoods.save().then(res => {
            console.log(res)
            if (this.data.id) {
                wx.showToast({

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

                    title: '创建成功',
                    icon: 'none'
                })
            }
            _this.setData({
                name: '',
                images: [],
                image: '',
                price: '',
                originalPrice: '',
                total: '',
                category: '',
                Introduction: "",

            })

            wx.navigateBack({
                delta: 1
            })

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

    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,
                checked: goods.status,
                check: goods.isRecom,
                desc: goods.desc,
                sales: goods.sales,
                total: goods.total,
                name: goods.name,
                price: goods.price,
                originalPrice: goods.originalPrice,

            })
        })
    },


    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'); //用户
        let store = wx.getStorageSync('store'); //用户
        this.setData({ merchant: merchant,store:store })
        this.getCategory()
        let id = (options.id)
        console.log(id)
        this.setData({ id: id });
        if (id) {
            let imageList = []
            let ShopGoods = new Parse.Query("ShopGoods")
            console.log(id);
            ShopGoods.include("shopStore")
            ShopGoods.include("category")
            let Goods = await ShopGoods.get(id)
            let goods = Goods.toJSON()
            imageList.push({
                url: goods.image
            })
            this.setData({
                goods: goods,
                services: goods.services,
                image: goods.image,
                checked: goods.status,
                check: goods.isRecom,
                desc: goods.desc,
                sales: goods.sales,
                total: goods.total,
                name: goods.name,
                price: goods.price,
                originalPrice: goods.originalPrice,
                imageList: imageList,
                time: goods.category.objectId,
                category: goods.category
            })
        }

    },

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

    },

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

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

    },

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

    },

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

    },

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

    },

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

    }
})