/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：商品选择
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		于继渤		  2022-05-13	              1.00		   	    
 *******************************************************************************/
const api = require('../../../utils/api.js');
const Constants = require('../../../utils/Constants.js');
import Dialog from '../../../dist/dialog/dialog.js';
const common = require('../../../utils/common.js');
const chooseGoodsCommon = require('../../../utils/chooseGoodsCommon.js');
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nonStandardListFlag: true,
        skuloading: false,
        specsId: undefined,
        orderType: '',
        followFlag: false, // 退换补标识
        loading: false,
        list: [],
        pageInfo: {
            pageSize: 10,
            currentPage: 1
        },
        noMore: false,
        choosedGoodsList: [], //已选商品列表
        choosedGoodsListLength: 0,
        goodsList: [], //商品列表
        goodsSkuList: [], //SPU对应的SKU
        //------------------------
        sumGoodsAmount: '0', //合计金额
        sumQuantity: '0', // 合计数量
        categoryQuantity: 0, // 品类数

        mainActiveIndex: 0,
        numNum: 0,
        sideKey: 0,
        search: '',
        noMore: false,
        loading: false,
        pageInfo: {
            pageSize: 10,
            currentPage: 1
        },
        active: 0,
        specsActive: -1, // 个别分类
        showAdd: false,
        showChoosed: false,
        showAllSpecs: false, // 是否显示商品分类
        updateIndex: null,
        skuData: [], // 根据spuId查询出的sku信息
        defSkuId: 0, // 默认的skuId

        // 商品分类
        typeList: [{
                name: "全部分类",
                id: ''
            },
            {
                name: "促销套餐",
                id: 0
            },
        ],

        // sku规格
        skuSpecsList: [],
        // 可用的sku规格
        skuSpecsData: [],

        // 坑距
        formKG: [{
            title: '',
            tags: [],
        }],


        //单品促销
        PricePromotionData: [],

        tagList: [{
                id: 1,
                name: '原木柜'
            },
            {
                id: 2,
                name: '古典柜'
            }, {
                id: 3,
                name: '金属柜'
            }, {
                id: 4,
                name: '生态柜'
            },
            {
                id: 0,
                name: '更多'
            },

        ],
        infoTypeFlag: false,
        infoTypeFlag1: false,

        show_spec: false,
        show_glassParameters: false,
    },



    changeTag(e) {
        this.setData({
            active: e.detail.index
        })
    },



    /**
     * 允许从相机和相册扫码
     * @param {*} e 
     */
    scanQRCode(e) {
        // 允许从相机和相册扫码
        wx.scanCode({
            success(res) {
                let scancode = res.result
                // 调转商品选品
                wx.navigateTo({
                    url: '../choose-goods/choose-goods?searchText=' + scancode.length > 14 ? scancode.substring(0, 14) : scancode,
                })
            }
        })
    },
    /**
     * @desc : 改变标识
     * @author : 周兴
     * @date : 2022/8/6 17:16
     */
    changeAllReadyCheckBox(e) {
        chooseGoodsCommon.changeAllReadyCheckBoxCommon(e, this)
    },

    /**
     * @desc : 分类切换
     * @author : 于继渤
     * @date : 2022/5/26 20:16
     */
    changeSidebar(e) {
        let id = this.data.typeList[e.detail].id
        if (id == "" && typeof (id) != 'number') {
            this.setData({
                sideKey: null,
                specsId: null
            })
        } else {
            this.setData({
                sideKey: e.detail,
                specsId: id
            })
        }
        this.setData({
            searchText: ''
        })
        // 查询
        this.doSearch()
    },

    /**
     * @desc : 打开商品
     * @author : 周兴
     * @date : 2022/7/2 20:16
     */
    openAddItemInfo(e) {
        //  chooseGoodsCommon.openAddItemInfoCommon(e, this, 'choose-goods')
        let item = e.currentTarget.dataset.item
        this.setData({
            currentChoosedItem: item,
            showAdd: true,
            show1: true,
            show2: false,
            show3: false,
            show4: false,
            show5: false
        })

    },
    /**
     * 关闭产品
     * @param {*} e 
     */
    closeAddItemInfo() {
        chooseGoodsCommon.closeAddItemInfoCommon(this)
    },
    /**
     * @desc : 打开选择明细
     * @author : 周兴
     * @date : 2022/7/4 20:16
     */
    openChoosedItemInfo(e) {
        chooseGoodsCommon.openChoosedItemInfoCommon(e, this)
    },
    /**
     * @desc : 删除选中的数据
     * @author : 周兴
     * @date : 2022/7/4 20:16
     */
    delChoosedGoodsItem(e) {
        chooseGoodsCommon.delChoosedGoodsItemCommon(e, this, false)

        let choosedGoodsListLength = this.data.choosedGoodsListLength
        if (choosedGoodsListLength == 0) {
            wx.disableAlertBeforeUnload({
                success: (e) => {

                },
                fail: (e) => {

                }
            })
        }


    },
    /**
     * @desc : 确定
     * @date : 2022/7/5 16:49
     * @author : 周兴
     */
    submit() {
        let choosedGoodsList = this.data.choosedGoodsList
        wx.navigateTo({
            url: '../order-billing/add/add?choosedGoodsList='   + encodeURIComponent(JSON.stringify(choosedGoodsList))  ,
        })
    },
    /**
     * @desc : 查询
     * @date : 2022/5/12 16:49
     * @author : 于继渤
     */
    doSearch() {
        let pageInfo = this.data.pageInfo;
        pageInfo.pageSize = 10;
        pageInfo.currentPage = 1;
        this.setData({
            show: false,
            noMore: false,
            pageInfo: pageInfo,
            list: [],
            goodsList: []
        })
        this.getData()
    },

    onSearchText(e) {
        this.setData({
            searchText: e.detail,
            sideKey: 0,
            specsId: null
        })
    },

    /**
     * @desc : 获取商品数据
     * @date : 2022/5/13 16:49
     * @author : 于继渤
     */
    getData(e) {


        let tList = [{
            activityId: 84,
            activityName: "零售活动方案",
            desc: "零售活动方案",
            id: "d2f69c53-a5ba-4414-86ee-3b05849cb882",
            orderItemQuantity: 1,
            pathType: 1,
            pricePromotion: 70000,
            priceSale: 70000,
            promotionId: 283,
            promotionName: "套餐相同商品",
            promotionPriceType: -2,
            promotionPriceTypeName: "正价产品",
            promotionType: 2,
            promotionTypeName: "组合促销",
            seq: 1,
            spuModel: "套餐相同商品",
            standardId: 308,
            title: "套餐相同商品",
            titleTag: "组合促销"
        }, {
            activityId: 84,
            activityName: "零售活动方案",
            desc: "零售活动方案",
            id: "f911da02-2b9a-400c-813b-8007bf994856",
            orderItemQuantity: 1,
            pathType: 1,
            pricePromotion: 8600,
            priceSale: 8600,
            promotionId: 273,
            promotionName: "1115新活动",
            promotionPriceType: -2,
            promotionPriceTypeName: "正价产品",
            promotionType: 2,
            promotionTypeName: "组合促销",
            seq: 2,
            spuModel: "1115新活动",
            standardId: 308,
            title: "1115新活动",
            titleTag: "组合促销"
        }, {
            activityId: 84,
            activityName: "零售活动方案",
            desc: "零售活动方案",
            id: "a2708ff8-4032-40a2-8823-5176a0e92b84",
            orderItemQuantity: 1,
            pathType: 1,
            pricePromotion: 13000,
            priceSale: 13000,
            promotionId: 271,
            promotionName: "零售套餐001",
            promotionPriceType: -2,
            promotionPriceTypeName: "正价产品",
            promotionType: 2,
            promotionTypeName: "组合促销",
            seq: 3,
            spuModel: "零售套餐001",
            standardId: 308,
            title: "零售套餐001",
            titleTag: "组合促销"
        }];

        this.setData({
            list: tList,
            goodsList: tList
        })

    },
    /**
     * 数量的变化事件
     * @param {*} e 
     */
    changeAllreadyChooseQuantityPop(e) {
        let currentChoosedItem = this.data.currentChoosedItem
        currentChoosedItem.itemQuantity = e.detail
        if (currentChoosedItem.nonStandardArea) {
            currentChoosedItem.itemAmount = Number(currentChoosedItem.priceSale * currentChoosedItem.itemQuantity * currentChoosedItem.nonStandardArea).toFixed(2)
            currentChoosedItem.itemAmount = isNaN(currentChoosedItem.itemAmount) ? 0 : currentChoosedItem.itemAmount
        } else {
            currentChoosedItem.itemAmount = Number(currentChoosedItem.priceSale * currentChoosedItem.itemQuantity).toFixed(2)
            currentChoosedItem.itemAmount = isNaN(currentChoosedItem.itemAmount) ? 0 : currentChoosedItem.itemAmount
        }

        this.setData({
            currentChoosedItem: currentChoosedItem
        })
    },
    /**
     * @desc : 生命周期函数--监听页面加载
     * @date : 2022/5/13 16:49
     * @author : 于继渤
     */
    onLoad: function (options) {

        let that = this
        // 调用监听器，监听数据变化
        this.watch(this.data, {
            choosedGoodsListLength: function (newVal) {

                if (newVal != 0) {
                    that.BeaforeUnLoad()
                    console.log('调用监听器，监听数据变化')
                }
            }
        })
        if (options.customerId) {
            this.setData({
                customerId: parseInt(options.customerId)
            })
        }
        if (options.orgId) {
            this.setData({
                orgId: parseInt(options.orgId)
            })
        }

        let _this = this;
        wx.getSystemInfo({
            success: function (res) {
                _this.setData({
                    windowHeight: res.windowHeight,
                    windowWidth: res.windowWidth
                })
            }
        })
        //设置来源
        if (options.orderType) {
            this.setData({
                orderType: options.orderType
            })
        }
        // 是否是退换补单（退换补单按照实际量进行处理）
        if (options.followFlag) {
            this.setData({
                followFlag: options.followFlag,
                orgId: Number(options.orgId)
            })
        }
        //预算报价客户信息
        if (options.customerItem) {
            this.setData({
                customerItem: JSON.parse(decodeURIComponent(options.customerItem))
            })
        }
        //扫码搜索
        if (options.searchText) {
            this.setData({
                searchText: options.searchText
            })
        }
        //哪个界面 进来的
        if (options.page) {
            this.setData({
                page: options.page
            })
        }
        //执行查询
        this.doSearch()
        this.getGoodsClassification()
    },
    /**
     * @desc : 清空default
     * @date : 2022/7/4 16:49
     * @author : 周兴
     */
    clearDefault() {
        chooseGoodsCommon.clearDefaultCommon(this);
    },

    /**
     * @desc : 加载商品分类
     * @date : 2022/5/15 16:49
     * @author : 于继渤
     */
    getGoodsClassification() {
       

                let typeList = [{
                        id: null,
                        name: "全部分类"
                    },
                    {
                        id: 0,
                        name: "促销套餐"
                    },
                    {
                        id: 64,
                        name: "智能马桶"
                    },
                    {
                        id: 96,
                        name: "坐便器"
                    },
                    {
                        id: 138,
                        name: "电控坐便器"
                    },
                    {
                        id: 79,
                        name: "蹲便器"
                    },
                    {
                        id: 104,
                        name: "小便器"
                    },
                    {
                        id: 105,
                        name: "洗面器"
                    },
                    {
                        id: 93,
                        name: "其它陶瓷"
                    },
                    {
                        id: 66,
                        name: "浴室柜"
                    },
                ]

                this.setData({
                    typeList: typeList
                })
        
    },
    /**
     * @desc : 选择数据
     * @date : 2022/7/4 16:49
     * @author : 周兴
     */
    chooseSkuInfo() {

        let currentChoosedItemTemp = {
            ...this.data.currentChoosedItem
        }
        let choosedGoodsList = this.data.choosedGoodsList
        choosedGoodsList.push(currentChoosedItemTemp)
        this.setData({
            choosedGoodsList,
            showAdd:false
        })

    },
    /**
     * @desc : 已选商品更改数量计算合计
     * @date : 2022/7/4 16:49
     * @author : 周兴
     */
    changeAllreadyChooseQuantity(e) {
        let choosedGoodsList = this.data.choosedGoodsList
        let index = e.currentTarget.dataset.index

        choosedGoodsList[index].itemQuantity = e.detail ? Number(e.detail) : 0
        choosedGoodsList[index].itemAmount = Number(choosedGoodsList[index].priceSale * choosedGoodsList[index].itemQuantity)
        this.setData({
            choosedGoodsList: choosedGoodsList,
        })
        // 计算合计金额
        chooseGoodsCommon.getSumAmount(this);
    },

    /**
     * @desc : 标价折扣输入事件
     * @author : 于继渤
     * @date : 2022/5/31 17:16
     */
    changeDiscountStandardField(e) {
        let currentChoosedItem = this.data.currentChoosedItem
        currentChoosedItem.discountStandard = e.detail
        this.setData({
            currentChoosedItem: currentChoosedItem
        })
    },
    /**
     * @desc : 销售价格编辑
     * @author : 常皓宁
     * @date : 2022/5/31 14:45
     */
    changeSalesPriceField(e) {
        let priceSale = e.detail.value;
        //优惠卷（标价负数）
        if (this.data.currentChoosedItem.priceStandard < 0 || this.data.currentChoosedItem.pricePromotion < 0) {
            priceSale = Number(0 - e.detail.value)
        }


        chooseGoodsCommon.changeSalesPriceCommon(priceSale, this, false)
    },
    /**
     * @desc : 修改销售价格
     * @author : 周兴
     * @date : 2022/7/6 14:45
     */
    changeSalesPrice(priceSale) {
        chooseGoodsCommon.changeSalesPriceCommon(priceSale, this, true)
    },
    /**
     * @desc : 修改销售金额
     * @author : 周兴
     * @date : 2022/7/4 14:45
     */
    changeItemAmountField(e) {
        chooseGoodsCommon.changeItemAmountFieldCommon(e, this)
    },

    /**
     * @desc : 切换sku商品规格
     * @author : 周兴
     * @date : 2022/6/1 10:16
     */
    changeSkuSpecs(e) {
        chooseGoodsCommon.changeSkuSpecsCommon(e, this);
    },


    /**
     * @desc : 主柜规格单选
     * @author : 于继渤
     * @date : 2022/6/02 16:16
     */
    clickZGGG(e) {
        let itemt = e.target.dataset.itemt;
        let pindex = e.target.dataset.pindex;
        let indext = e.target.dataset.indext;
        let formZGGG = this.data.formZGGG
        let infotype = formZGGG[pindex].tags[indext].infotype

        infotype = 'default'
        formZGGG[pindex].tags.forEach(res => {
            res.infotype = 'default'
        })

        if (infotype == 'default') {
            infotype = 'info'
        } else {
            infotype = 'default'
        }

        formZGGG[pindex].tags[indext].infotype = infotype
        this.setData({
            formZGGG
        })
    },


    /**
     * @desc : 定制品单选
     * @author : 于继渤
     * @date : 2022/6/02 16:16
     */
    clickDZP(e) {
        let itemt = e.target.dataset.itemt;
        let pindex = e.target.dataset.pindex;
        let indext = e.target.dataset.indext;
        let formDZP = this.data.formDZP
        let infotype = formDZP[pindex].tags[indext].infotype

        infotype = 'default'
        formDZP[pindex].tags.forEach(res => {
            res.infotype = 'default'
        })

        if (infotype == 'default') {
            infotype = 'info'
        } else {
            infotype = 'default'
        }

        formDZP[pindex].tags[indext].infotype = infotype
        this.setData({
            formDZP
        })
    },
    /**
     * @desc : 切换组合促销明细
     * @date : 2022/7/5 16:49
     * @author : 周兴
     */
    changeCombinedItem(e) {
        chooseGoodsCommon.changeCombinedItemCommon(e, this)
    },

    /**
     * @desc : 单品促销单选
     * @author : 于继渤
     * @date : 2022/6/02 16:16
     */
    clickDP(e) {
        chooseGoodsCommon.clickDPCommon(e, this)
    },


    /**
     * @desc : 使用位置相关事件
     * @author : 于继渤
     * @date : 2022/5/26 12:16
     */
    changeUseLocation(e) {
        let currentChoosedItem = this.data.currentChoosedItem
        currentChoosedItem.usedLocation = e.detail
        this.setData({
            currentChoosedItem: currentChoosedItem
        })
    },
    /**
     * @desc : 点击全部分类
     * @date : 2022/7/8 16:49
     * @author : 周兴
     */
    clickAllSpecs() {
        // 让其他分类的标识置为-1
        this.setData({
            specsActive: -1,
            specsId: null
        })
        // 查询数据
        this.doSearch()
    },
    /**
     * @desc : 点击全部单个分类
     * @date : 2022/7/8 16:49
     * @author : 周兴
     */
    changeSpecsTabs(e) {
        let index = e.detail.index;
        this.setData({
            specsActive: index,
        })
        let id = this.data.typeList[index].id
        this.setData({
            specsId: id
        })
        // 查询数据
        this.doSearch()
    },
    /**
     * @desc : 是否显示商品分类页面
     * @date : 2022/7/9 16:49
     * @author : 周兴
     */
    displayAllSpecs() {
        this.setData({
            showAllSpecs: true
        })
    },
    /**
     * @desc : 页面上拉触底事件的处理函数
     * @author : 周兴
     * @date : 2022/8/1 12:16
     */
    scrollToLower() {
        if (this.data.loading || this.data.noMore) {
            return;
        }
        this.setData({
            pageInfo: {
                pageSize: this.data.pageInfo.pageSize,
                currentPage: this.data.pageInfo.currentPage + 1
            }
        })
        this.getData('more')
    },
    /**
     * @desc : 页面上拉触底事件的处理函数
     * @author : 于继渤
     * @date : 2022/5/24 12:16
     */
    onReachBottom: function () {

        if (this.data.loading || this.data.noMore || this.data.active == 1) {
            return;
        }
        this.setData({
            pageInfo: {
                pageSize: this.data.pageInfo.pageSize,
                currentPage: this.data.pageInfo.currentPage + 1
            }
        })
        this.getData('more')
    },

    BeaforeUnLoad() {
        wx.enableAlertBeforeUnload({
            message: '离开此页后已选商品将会被清空哦',
            success: (e) => {
                wx.setStorageSync('choosedGoodsList', [])

            },
            fail: (e) => {

            }
        })
    },

    // 设置监听器
    watch: function (ctx, obj) {
        Object.keys(obj).forEach(key => {

            this.observer(ctx, key, ctx[key], function (value) {
                obj[key].call(ctx, value)
            })
        })
    },
    // 监听属性，并执行监听函数
    observer: function (data, key, val, fn) {
        Object.defineProperty(data, key, {
            configurable: true,
            enumerable: true,
            get: function () {
                return val
            },
            set: function (newVal) {
                if (newVal === val) return
                fn && fn(newVal)
                val = newVal
            },
        })
    },
    /**
     * @desc : 选择非标参数事件
     * @author : 于继渤
     * @date : 2022/8/24 13:16
     */
    nonStandardTap(e) {
        chooseGoodsCommon.nonStandardTap(e, this)
    },
    /**
     * @desc : 设置非标匹配参数
     * @author : 于继渤
     * @date : 2022/8/24 13:16
     */
    setNonStandardMatchingParameters() {
        chooseGoodsCommon.setNonStandardMatchingParameters(e, this)
    },
    /**
     * @desc : 非标商品选择事件
     * @author : 于继渤
     * @date : 2022/8/24 13:16
     */
    nonGlassSpuItemsTap(e) {
        chooseGoodsCommon.nonGlassSpuItemsTap(e, this)
    },

    /**
     * @desc : 非标商品非标参数输入事件
     * @author : 于继渤
     * @date : 2022/8/24 13:16
     */
    bindInputIsScopeOne(e) {
        chooseGoodsCommon.bindInputIsScopeOne(e, this)
    },
    bindBlurIsScopeOne(e) {
        chooseGoodsCommon.bindBlurIsScopeOne(e, this)
    },
    changeFlgAllowSpecsUndefine(e) {

        let currentChoosedItem = this.data.currentChoosedItem
        currentChoosedItem.flgSpecsUndefine = e.detail
        this.setData({
            currentChoosedItem: currentChoosedItem
        })
    },


    bindInputNonStantardArea(e) {

        chooseGoodsCommon.bindInputNonStantardArea(e, this)
    },
    //面积离焦
    bindBlurNonStantardArea(e) {

        chooseGoodsCommon.bindBlurNonStantardArea(e, this)
    },
    onUnload() {

        Dialog.confirm({
            message: '哈哈哈哈哈哈',
        }).then(() => {

        })
    },

    /**
     * @desc : 计算折扣反算销售价格
     * @author : 于继渤
     * @date : 2022/7/4 14:45
     */
    changeDiscountField(e) {
        chooseGoodsCommon.changeDiscountFieldCommon(e, this)
    }
})