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

var company = getApp().globalData.company
const Parse = getApp().Parse;
Page({

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

    data: {
        idx: 0,
        show: false,
        food: {},
        id: "",
        cid: null,
        category: {}, //商品分类
        value: '',
        checked: true, //上架状态
        unit: null, //推荐状态
        twoModal: false,
        name: "", //商品名称
        price: "", //价格
        images: [], //商品轮播图
        imageList: [],
    },
    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 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({
                images: [e.detail[0].url]
            })
        } else {
            this.setData({
                images: []
            })
        }
    },

    onCancel() {
        console.log('取消')
        this.setData({
            showPicker: false
        })
    },
    async getCategory() {
        let Category = new Parse.Query("Category")
        Category.equalTo("company", company)
        Category.equalTo("type", 'catering')
        Category.equalTo("store", this.data.store.objectId)
        let category = await Category.find()
        let columns = []
        if (category) {
            category.forEach(item => {
                let category = item.toJSON()
                columns.push(category)
            })
            this.setData({
                columns: columns,
            })
        }
        console.log(this.data.columns);
    },
    // 新建商品
    async submit() {
        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
        if (!this.data.name || !this.data.price || !this.data.unit || !this.data.images || !this.data.cid) {
            wx.showToast({
                title: '请填写完整信息',
                icon: 'none'
            })
            return
        }
        let foods
        if (this.data.id) {
            let Foods = new Parse.Query("Food")
            foods = await Foods.get(this.data.id)
        } else {
            let Foods = Parse.Object.extend("Food")
            foods = new Foods()
            foods.set("company", {
                __type: "Pointer",
                className: "Company",
                objectId: company
            })
        }
        foods.set("name", this.data.name)
        foods.set("price", Number(this.data.price))
        foods.set("images", this.data.images)
        foods.set("isOpen", this.data.checked)
        foods.set("unit", this.data.unit)
        foods.set("category", {
            __type: "Pointer",
            className: "Category",
            objectId: this.data.cid
        })
        foods.set("store", {
            __type: "Pointer",
            className: "ShopStore",
            objectId: id
        })
        foods.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: [],
                images: '',
                price: '',
                columns: null,
                unit: null
            })

            wx.navigateBack({
                delta: 1

            });

        })
    },

    goIndex(e) {
        let index = e.currentTarget.dataset.index;
        this.setData({
            idx: index,
            cid: e.currentTarget.dataset.item.objectId,
            show: false,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    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 Food = new Parse.Query("Food")
            console.log(id);
            Food.include("store")
            Food.include("category")
            let Foods = await Food.get(id)
            let food = Foods.toJSON()
            // order.orderTime = dateF.formatTime("YYYY-mm-dd ", order.createdAt)
            imageList.push({
                url: food.images[0]
            })
            this.setData({
                food: food,
                cid: food.category.objectId,
                images: food.images,
                checked: food.isOpen,
                name: food.name,
                unit: food.unit,
                price: food.price,
                imageList: imageList,
            })
        }

    },
    category() {
        this.setData({ show: true })
    },

    onCancela() {
        this.setData({ show: false })
    },   /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

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

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

    },

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

    },

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

    },

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

    },

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

    }
})