const _Http = getApp().globalData.http,
    file = require("../../../../utils/matchingFeilType"),
    currency = require("../../../../utils/currency"),
    CNY = value => currency(value, {
        symbol: "￥",
        precision: 2
    }).format();
let queue = [],
    downCounter = null,
    sa_quotedpriceid = 0;
Component({
    properties: {
        disabled: Boolean, //禁用
        sa_projectid: Number,
        type: String, //报价单类型
        savePage: null, //保存页面
    },
    observers: {
        sumamount(newData) {
            let savePage = this.data.savePage;
            let i = savePage.data.list1.findIndex(v => v.label == '总金额');
            if (i != -1 && savePage.data.list1[i].value != newData) savePage.setData({
                [`list1[${i}].value`]: newData
            })
        }
    },
    data: {
        "content": {
            nocache: true,
            "pageNumber": 1,
            pageTotal: 1,
            total: null
        },
        actionShow: false,
        actions: [{
            name: "自项目产品添加"
        }, {
            name: "自产品档案添加"
        }]
    },
    lifetimes: {
        detached: function () {
            if (downCounter) {
                clearTimeout(downCounter);
                this.changeItem(queue)
            }
        },
    },
    methods: {
        /* 获取产品列表 */
        getList(id, init) {
            let content = this.data.content;
            content.sa_quotedpriceid = id;
            sa_quotedpriceid = id;
            if (init) content.pageNumber = 1;
            _Http.basic({
                "id": "20221021095503",
                content
            }).then(res => {
                console.log("项目清单列表", res)
                if (res.msg != '成功') return wx.showToast({
                    title: res.data,
                    icon: "none"
                })
                res.data = res.data.map(value => {
                    if (value.attinfos.length != 0) {
                        value.attinfos = file.fileList(value.attinfos)
                        let image = value.attinfos.find(v => v.fileType == "image");
                        value.cover = image ? image.cover : "";
                    }
                    //最低价 = 牌价*最低折扣
                    value.minPrice = currency(value.marketprice).multiply(value.mindiscountrate).value;
                    value.mindiscountrate = currency(value.mindiscountrate).multiply(100).value;
                    value.discountrate = currency(value.discountrate).multiply(100).value;
                    value.price = currency(value.price).value;

                    //显示格式化金额
                    value.showMarketprice = CNY(value.marketprice);
                    value.discountDifferenceAmount = CNY(value.discountDifferenceAmount)
                    value.showAmount = CNY(value.amount)
                    value.className = value.itemclass.length == 0 ? "暂无类目" : value.itemclass.map(v => v.itemclassname);
                    value.brandName = value.brand.length == 0 ? "暂无品牌" : value.brand.map(v => v.brandname);
                    return value;
                })
                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,
                    savePage: getCurrentPages().find(v => v.__route__ == 'packageA/offers/detail'),
                })
                if (res.pageNumber == 1) this.setData({
                    sumamount: CNY(res.data[0].rowstotal[0].sumamount || 0)
                })
            })
        },
        /* 去选择产品 */
        addProduct() {
            console.log("添加产品", this.data.type, this.data.sa_projectid)
            if (this.data.type == '项目报价') {
                this.setData({
                    actionShow: true
                })
            } else {
                this.toSelected(0);
            }
        },
        cancelSelector() {
            this.setData({
                actionShow: false
            })
        },
        selectorMode({
            detail
        }) {
            this.toSelected(detail.name == '自项目产品添加' ? this.data.sa_projectid : 0);
            this.cancelSelector();
        },
        /* 去挑选 */
        toSelected(sa_projectid) {
            wx.navigateTo({
                url: '/packageA/select/product/select?params=' + JSON.stringify({
                    "id": 20221020164903,
                    "version": 1,
                    "content": {
                        nocache: true,
                        total: null,
                        sa_projectid,
                        sa_quotedpriceid,
                        where: {
                            condition: ""
                        }
                    }
                })
            });
            getApp().globalData.handleSelect = sa_projectid == 0 ? this.selectProduct.bind(this) : this.projectProduct.bind(this)
        },
        /* 项目产品 */
        projectProduct({
            list
        }) {
            console.log('项目产品添加', list)
            let that = this;
            wx.showModal({
                title: '提示',
                content: `是否确认添加${list.length}件产品?`,
                complete: ({
                    confirm
                }) => {
                    if (confirm) _Http.basic({
                        "id": 20221021095403,
                        "version": 1,
                        "content": {
                            sa_quotedpriceid,
                            items: list.map(v => {
                                return {
                                    "sa_quotedprice_itemsid": 0,
                                    "itemid": v.itemid,
                                    "price": v.price,
                                    "discountrate": currency(v.price).divide(v.marketprice).value,
                                    "qty": v.qty
                                }
                            })
                        }
                    }).then(res => {
                        console.log("报价单添加产品", res);
                        wx.showToast({
                            title: res.msg != '成功' ? res.msg : '添加成功!',
                            icon: "none"
                        });
                        if (res.msg == '成功') setTimeout(() => {
                            that.getList(sa_quotedpriceid, true)
                            wx.navigateBack()
                        }, 300)
                    })
                }
            })
        },
        /* 产品档案添加 */
        selectProduct({
            list
        }) {
            console.log('产品档案添加', list)
            let that = this;
            wx.showModal({
                title: '提示',
                content: `是否确认添加${list.length}件产品?`,
                complete: ({
                    confirm
                }) => {
                    if (confirm) _Http.basic({
                        "id": 20221021095403,
                        "version": 1,
                        "content": {
                            sa_quotedpriceid,
                            items: list.map(v => {
                                return {
                                    "sa_quotedprice_itemsid": 0,
                                    "itemid": v.itemid,
                                    "price": v.marketprice,
                                    "discountrate": 1,
                                    "qty": 1
                                }
                            })
                        }
                    }).then(res => {
                        console.log("报价单添加产品", res);
                        wx.showToast({
                            title: res.msg != '成功' ? res.msg : '添加成功!',
                            icon: "none"
                        });
                        if (res.msg == '成功') setTimeout(() => {
                            that.getList(sa_quotedpriceid, true)
                            wx.navigateBack()
                        }, 300)
                    })
                }
            })
        },
        /* 删除产品 */
        deleteItems({
            detail
        }) {
            _Http.basic({
                "id": 20221021095603,
                "version": 1,
                "content": {
                    "sa_quotedprice_itemsids": detail
                }
            }).then(res => {
                console.log("批量删除产品", res);
                wx.showToast({
                    title: res.msg == '成功' ? '删除成功!' : res.msg,
                    icon: "none"
                })
                if (res.msg == '成功') {
                    let i = this.data.list.findIndex(v => v.sa_quotedprice_itemsid == detail);
                    let sumamount = CNY(currency(this.data.sumamount).subtract(this.data.list[i].amount));
                    this.data.list.splice(i, 1);
                    this.setData({
                        list: this.data.list,
                        sumamount
                    })
                }
            })
        },

        /* 生成修改队列 */
        changeQueue({
            detail
        }) {
            let i = queue.findIndex(v => v.sa_quotedprice_itemsid == detail.sa_quotedprice_itemsid);
            i == -1 ? queue.push(detail) : queue[i] = detail;
            clearTimeout(downCounter)
            downCounter = setTimeout(() => {
                this.changeItem(queue)
            }, 300);
        },
        changeItem(items) {
            console.log(items)
            if (items.length == 0) return;
            _Http.basic({
                "id": 20221021095403,
                "version": 1,
                "content": {
                    sa_quotedpriceid,
                    items
                }
            }, false).then(res => {
                console.log("批量修改产品清单", res)
                queue = [];
                downCounter = null;
                let list = this.data.list;
                if (res.msg != '成功') {
                    wx.showToast({
                        title: res.msg,
                        icon: "none"
                    })
                    return;
                } else {
                    items.forEach(v => {
                        let i = list.findIndex(value => v.sa_quotedprice_itemsid == value.sa_quotedprice_itemsid);
                        if (i != -1) {
                            v.discountrate = (v.discountrate * 100).toFixed(2);
                            this.setData({
                                sumamount: CNY(currency(this.data.sumamount).subtract(list[i].amount).add(v.amount))
                            })
                            v.showAmount = CNY(v.amount)
                            this.data.list[i] = Object.assign(list[i], v);
                        }
                    });

                }
                this.setData({
                    list
                })
                let page = getCurrentPages().find(v => v.__route__ == 'packageA/offers/detail');
                if (page) {
                    let index = page.data.list1.findIndex(v => v.label == '总金额');
                    if (index != -1) page.setData({
                        [`list1[${index}].value`]: this.data.sumamount
                    })
                }

            })
        }
    }
})