const _Http = getApp().globalData.http,
    currency = require("../../utils/currency"),
    CNY = num => currency(num, {
        symbol: "￥",
        precision: 2
    }).format();

Page({
    data: {
        loading: true,
        sa_orderid: null,
        tabsActive: 0,
        tabsList: [{
            label: "借用工具明细",
            icon: "icon-tabchanpin",
            model: "#Product"
        }, {
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Yl_Attachment"
        }, {
            label: "订单进度",
            icon: "icon-tabcaozuojilu1",
            model: "#Progress"
        }],

    },
    onLoad(options) {
        this.setData({
            sa_orderid: options.id
        });
        this.getDetail(true);
    },
    onCopy() {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定复制该借用单',
            complete: (a) => {
                if (a.confirm) _Http.basic({
                    "id": "20240315131202",
                    "content": {
                        "sa_orderid": that.data.sa_orderid
                    }
                }).then(res => {
                    console.log("借用单复制", res)
                    if (res.msg != '成功') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    })
                    wx.showModal({
                        title: '提示',
                        content: '复制成功，是否立即前往',
                        complete: (s) => {
                            if (s.confirm) wx.navigateTo({
                                url: '/packageA/borrow/detail?id=' + res.data.sa_orderid,
                            })
                        }
                    })
                })
            }
        })
    },
    /* 获取详情 */
    getDetail(init = false, show = true) {
        _Http.basic({
            "id": 20230114140402,
            "content": {
                nocache: true,
                "sa_orderid": this.data.sa_orderid
            }
        }, show).then(res => {
            console.log("订单详情", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.msg,
                icon: "none"
            });

            res.data.amount = CNY(res.data.amount);
            this.setData({
                detail: res.data,
                loading: false
            });
            if (init) this.partialRenewal(true)
        })
    },
    /* 选择收货人 */
    selectConsignee() {
        if (this.isEdit()) return;
        wx.navigateTo({
            url: `/select/address/index?params=${JSON.stringify({ 
				"id":20221009155803,
				"content": {
					nocache:true,
					sys_enterpriseid:this.data.detail.sys_enterpriseid,
					"pageNumber": 1, 
					"pageTotal": 1, 
					"pageSize": 20,
					"where": {
						"condition": "",
						workaddress:1
						}, 
				}
			 })}&radio=true`,
        });
        getApp().globalData.handleSelect = this.setConsignee.bind(this);
    },
    /* 设置收货人 */
    setConsignee({
        item
    }) {
        let that = this;
        console.log("设置收货人", item)
        wx.showModal({
            title: '提示',
            content: `是否确认设置"${item.name}"为收货人？`,
            complete: (res) => {
                if (res.confirm) {
                    let rec_contactsid = that.data.detail.rec_contactsid;
                    that.setData({
                        "detail.rec_contactsid": item.contactsid
                    });
                    that.changeDetail().then(s => {
                        if (s.msg == '成功') {
                            wx.showToast({
                                title: '设置成功',
                                icon: "none"
                            });
                            setTimeout(() => {
                                wx.navigateBack();
                                that.getDetail();
                            }, 500)
                        } else {
                            that.setData({
                                "detail.rec_contactsid": rec_contactsid
                            });
                        }
                    })
                }
            }
        })
    },
    /* 选择财务信息 */
    selectFinance() {
        if (this.isEdit()) return;
        wx.navigateTo({
            url: `/select/finance/index?params=${JSON.stringify({ 
				"id":20221013160602,
				"content": {
					nocache:true,
					sys_enterpriseid:this.data.detail.sys_enterpriseid,
					"pageNumber": 1, 
					"pageTotal": 1, 
					"pageSize": 20,
					"where": {
						"condition": "",
					}, 
				}
			 })}&radio=true`,
        });
        getApp().globalData.handleSelect = this.setFinance.bind(this);
    },
    /* 设置财务信息 */
    setFinance({
        item
    }) {
        let that = this;
        console.log("设置财务信息", item)
        wx.showModal({
            title: '提示',
            content: `是否确认设置"${item.enterprisename}"为开票单位？`,
            complete: (res) => {
                if (res.confirm) {
                    let sys_enterprise_financeid = that.data.detail.sys_enterprise_financeid;
                    that.setData({
                        "detail.sys_enterprise_financeid": item.sys_enterprise_financeid
                    });
                    that.changeDetail().then(s => {
                        if (s.msg == '成功') {
                            wx.showToast({
                                title: '设置成功',
                                icon: "none"
                            });
                            setTimeout(() => {
                                wx.navigateBack();
                                that.getDetail();
                            }, 500)
                        } else {
                            that.setData({
                                "detail.sys_enterprise_financeid": sys_enterprise_financeid
                            });
                        }
                    })
                }
            }
        })
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    //局部数据更新 tabs
    partialRenewal(init = false) {
        let model = this.data.tabsList[this.data.tabsActive].model;
        if (model) {
            let Component = this.selectComponent(model),
                {
                    total,
                    pageNumber,
                    pageTotal
                } = Component.data.content,
                id = this.data.detail.sa_orderid;
            if (model == '#Product') id = {
                id: this.data.detail.sa_orderid,
                toolcount: this.data.detail.toolcount || ""
            };
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            }
        }
    },
    onReachBottom() {
        this.partialRenewal();
    },
    /* 更新数据 */
    changeDetail() {
        let data = this.data.detail,
            content = {
                "sa_orderid": data.sa_orderid,
                "sys_enterpriseid": data.sys_enterpriseid, //订货企业id
                "sa_accountclassid": data.accountclass.sa_accountclassid || 0, //营销账户类型ID
                "sa_brandid": data.sa_brandid, //品牌ID
                "sys_enterprise_financeid": data.sys_enterprise_financeid || 0, //合作企业财务信息ID（开票信息）
                "rec_contactsid": data.rec_contactsid || 0, //合作企业联系人表ID（收货信息）
                "type": data.type, //订单类型
                "typemx": data.typemx, // 明细分类，可选
                "remarks": data.remarks,
                sa_contractid: data.sa_contractid,
                "saler_hrid": data.saler_hrid, //销售人员hrid,业务员hrid
                "tradefield": data.tradefield, //必选
                "pay_enterpriseid": data.pay_enterpriseid, //结算单位
            };
        return new Promise((resolve, reject) => {
            _Http.basic({
                "id": 20230116092702,
                content
            }).then(res => {
                console.log("修改订单数据", res);
                if (res.msg != '成功') wx.showToast({
                    title: res.msg,
                    icon: "none"
                });
                resolve(res)
            })
        })
    },
    /* 修改订单备注 */
    changeRemarks(e) {
        let value = e.detail.value,
            remarks = this.data.detail.remarks,
            that = this;
        if (value == this.data.detail.remarks) return;
        wx.showModal({
            title: '提示',
            content: '是否确定修改订单备注？',
            complete: async (res) => {
                if (res.cancel) that.setData({
                    "detail.remarks": remarks
                })
                if (res.confirm) {
                    this.data.detail.remarks = value;
                    let res = await that.changeDetail();
                    that.setData({
                        "detail.remarks": res.msg == '成功' ? value : remarks
                    })
                }
            }
        })
    },
    /* 删除订单 */
    deleteItem() {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确认删除订单？',
            complete: (res) => {
                if (res.confirm) _Http.basic({
                    "id": 20230116100002,
                    "content": {
                        "sa_orderids": [
                            that.data.sa_orderid
                        ]
                    }
                }).then(s => {
                    console.log("删除订单", s)
                    if (s.msg != '成功') return wx.showToast({
                        title: s.msg,
                        icon: "none"
                    });
                    wx.showToast({
                        title: `成功删除${that.data.detail.sonum}订单`,
                        icon: "none"
                    });
                    setTimeout(() => {
                        /*  let page = getCurrentPages().find(v => v.__route__ == 'packageA/orderForm/index');
                         if (page) page.setData({
                             list: page.data.list.filter(v => v.sa_orderid != that.data.sa_orderid),
                             "content.total": page.data.content.total - 1,
                             amount: (page.data.amount - that.data.detail.amount).toFixed(2)
                         }); */
                        wx.navigateBack()
                    }, 500)
                })
            }
        })
    },
    /* 提交订单 */
    submit() {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确认提交订单？',
            complete: (res) => {
                if (res.confirm) _Http.basic({
                    "id": 20230114160002,
                    "content": {
                        sa_orderid: that.data.sa_orderid
                    },
                }).then(s => {
                    console.log("提交订单", s)
                    wx.showToast({
                        title: s.msg != '成功' ? s.msg : '提交成功',
                        icon: "none"
                    });
                    if (s.msg == '成功') that.setData({
                        "detail.status": "提交"
                    })
                })
            }
        })
    },
    /* 确认订单交期 */
    notarize() {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确认交期？',
            complete: (res) => {
                if (res.confirm) _Http.basic({
                    "id": 20230129154102,
                    "content": {
                        sa_orderid: that.data.sa_orderid
                    },
                }).then(s => {
                    console.log("确认交期", s)
                    wx.showToast({
                        title: s.msg != '成功' ? s.msg : '确认成功',
                        icon: "none"
                    });
                    if (s.msg == '成功') {
                        that.setData({
                            "detail.status": "交期确认"
                        })
                    }
                })
            }
        })
    },
    /* 判断是否可以编辑 */
    isEdit() {
        if (this.data.detail.status != '新建') wx.showToast({
            title: '当前订单状态不可设置!',
            icon: "none"
        });
        return this.data.detail.status != '新建';
    },
    /* 设置项目订单品牌领域 */
    setBraned() {
        wx.navigateTo({
            url: './modules/setBrand/index?id=' + this.data.sa_orderid,
        })
    },
    onUnload() {
        let page = getCurrentPages().find(v => v.__route__ == 'packageA/borrow/index');
        let content = JSON.parse(JSON.stringify(page.data.content));
        content.pageNumber = 1;
        content.pageSize = (page.data.content.pageNumber - 1) * page.data.content.pageSize;
        _Http.basic({
            "id": 20230114105002,
            content
        }).then(res => {
            console.log("更新借用单", res)
            page.setData({
                list: res.data.map(v => {
                    v.amount = CNY(v.amount)
                    return v
                }),
                "content.total": res.total,
            })
            /* amount: res.tips.amount || 0 */
        })
    },
})