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: {
        disabled: Boolean, //禁用
    },
    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.defaultprice = CNY(v.defaultprice)
                    v.marketprice = CNY(v.marketprice)
                    v.defaultamount = CNY(v.defaultamount)
                    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.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 = this.data.list.findIndex(v => v.itemid == detail.itemid),
                data = this.data.list[index];
            if (data.qty == obj.qty && data.remarks == obj.remarks && data.needdate == obj.needdate) return;
            _Http.basic({
                "id": 20221109093602,
                "content": {
                    ...this.data.base,
                    "items": [detail]
                }
            }).then(res => {
                console.log("产品修改", res)
                if (res.msg != '成功') {
                    wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    obj = data;
                };
                data = {
                    ...data,
                    ...obj
                };
                data.defaultamount = CNY(currency(data.defaultprice).multiply(data.qty).format());
                this.setData({
                    [`list[${index}]`]: data
                })
                this.updateThePrice();
            })
        },
        /* 删除 */
        deleteItem({
            detail
        }) {
            let that = this;
            wx.showModal({
                title: '提示',
                content: `是否确认删除“${detail.itemname}”?`,
                complete: (res) => {
                    if (res.confirm) _Http.basic({
                        "id": 20221109093702,
                        "content": {
                            sa_orderid,
                            "sa_orderitemsids": [
                                detail.sa_orderitemsid
                            ]
                        }
                    }).then(s => {
                        if (s.msg != '成功') return wx.showToast({
                            title: res.msg,
                            icon: "none"
                        });
                        that.setData({
                            list: that.data.list.filter(v => v.sa_orderitemsid != detail.sa_orderitemsid)
                        });
                        this.updateThePrice();
                    })
                }
            })
        },
        /* 去添加产品 */
        addProduct() {
            let detail = getCurrentPages().find(v => v.__route__ == 'packageA/orderForm/detail').data.detail,
                id = '',
                query = "&newprice=contractprice";
            switch (detail.type) {
                case '项目订单':
                    id = 20230103155002;
                    break;
                case '促销订单':
                    id = 20230107182302;
                    break;
                case '工具订单':
                    id = 20221109153502;
                    query = '';
                    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": ""
						}
					}
				})+query}`
            });
            this.setData({
                type: detail.type
            })
            getApp().globalData.handleSelect = this.handleSelect.bind(this);
        },
        /* 处理新增产品 */
        handleSelect(detail) {
            let that = this;
            wx.showModal({
                title: '提示',
                content: `是否确认添加${detail.result.length}件商品?`,
                complete: (res) => {
                    if (res.confirm) _Http.basic({
                        "id": 20221109093602,
                        "content": {
                            ...that.data.base,
                            "items": detail.list.map(v => {
                                return {
                                    sa_orderitemsid: 0,
                                    "itemid": v.itemid, //商品ID
                                    "qty": 1, //数量
                                    price: this.data.type == '工具订单' ? v.marketprice : v.contractprice
                                }
                            })
                        }
                    }).then(s => {
                        console.log('新增产品', s)
                        wx.showToast({
                            title: s.msg == '成功' ? '添加成功' : s.msg,
                            icon: "none"
                        });
                        if (s.msg == '成功') setTimeout(() => {
                            that.getList(sa_orderid, true);
                            wx.navigateBack();
                            that.updateThePrice();
                        }, 300)
                    })
                }
            });
        },
        /* 使用接口更新总价 */
        updateThePrice() {
            // _Http.basic({
            //     "id": 20230105101102,
            //     "content": {
            //         sa_orderid
            //     },
            // }).then(res => {
            //     console.log("修改列表总价", res)
            //     if (res.msg != '成功') return wx.showToast({
            //         title: `产品总价更新失败`,
            //         icon: "none"
            //     });
            //     let page = getCurrentPages()[getCurrentPages().length - 1];
            //     if (page) {
            //         this.setData({
            //             "detail.defaultamount": CNY(res.data.amount)
            //         })
            //         page.setLogisticsMsg();
            //     }
            // })
            let page = getCurrentPages().find(v => v.__route__ == 'packageA/orderForm/detail');
            page.getDetail();
        }
    }
})