const _Http = getApp().globalData.http,
    file = require("../../../../utils/FormatTheAttachment"),
    currency = require("../../../../utils/currency");
let queue = [],
    downCounter = null,
    sa_orderid = 0,
    CNY = num => currency(num, {
        symbol: "￥",
        precision: 2
    }).format();

Component({
    properties: {
        sa_order_v: {
            type: String
        },
        disabled: {
            type: Boolean
        }, //禁用
        returnProductCount: {
            type: Function
        },
        privacyFieldC: {
            type: Array
        },
        packagetype: {
            type: String
        },
        packagetypemxrows: {
            type: Array,
            value: []
        },
        sa_promotionid:{
            type: String
        }
    },
    data: {
        content: {
            nocache: true,
            pageNumber: 1,
            pageTotal: 1,
            total: null
        }
    },
    lifetimes: {
        detached: function () {
            if (downCounter) {
                clearTimeout(downCounter);
                this.changeItem(queue)
            }
        },
    },
    methods: {
        /* 获取产品列表 */
        getList(id, init) {
            let content = this.data.content;
            content.sa_orderid = id;
            sa_orderid = id;
            if (init) content.pageNumber = 1;
            _Http.basic({
                "id": "20221109093902",
                content
            }).then(res => {
                console.log("订货清单列表", res)
                if (res.msg != '成功') return wx.showToast({
                    title: res.msg,
                    icon: "none"
                })
                res.data = res.data.map(v => {
                    if (v.attinfos.length != 0) {
                        v.attinfos = file.fileList(v.attinfos)
                        let image = v.attinfos.find(v => v.fileType == "image");
                        v.cover = image ? image.cover : "";
                    };
                    v.showPrice = CNY(v.price)
                    // v.marketprice = CNY(v.marketprice)
                    v.showAmount = CNY(v.amount)
                    return v;
                })
                let page = getCurrentPages().find(v => v.__route__ == 'packageA/orderForm/detail').data.detail;
                let base = {
                    sa_orderid: page.sa_orderid,
                    sys_enterpriseid: page.sys_enterpriseid,
                    sa_contractid: page.sa_contractid,
                    type: page.type,
                };
                this.triggerEvent("returnProductCount", res.total)
                this.setData({
                    list: res.pageNumber == 1 ? res.data : this.data.list.concat(res.data),
                    "content.pageNumber": res.pageNumber + 1,
                    "content.pageSize": res.pageSize,
                    "content.pageTotal": res.pageTotal,
                    "content.total": res.total,
                    base
                })
            })
        },
        /* 修改 */
        changeProduct({
            detail
        }) {
            let obj = detail,
                index = obj.index,
                data = this.data.list[index];
            if (data.qty == obj.qty && data.remarks == obj.remarks && data.needdate == obj.needdate) return;
            detail.sa_order_v = this.data.sa_order_v - 0;
            _Http.basic({
                "id": 20221109093602,
                "content": {
                    ...this.data.base,
                    "items": [detail],
                    sa_order_v: this.data.sa_order_v - 0
                }
            }).then(res => {
                console.log("产品修改", res)
                if (res.msg != '成功') {
                    wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    obj = data;
                };
                data = {
                    ...data,
                    ...obj
                };
                data.showAmount = CNY(currency(data.price).multiply(data.qty).format());
                data.showPrice = CNY(data.price)
                this.setData({
                    [`list[${index}]`]: data
                })
                this.updateThePrice();
            })
        },
        /* 删除 */
        deleteItem({
            detail
        }) {
            let that = this;
            wx.showModal({
                title: '提示',
                content: that.data.packagetype ? '该商品为套餐商品，删除后该套餐下所有商品都会被删除，确认删除吗？' : `是否确认删除“${detail.itemname}”?`,
                complete: (res) => {
                    if (res.confirm) _Http.basic({
                        "id": 20221109093702,
                        "content": {
                            sa_orderid,
                            "sa_orderitemsids": [
                                detail.sa_orderitemsid
                            ],
                            sa_order_v: that.data.sa_order_v
                        }
                    }).then(s => {
                        if (s.msg != '成功') return wx.showToast({
                            title: res.msg,
                            icon: "none"
                        });
                        if (that.data.packagetype) {
                            that.getList(sa_orderid, true)
                        } else {
                            that.setData({
                                list: that.data.list.filter(v => v.sa_orderitemsid != detail.sa_orderitemsid)
                            });
                            that.triggerEvent("returnProductCount", that.data.content.total - 1)
                        }
                        that.updateThePrice();
                    })
                }
            })
        },
        /* 去添加产品 */
        addProduct() {
            if (this.data.packagetype) {
                wx.navigateTo({
                    url: '/packageA/activity/bindingProduct/index?params=' + JSON.stringify({
                        "id": 20230107182302,
                        "version": 1,
                        "content": {
                            nocache: true,
                            sa_orderid, //订单ID
                            packagetype: this.data.packagetype,
                            sa_promotionid: this.data.sa_promotionid,
                            "where": {
                                "condition": "",
                                packagetypemx: "",
                            }
                        }
                    }) + `&butText=添加套餐&packagetypemxrows=${JSON.stringify(this.data.packagetypemxrows)}&getListPa=` + JSON.stringify({
                        "id": "20221109093902",
                        content: this.data.content
                    }),
                });

                getApp().globalData.handleSelect = this.handleInsert.bind(this);

            } else {
                let detail = getCurrentPages().find(v => v.__route__ == 'packageA/orderForm/detail').data.detail,
                    id = '';
                switch (detail.type) {
                    case '促销订单':
                        id = 20230107182302;
                        break;
                    case '标准订单':
                        id = 20221109153502;
                        break;
                    case '特殊订单':
                        id = 20221109153502;
                        break;
                }
                wx.navigateTo({
                    url: `${detail.type=='促销订单'?'/packageA/activity/selectProduct/index':'/select/product/index'}?params=${JSON.stringify({
					"id":id,
					"content": {
						nocache:true,
						sa_orderid, //订单ID
						"total": 0,
						"where": {
							"condition": ""
						}
					}
				})}&butText=添加产品`
                });
                this.setData({
                    type: detail.type
                })
                getApp().globalData.handleSelect = this.handleSelect.bind(this);
            }

        },
        /* 去修改 */
        editProduct() {
            wx.navigateTo({
                url: '/packageA/activity/bindingProduct/index?params=' + JSON.stringify({
                    "id": 20230107182302,
                    "version": 1,
                    "content": {
                        nocache: true,
                        sa_orderid, //订单ID
                        packagetype: this.data.packagetype,
                        "where": {
                            "condition": "",
                            packagetypemx: "",
                        }
                    }
                }) + `&butText=调整套数&packagetypemxrows=${JSON.stringify(this.data.packagetypemxrows)}&getListPa=` + JSON.stringify({
                    "id": "20221109093902",
                    content: this.data.content
                }),
            });
            getApp().globalData.handleSelect = this.handleInsert.bind(this);
        },
        /* 处理新增产品 */
        handleSelect(detail) {
            let that = this;
            _Http.basic({
                "id": 2024020201095102,
                "content": {
                    ...that.data.base,
                    "items": detail.list
                },
            }).then(res => {
                console.log("查询重复产品", res)
                if (res.msg != '成功') return wx.showToast({
                    title: res.msg,
                    icon: "none"
                });
                if (res.data.items.length) {
                    if (res.data.isrepeat) {
                        wx.showModal({
                            title: '提示',
                            content: `本单已存在【${res.data.items[0].itemname}】商品，确认继续添加吗？`,
                            complete: (res) => {
                                if (res.confirm) handle()
                            }
                        })
                    } else {
                        wx.showModal({
                            title: '提示',
                            content: `本单已存在【${res.data.items[0].itemname}】商品，禁止重复添加！`,
                            showCancel: false
                        })
                    }

                } else {
                    handle()
                }
            })

            function handle() {
                wx.showModal({
                    title: '提示',
                    content: `是否确认添加${detail.result.length}件商品?`,
                    complete: (res) => {
                        if (res.confirm) that.handleInsert(detail).bind(that)
                    }
                });
            }
        },
        handleInsert({
            list
        }) {
            return new Promise((resolve) => {
                _Http.basic({
                    "id": 20221109093602,
                    content: {
                        ...this.data.base,
                        "items": list.map(v => {
                            return {
                                sa_orderitemsid: v.sa_orderitemsid || 0,
                                itemid: v.itemid, //商品ID
                                qty: v.qty, //数量
                                width: v.width || 0,
                                length: v.length || 0,
                                cheek: v.cheek,
                                color: v.color,
                                material: v.material,
                                spec: v.spec,
                                custom: v.custom,
                                price: this.data.type == '工具订单' ? v.marketprice : v.contractprice,
                                sa_promotion_itemsid: v.sa_promotion_itemsid || 0
                            }
                        })
                    }
                }).then(s => {
                    console.log('新增产品', s)
                    resolve(s.msg == '成功')
                    wx.showToast({
                        title: s.msg == '成功' ? '操作成功' : s.msg,
                        icon: "none",
                        mask: s.msg == '成功'
                    });
                    if (s.msg == '成功') {
                        this.getList(sa_orderid, true);
                        this.updateThePrice();
                        setTimeout(() => {
                            wx.navigateBack();
                        }, 300)
                    }
                })
            })
        },

        /* 使用接口更新总价 */
        updateThePrice() {
            getCurrentPages().find(v => v.__route__ == 'packageA/orderForm/detail').getDetail();
        }
    }
})