/*******************************************************************************
 * Copyright(c) 2021 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：客户收款确认
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		jyh		     2022-5-25		        1.00		   	    新建
 *******************************************************************************/
const api = require('../../../../utils/api');
const app = getApp()
const Constants = require('../../../../utils/Constants');
const util = require('../../../../utils/util.js')
const config = require('../../../../config/config.js');
import Dialog from '../../../../dist/dialog/dialog.js';
const chooseGoodsCommon = require('../../../../utils/chooseGoodsCommon');
Page({
    /**
     * 页面的初始数据
     */
    data: {
        active: 0,
        activeNames: [
          "1"
        ],
        annexPaths: [],
        btnTitle: "收款成交",
        dealFalg: "true",
        disabledSave: true,
        fileList: [],
        form: {
          balanceAmount: 0,
          customer: {
            addressFull: "辽宁省沈阳市浑南区沈阳市浑南区人民政府(新聪街西)1",
            addressName: "沈阳市浑南区人民政府(新聪街西)",
            bankAccount: "",
            customerName: "ZHANGZAHNG",
            customerPhone: "13512341234"
          },
          fileList: [],
          order: {},
          orderDetail: [],
          orderId: "",
          orgCode: "",
          receivable: 0,
          remarks: "",
          staffCode: "",
          sumAmount: "70000"
        },
        guId: "474fd125-7b97-4c30-88f2-5dd731fd111b",
        guid: "",
        page: "orderBillingAdd",
        pageIndex: "undefined",
        settlementTypeFlag: true,
        settlementTypeList: [
            {
                accountType: "收款账户类型-现金",
                accountname: "现金",
                addressFull: null,
                ascpId: null,
                categoryCode: null,
                categoryId: null,
                categoryName: null,
                channelId: null,
                checked: true,
                code: null,
                contactName: null,
                deliveryPhone: null,
                cpId: null,
                customerPhone: null,
                defSettlementType: 516,
                defWhId: null,
                erpOrgCode: null,
                erpStaffCode: null,
                flgStore: false,
                flgValid: null,
                id: null,
                imageReceiptCode: null,
                imageReceiptCode_ping: "https://hgscrm-dev.oss-cn-shenzhen.aliyuncs.com/null",
                jobId: 0,
                keyWords: null,
                name: null,
                objCode: null,
                objId: null,
                objName: null,
                objType: null,
                objTypeName: null,
                orgAscpId: null,
                orgAscpName: null,
                orgCode: null,
                orgId: null,
                orgName: null,
                orgSale2Id: null,
                orgSale2Name: null,
                orgSalesChannel: null,
                orgSalesChannelName: null,
                parentId: null,
                phone: null,
                postId: null,
                postName: null,
                qvUserid: null,
                remarks: null,
                sale1Id: null,
                sale2Id: null,
                salesChannel: null,
                salesChannelName: null,
                sumAmount: "70000",
                toiletsNum: null,
                typeId: 516,
                typeName: "无库无ERP00001",
                whId: null,
                whName: null
            },
            {
                accountType: "收款账户类型-现金",
                accountname: "现金",
                addressFull: null,
                ascpId: null,
                categoryCode: null,
                categoryId: null,
                categoryName: null,
                channelId: null,
                code: null,
                contactName: null,
                deliveryPhone: null,
                cpId: null,
                customerPhone: null,
                defSettlementType: 516,
                defWhId: null,
                erpOrgCode: null,
                erpStaffCode: null,
                flgStore: false,
                flgValid: null,
                id: null,
                imageReceiptCode: null,
                imageReceiptCode_ping: "https://hgscrm-dev.oss-cn-shenzhen.aliyuncs.com/null",
                jobId: 0,
                keyWords: null,
                name: null,
                objCode: null,
                objId: null,
                objName: null,
                objType: null,
                objTypeName: null,
                orgAscpId: null,
                orgAscpName: null,
                orgCode: null,
                orgId: null,
                orgName: null,
                orgSale2Id: null,
                orgSale2Name: null,
                orgSalesChannel: null,
                orgSalesChannelName: null,
                parentId: null,
                phone: null,
                postId: null,
                postName: null,
                qvUserid: null,
                remarks: null,
                sale1Id: null,
                sale2Id: null,
                salesChannel: null,
                salesChannelName: null,
                sumAmount: 0,
                toiletsNum: null,
                typeId: 548,
                typeName: "无库无ERP00002",
                whId: null,
                whName: null
            }
        ]
     
      
      },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      
    },
    /**
     * 显示放大图片
     * @param {*} e 
     */
    previewImg: function (e) {
        let imgs = [e.currentTarget.dataset.imgurl]
        wx.previewImage({
            urls: imgs,
            current: e.currentTarget.dataset.imgurl, //当前图片地址
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
        })
    },

    /**
     *得到初始化数据
     */
    getinitdata(orgId) {
        let param = {
            orgId: app.globalData.user.orgId,
            cpId: app.globalData.user.cpId
        }
        //按单据的部门获取默认结算方式
        if (this.data.page == 'orderBillingAdd' || this.data.page == 'orderBilling') {
            param.orgId = this.data.typeForm.orgId
        }




        api.request(Constants.BASIC_COMMON_API + 'select_settlement_by_org', 'POST', param).then(res => {
            if (res.data.code === 200) {
                let list = res.data.data
                if (list && list.length > 0) {
                    list.forEach(element => {
                        element.sumAmount = 0
                        if (element.typeId == element.defSettlementType) { //根据组织机构中得默认结算方式id 勾选出默认得
                            element.checked = true
                            element.sumAmount = this.data.form.sumAmount
                        }
                        element.typeName = element.typeName ? element.typeName : ''
                        element.typeId = element.typeId ? element.typeId : null
                        element.imageReceiptCode_ping = config.server_img_http + element.imageReceiptCode
                    });
                    list.forEach(res => {
                        if (res.accountType) {
                            let accountTypeList = res.accountType.split('-')
                            res.accountname = accountTypeList[1]
                        }

                    })
                } else {
                    //没有结算方式 设置变量 点击收款按钮返回 提示:当前没有结算方式
                    this.setData({
                        settlementTypeFlag: false
                    })
                }

                this.setData({
                    settlementTypeList: list
                })
            }
        })
    },

    /**
     * @desc : checkbox点击事件 
     * @date : 2022/5/23 15:16
     */
    catchtapCheck(e) {
        let item = e.currentTarget.dataset.item
        let list = this.data.settlementTypeList
        let form = this.data.form
        let index = e.target.dataset.index


        if (list && list.length > 0) {
            if (this.data.type == 0 || this.data.type == 4 || this.data.type == 3 || (this.data.page == 'orderBilling' && this.data.type == 1)) {
                //客户收款结算方式单选
                list.forEach(item => {
                    item.checked = false
                })
                list.forEach(res => {
                    if (res.typeId === item.typeId) {
                        res.checked = !res.checked
                    }
                })
                let settlementTypeListLength = list.filter(item => {
                    return item.checked
                })
                if (settlementTypeListLength.length == 1) {
                    list.forEach(res => {
                        if (res.checked) {
                            res.sumAmount = form.sumAmount
                        }
                    })
                }
                this.setData({
                    settlementTypeList: list,
                    settlementTypeListLength: settlementTypeListLength.length //已选数量
                })
            } else {
                //客户收款结算方式多选
                if (list[index].checked) {
                    list[index].sumAmount = Number(0)
                }
                list.forEach(res => {
                    if (res.typeId === item.typeId) {
                        res.checked = !res.checked
                    }
                })
                //已选数量
                let settlementTypeListLength = list.filter(item => {
                    return item.checked
                })

                if (settlementTypeListLength.length == 1) {
                    list.forEach(res => {
                        if (res.checked) {
                            res.sumAmount = form.sumAmount
                        }
                    })
                }
                let sumAmountFlag = true
                if (settlementTypeListLength.length == 0) {
                    form.sumAmount = form.sumTempAmount
                    sumAmountFlag = false
                    this.setData({
                        sumAmountFlag: false
                    })

                } else {
                    sumAmountFlag = true
                    this.setData({
                        sumAmountFlag: true
                    })
                }

                this.setData({
                    form: form,
                    settlementTypeList: list,
                    settlementTypeListLength: settlementTypeListLength.length //已选数量
                })
                if (sumAmountFlag) {
                    this.getSumAmount(list)
                }

            }
        }
    },


    //结算方式金额输入事件
    sumAmountBindValue(e) {

        let settlementTypeList = this.data.settlementTypeList
        let value = e.detail.value ? Number(e.detail.value) : 0
        let index = e.currentTarget.dataset.index
        settlementTypeList[index].sumAmount = value
        this.setData({
            settlementTypeList: settlementTypeList
        })
        this.getSumAmount(settlementTypeList)
    },

    getSumAmount(settlementTypeList) {
        let form = this.data.form
        let sumAmountTemp = Number(0)
        if (settlementTypeList && settlementTypeList.length > 0) {
            settlementTypeList.forEach(res => {
                if (res.checked) {
                    sumAmountTemp = util.AddNumber(sumAmountTemp, res.sumAmount ? res.sumAmount : 0)
                }
            })
            form.sumAmount = sumAmountTemp
            this.setData({
                form: form
            })
        }

    },

    /**
     * @desc : 销售价格编辑
     * @author : 常皓宁
     * @date : 2022/5/31 14:45
     */
    changeSalesPriceField(e) {
        let form = this.data.form
        form.sumAmount = e.detail.value;
        let settlementTypeList = this.data.settlementTypeList
        if (settlementTypeList && settlementTypeList.length > 0) {
            settlementTypeList.forEach(res => {
                if (res.checked) {
                    res.sumAmount = Number(e.detail.value ? e.detail.value : 0);
                }
            })
        }

        this.setData({
            settlementTypeList: settlementTypeList,
            form
        })
    },


    /**
     * @desc : checkbox点击事件 
     * @date : 2022/5/23 15:16
     */
    onChangeFlag(e) {
        let item = e.currentTarget.dataset.item
        let list = this.data.settlementTypeList
        list.forEach(res => {
            if (res.settlementTypeId === item.settlementTypeId) {
                res.checked = true
            } else {
                res.checked = false
            }
        })
        this.setData({
            settlementTypeList: list
        })
    },

    /**
     * @desc : 手风琴展开事件
     * @author : 于继渤
     * @date : 2022/5/26 12:16
     */
    onChange(event) {
        this.setData({
            activeNames: event.detail,
        });
    },
    /* 客户收款-表单校验 */
    checkForm() {
        let form = this.data.form
        if (!form.staffID) {
            return {
                flag: false,
                msg: '请选择业务员'
            };
        }
        if (!form.orgID) {
            return {
                flag: false,
                msg: '请选择业务部门'
            };
        }
        if (!form.salesChannelID) {
            return {
                flag: false,
                msg: '请选择销售渠道'
            };
        }
        if (!form.customer.customerId) {
            return {
                flag: false,
                msg: '请选择客户'
            };
        }

        return {
            flag: true,
            msg: '表单校验通过'
        }
    },
    /**
     * 收款保存
     * @param {*} e 
     */
    btnOK(e) {
        if (this.data.type == '0') {
            if (this.data.form.sumAmount < 0) {
                Dialog.confirm({
                    title: '提示信息',
                    showCancelButton: false,
                    message: '收款不能为负数，如需退款请使用退款申请',
                })
                return
            }
        }
        if (this.data.page == 'orderBilling' && (this.data.type == '1' || this.data.type == '0')) {
            if (this.data.form.sumAmount < 0) {
                Dialog.confirm({
                    title: '提示信息',
                    showCancelButton: false,
                    message: '收款不能为负数，如需退款请使用退款申请',
                })
                return
            }

        }
        this.setData({
            loadingButtonFlag: true
        })
        if (this.data.settlementTypeList && this.data.settlementTypeList.length == 0) {
            wx.showToast({
                title: '当前没有结算方式',
                icon: 'none',
                duration: 1000
            })
            this.setData({
                loadingButtonFlag: false
            })
            return
        }
        let settlementTypeListTempLength = this.data.settlementTypeList.filter(item => {
            return item.checked
        })
        if (settlementTypeListTempLength.length == 0) {
            wx.showToast({
                title: '请选择结算方式',
                icon: 'none',
                duration: 1000
            })
            this.setData({
                loadingButtonFlag: false
            })
            return
        }
        if (!this.data.sumAmountFlag) {
            wx.showToast({
                title: '当前没有结算方式',
                icon: 'none',
                duration: 1000
            })
            this.setData({
                loadingButtonFlag: false
            })
            return
        }
        //没有结算方式 设置变量 点击收款按钮返回 提示:当前没有结算方式
        if (!this.data.settlementTypeFlag) {
            wx.showToast({
                title: '当前没有结算方式',
                icon: 'none',
                duration: 1000
            })
            this.setData({
                loadingButtonFlag: false
            })
            return
        }
        //表单提交分支
        // 0: 无订单的客户收款  1:订单收款 2 退换补收款 3 销售退货收款 4 客户退款
        if (this.data.type == 0) {
            let result = this.checkForm();
            if (!result.flag) {
                wx.showToast({
                    title: result.msg,
                    image: '/static/image/warning.png',
                    duration: 1000
                })
                this.setData({
                    loadingButtonFlag: false
                })
                return
            }
            let settlementTypeList = this.data.settlementTypeList
            let settlementTypeID = ''
            let settlementTypeName = ''
            settlementTypeList.forEach(element => {
                if (element.checked) {
                    settlementTypeID = element.typeId
                    settlementTypeName = element.typeName
                }
            });
            if (settlementTypeID == '') {
                wx.showToast({
                    title: "请选择收款方式",
                    image: '/static/image/warning.png',
                    duration: 1000
                })
                this.setData({
                    loadingButtonFlag: false
                })
                return
            }
            this.setData({
                loading: true,
                loadingButtonFlag: true
            })
            let form = this.data.form

            let param = {}
            let fileList_ = this.data.fileList
            let fileList = []
            fileList_.forEach(item => {
                fileList.push(
                    {
                        url: item.FilePath,
                        type: 'image',
                        name: '',
                        createTime: util.formatDataTime(new Date())
                    })
            })
            param.annexPaths = fileList

            // 跟进附件 20220613
            if (form.editTime) {
                param.editTime = form.editTime
            }
            param.staffId = Number(form.staffID) // 业务员
            param.orgId = Number(form.orgID) // 业务部门
            param.salesChannel = Number(form.salesChannelID) // 渠道
            param.customerId = form.customer.customerId //客户
            //收款 
            if (form.customerForm && form.customerForm.deliveryPhone && (form.customerForm.deliveryPhone.indexOf(',') != -1 || form.customerForm.deliveryPhone instanceof Array)) {
                param.deliveryPhone = form.customerForm.deliveryPhone ? form.customerForm.deliveryPhone.join(",") : null
            }
            param.settlementType = settlementTypeID //结算方式
            param.sumAmount = form.sumAmount
            param.receiptDirection = 1
            param.docCode = "客户收款"
            param.ascpId = app.globalData.user.ascpId
            param.sale1Id = app.globalData.user.sale1Id
            param.userCode = app.globalData.user.userCode
            param.makingUser = app.globalData.user.userId
            param.makingTime = util.formatDataTime(new Date())
            param.userName = app.globalData.user.userName
            param.balanceAmount = form.receivable ? ((form.sumAmount - form.receivable) > 0 ? (form.sumAmount - form.receivable) : 0) : form.sumAmount
            //如果关联了订单  剩余可用（可用余额） =  本次收款-应收 
            param.sumRefundAmount = 0 //使用额
            param.cpId = app.globalData.user.cpId,
                param.orderId = form.orderId
            let SAVE_API = 'insert'
            //判断是否关联了订单 关联走下面的接口
            if (param.orderId) {
                SAVE_API = 'insert_deposit'
            }
            //2023/11/06 于继渤  微信小程序 收款网络异常重复提交问题
            param.wxGuId = this.data.guId
            // iboss用到的参数 下面
            param.addressFull = form.addressFull //详细地址
            param.salesChannelName = form.salesChannelName //渠道
            param.organizationCode = form.orgCode //组织结构编码
            param.staffCode = form.staffCode //业务员编码
            param.settlementTypeName = settlementTypeName //结算方式
            param.decisionMakerName = form.customer.decisionMakerName  //决策者
            param.decorationStyleName = form.customer.fitupStyleName  //风格
            param.customerAgeGroupName = form.customer.ageCompositionName  //年龄 （80后）
            param.homeHouseTypeName = form.customer.houseTypeName //房屋类型    
            param.customerCode = form.customer.customerCode //客户编码
            param.customerName = form.customer.customerName
            param.customerTelephone = form.customer.customerCode //客户编码
            param.customerFromName = form.customer.customerFromName
            param.remarks = form.remarks ? form.remarks : ''
            param.erpPushStatus = Constants.ERP_PUSH_STATUS.NO_PUSH_STATUS
            // 用户erpUserCode20220820
            param.erpUserCode = app.globalData.user.erpUserCode//iboss用户

            if (!param.remarks) {
                param.remarks = ''
            }
            if (!param.annexPaths || param.annexPaths.length == 0) {
                param.annexPaths = []
            }
            api.request(Constants.ORDER_RECEIPT_PC_API + SAVE_API, 'POST', param).then(res => {
                this.setData({
                    loading: false
                })
                if (res.data.code === 200) {
                    wx.showToast({
                        title: '保存成功',
                        image: '/static/image/success.png',
                        duration: 1000
                    })
                    var pages = getCurrentPages();
                    var prevPage = pages[pages.length - 2];

                    setTimeout(function () {
                        wx.navigateBack({
                            delta: 2
                        })
                    }, 1500)
                } else {
                    this.setData({
                        loadingButtonFlag: false
                    })
                }
            })
        } else if (this.data.type == 1) {
            //订单收款
            this.setData({
                loading: true,
                loadingButtonFlag: true
            })
            let that = this
            let param = this.data.typeForm
            if (this.data.page == 'orderBilling' && this.data.form.sumAmount < 0) {
                param.bankAccount = this.data.form.customer.bankAccount
            }
            let settlementTypeList = this.data.settlementTypeList
            let tempOBJ = {}
            settlementTypeList.forEach(res => {
                if (res.checked) {
                    tempOBJ = res
                }
            })
            param.erpPushStatus = Constants.ERP_PUSH_STATUS.NO_PUSH_STATUS
            let tsumAmount = param.sumAmount //合计金额
            //收款金额 (输入的)
            let sumAmount = that.data.form.sumAmount
            if (this.data.page === 'orderBilling') {
                param.erpPushStatus = Constants.ERP_PUSH_STATUS.NO_PUSH_STATUS
                //客户收款 定金 
                param.receiptVOList = []
                tsumAmount = param.receivable
            } else {
                // 剩余应收=合计金额-收款金额
                param.receivable = Number(tsumAmount - sumAmount - Number(param.sumUsePrestore ? param.sumUsePrestore : 0)) ? Number(tsumAmount - sumAmount - Number(param.sumUsePrestore ? param.sumUsePrestore : 0)) : 0

            }
            if (this.data.settlementTypeList && this.data.settlementTypeList.length > 0) {
                let settlementTypeList = this.data.settlementTypeList.filter(item => {
                    return item.checked
                })
                settlementTypeList.forEach(res => {
                    if (isNaN(res.sumAmount)) {
                        res.sumAmount = 0
                    }
                    let OBJ = {
                        //结算方式
                        settlementType: res.typeId,
                        sumAmount: res.sumAmount ? Number(res.sumAmount) : 0,
                        settlementTypeName: res.typeName,
                        typeName: res.typeName,
                        typeId: res.typeId,
                    }
                    if (app.globalData.user.sale1Id) {
                        OBJ['sale1Id'] = app.globalData.user.sale1Id
                    }
                    if (app.globalData.user.sale2Id) {
                        OBJ['sale2Id'] = app.globalData.user.sale2Id
                    }
                    if (app.globalData.user.ascpId) {
                        OBJ['ascpId'] = app.globalData.user.ascpId
                    }
                    if (app.globalData.user.userId) {
                        OBJ['makingUser'] = app.globalData.user.userId
                    }



                    OBJ['makingTime'] = util.formatDataTime(new Date())
                    let annexPaths = []
                    // if(this.data.annexPaths && this.data.annexPaths.length > 0){
                    //     annexPaths.push({
                    //         url: data.data.relativePath,
                    //         type: 'image',
                    //         docType:'客户收款',
                    //         name: file[file.length - 1],
                    //         createTime: util.formatDataTime(new Date())
                    //       })
                    // }
                    OBJ['annexPaths'] = this.data.annexPaths
                    //收款数组
                    param.receiptVOList.push(OBJ)
                })
            }
            let numOne = util.numSub(tsumAmount, Number(param.sumUsePrestoreTemp ? param.sumUsePrestoreTemp : 0))
            // 收款状态
            if (Number(sumAmount) == 0 && Number(sumAmount) != Number(numOne)) {
                //未收款
                param.receiptStatus = Constants.RECEIPT_STATUS_CONSTANT.RECEIPT_STATUS_UNCOLLECTED;
            }
            else if (Number(sumAmount) < Number(numOne)) {
                //部分收款
                param.receiptStatus = Constants.RECEIPT_STATUS_CONSTANT.RECEIPT_STATUS_PART;
            } else if (Number(sumAmount) > Number(numOne)) {
                //部分收款
                param.receiptStatus = Constants.RECEIPT_STATUS_CONSTANT.RECEIPT_STATUS_PART;
            }
            else {
                //收款完成
                param.receiptStatus = Constants.RECEIPT_STATUS_CONSTANT.RECEIPT_STATUS_COMPLETE;
            }
            let SAVE_API = 'insert'
            // //收款成交
            if (this.data.dealFalg) {
                //送货日期
                param.deliveryTime = param.deliveryTime ? param.deliveryTime.replaceAll("/", "-") : util.formatDataTime(new Date())
                SAVE_API = 'insert'
            } else {
                //订单收款,修改总单信息
                SAVE_API = 'update'
            }
            let API = Constants.SALE_ORDER_API
            if (this.data.page === 'orderBilling') {
                param.sumReceiptAmount = Number(sumAmount) + Number(param.sumReceiptAmount)
                param.sumCollectedAmount = Number(sumAmount)
                param.sumAmount = Number(sumAmount)
                param.settlementType = tempOBJ.typeId
                param.settlementTypeName = tempOBJ.typeName,
                    param.typeName = tempOBJ.typeName
                param.makingUser = app.globalData.user.userId
                //2023/11/06 于继渤  微信小程序 收款网络异常重复提交问题
                param.wxGuId = this.data.guId
                if (param.editTimeFlag) {
                    param.editTime = util.formatTime(new Date(param.editTime)).replaceAll('/', '-')
                } else {
                    if (param.editTime.indexOf('/') != -1) {
                        param.editTime = param.editTime.replaceAll('/', '-')
                    } else {
                        if (param.editTime.indexOf('T') != -1) {
                            param.editTime = util.formatDataTime(new Date(param.editTime))
                        }
                    }

                }
                SAVE_API = 'insert_deposit'
                API = Constants.ORDER_RECEIPT_PC_API

            } else {
                //2023/11/06 于继渤  微信小程序 收款网络异常重复提交问题
                param.wxGuId = this.data.guId
                //收款合计
                param.sumReceiptAmount = util.AddNumber(Number(sumAmount ? sumAmount : 0), Number(param.sumReceiptAmount))
                param.sumCollectedAmount = util.AddNumber(Number(param.sumUsePrestore), Number(param.sumReceiptAmount))
            }
            if (this.data.form.remarks != '') {
                param.remarks = this.data.form.remarks
            }
            param.tSumGoodsAmount = Number(param.tSumGoodsAmount)
            if (!param.remarks) {
                param.remarks = ''
            }
            if (!param.annexPaths || param.annexPaths.length == 0) {
                param.annexPaths = []
            }
            if (this.data.noConfirm && this.data.noConfirm == '1') {
                delete param['sumReceipt']
            }


            this.getNetwork().then(res=>{
                if (!res) {
                    that.setData({
                        loading: false,
                        disabledSave: false
                    })
                    wx.showToast({
                        title: '网络不可用!',
                        icon: 'none'
                    })
    
                    return
                }
            })
   
          
            // console.log('param', param)
       
            api.request(API + SAVE_API, 'POST', param).then(res => {
                that.setData({
                    loading: false,
                })
                if (res.data.code === 200) {
                    wx.showToast({
                        title: '保存成功',
                        image: '/static/image/success.png',
                        duration: 1000
                    })
                    this.setData({
                        disabledSave: false,
                        loadingButtonFlag: true,
                    })

                    //首页购物车跳转列表页
                    if (this.data.pageIndex == 'shopping') {
                        setTimeout(function () {
                            wx.reLaunch({
                                url: '/pages/home-page/home-page?pageType=1',
                            })
                        }, 1000)
                        return
                    }
                    if (this.data.pageIndex == 'receiveCustomers') {

                        wx.navigateBack({
                            delta: 4
                        })

                        return

                    }
                    var pages = getCurrentPages();
                    // debugger
                    if (this.data.page == 'orderBilling' && this.data.dealFalg == 'false') {
                        //返回一览页面
                        var prevPage = pages[pages.length - 2];
                        if (prevPage) {
                            prevPage.setData({
                                orderAddFlag: true
                            })
                        }
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 1
                            })
                        }, 1000)
                        return
                    }
                    if (this.data.page == 'orderBilling' && this.data.dealFalg == 'true') {
                        //返回一览页面
                        var prevPage = pages[pages.length - 3];
                        if (prevPage) {
                            prevPage.setData({
                                orderAddFlag: true
                            })
                        }
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 2
                            })
                        }, 1000)
                        return
                    } if (this.data.page == 'orderBillingDeal') {
                        //返回列表页面
                        var prevPage = pages[pages.length - 3];
                        if (prevPage) {
                            prevPage.setData({
                                orderAddFlag: true
                            })
                        }

                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 2
                            })
                        }, 1000)
                        return
                    } if ((this.data.page == 'orderBillingAdd') && this.data.typeForm.orderId) {
                        //返回列表页面
                        var prevPage = pages[pages.length - 5];
                        if (prevPage) {
                            prevPage.setData({
                                orderAddFlag: true
                            })
                        }

                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 4
                            })
                        }, 1000)
                        return
                    } if ((this.data.page == 'orderBillingAdd') && this.data.noConfirm) {
                        //返回列表页面
                        var prevPage = pages[pages.length - 5];
                        if (prevPage) {
                            prevPage.setData({
                                orderAddFlag: true
                            })
                        }

                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 4
                            })
                        }, 1000)
                        return
                    } if ((this.data.page == 'orderBillingAdd') && this.data.noConfirm == '1') {
                        //返回列表页面
                        var prevPage = pages[pages.length - 5];
                        if (prevPage) {
                            prevPage.setData({
                                orderAddFlag: true
                            })
                        }

                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 4
                            })
                        }, 1000)
                        return
                    } if ((this.data.page == 'orderBillingAdd') && !this.data.typeForm.orderId) {
                        //返回列表页面
                        var prevPage = pages[pages.length - 6];
                        if (prevPage) {
                            prevPage.setData({
                                orderAddFlag: true
                            })
                        }
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 5
                            })
                        }, 1000)
                        return
                    } if (this.data.noConfirm == '1' && this.data.page != 'orderBillingAdd') {
                        //返回一览页面
                        var prevPage = pages[pages.length - 3];
                        prevPage.setData({
                            orderAddFlag: true
                        })
                        setTimeout(function () {
                            wx.navigateBack({
                                delta: 2
                            })
                        }, 1000)
                    }
                } else {
                    this.setData({
                        loadingButtonFlag: false
                    })
                }
            })
        } else if (this.data.type == 2) {
            //退换补
            this.setData({
                loading: true,
                loadingButtonFlag: true
            })
            let param = this.data.typeForm
            let settlementTypeList = this.data.settlementTypeList
            let tempOBJ = {}
            param.receiptVOList = []
            settlementTypeList.forEach(res => {
                if (res.checked) {
                    tempOBJ = res
                }
            })
            //收款金额 (输入的)
            let sumAmount = this.data.form.sumAmount
            //收款数组
            if (this.data.settlementTypeList && this.data.settlementTypeList.length > 0) {
                let settlementTypeList = this.data.settlementTypeList.filter(item => {
                    return item.checked
                })
                settlementTypeList.forEach(res => {
                    let OBJ = {
                        //结算方式
                        settlementType: res.typeId,
                        sumAmount: Number(res.sumAmount),
                        settlementTypeName: res.typeName,
                        typeName: res.typeName,
                        typeId: res.typeId,
                    }
                    if (app.globalData.user.sale1Id) {
                        OBJ['sale1Id'] = app.globalData.user.sale1Id
                    }
                    if (app.globalData.user.sale2Id) {
                        OBJ['sale2Id'] = app.globalData.user.sale2Id
                    }
                    if (app.globalData.user.ascpId) {
                        OBJ['ascpId'] = app.globalData.user.ascpId
                    }
                    if (app.globalData.user.userId) {
                        OBJ['makingUser'] = app.globalData.user.userId
                    }
                    OBJ['makingTime'] = util.formatDataTime(new Date())
                    OBJ['annexPaths'] = this.data.annexPaths
                    //收款数组
                    param.receiptVOList.push(OBJ)
                })
            }

            let tsumAmount = param.sumAmount //合计金额
            //服务费用 - 原单服务费用
            param.sumFeeAmount = Number(param.sumFeeAmount - param.sumFeeAmountTemp)
            param.cpId = app.globalData.user.cpId
       
            param.sumReceiptAmount = sumAmount
            param.sumCollectedAmount = Number(param.sumReceiptAmount)

            param.sumAmount = Number(sumAmount)
            let receivableTemp = Number(param.receivable) - Number(sumAmount);

            param.sumUsePrestore = Number(0)
            param.sumReceiptAmount = Number(param.sumReceiptAmount)
            param.receivable = Number(receivableTemp)
            delete param['sumAmount']
            delete param['tSumBackGoodsAmount']
            delete param['tSumEndGoodsAmount']
            delete param['sumReceipt']
            delete param['usablePrestore']

            delete param['sumAmount']
            delete param['makingTime']
            delete param['sumGoodsAmount']
            delete param['sumOutAmount']
            delete param['sumPromotion']
            delete param['sumQuantity']
            delete param['sumStandard']
            delete param['sumRejectAmount']

            api.request(Constants.SALE_ORDER_API + 'operation', 'POST', param).then(res => {
                this.setData({
                    loading: false
                })
                if (res.data.code === 200) {
                    if (res.data.data.message === '操作成功') {
                        wx.showToast({
                            title: '保存成功',
                            image: '/static/image/success.png',
                            duration: 1000
                        })
                        var pages = getCurrentPages();
                        var prevPage = pages[pages.length - 3];
                        prevPage.setData({
                            orderAddFlag: true
                        })
                        setTimeout(function () {

                            wx.navigateBack({
                                delta: 2
                            })
                        }, 1000)
                    } else {
                        this.setData({
                            loadingButtonFlag: false
                        })
                        wx.showToast({
                            title: res.data.data.message,
                            icon: 'none',
                            duration: 1500
                        })
                    }
                }
            })

        } else if (this.data.type == 3) {
            this.setData({
                loading: true,
                loadingButtonFlag: true
            })
            let settlementTypeList = this.data.settlementTypeList
            let receiptVOList = []
            let form = this.data.form
            if (settlementTypeList && settlementTypeList.length > 0) {
                let settlementTypeList = this.data.settlementTypeList.filter(item => {
                    return item.checked
                })
                settlementTypeList.forEach(res => {
                    let OBJ = {
                        //结算方式
                        settlementType: res.typeId,
                        sumAmount: Number(res.sumAmount),
                        itemAmount: Number(res.sumAmount),
                        settlementTypeName: res.typeName,
                        typeName: res.typeName,
                        typeId: res.typeId,
                    }
                    if (app.globalData.user.sale1Id) {
                        OBJ['sale1Id'] = app.globalData.user.sale1Id
                    }
                    if (app.globalData.user.sale2Id) {
                        OBJ['sale2Id'] = app.globalData.user.sale2Id
                    }
                    if (app.globalData.user.ascpId) {
                        OBJ['ascpId'] = app.globalData.user.ascpId
                    }
                    if (app.globalData.user.userId) {
                        OBJ['makingUser'] = app.globalData.user.userId
                    }
                    OBJ['makingTime'] = util.formatDataTime(new Date())
                    //收款数组
                    receiptVOList.push(OBJ)
                })
            }
            let sumAmount = this.data.form.sumAmount
            let param = this.data.typeForm
            delete param['tdiscountPromotion']
            delete param['tdiscountStandard']
            delete param['toiletCount']
            delete param['toiletCountName']
            delete param['tsumAmount']
            delete param['tsumGoodsAmount']
            delete param['tsumPromotion']
            delete param['tsumQuantity']
            delete param['tsumStandard']
            delete param['merOrderType']
            delete param['merOrderTypeName']
            delete param['sumOutAmount']
            delete param['receiptStatus']
            delete param['outStatus']
            param.editTime = param.editTimeTemp
            param.cpId = app.globalData.user.cpId
            param.receiptVOList = receiptVOList
            param.rejectReason = this.data.form.mReasonForReturn  //退货原因
            param.receivable = Number(param.receivable) - Number(sumAmount)
            param.refundAccount = this.data.form.mRefundAccountNumber //退款账号
            param.staffList = []
            param.orgList = []
            param.sumCollectedAmount = Number(sumAmount)
            param.sumAmount = Number(sumAmount)
            param.sumReceiptAmount = Number(sumAmount)
            param.orderOutRejectItemVOList = this.data.typeForm.orderOutRejectItemVOList
            api.request(Constants.ORDER_OUT_REJECT_PC_API + 'insert', 'POST', param).then(res => {
                this.setData({
                    loading: false
                })
                if (res.data.code === 200) {
                    wx.showToast({
                        title: '保存成功',
                        image: '/static/image/success.png',
                        duration: 1000
                    })
                    this.setData({
                        disabledSave: false
                    })
                    var pages = getCurrentPages();
                    var prevPage = pages[pages.length - 4];
                    // prevPage.setData({
                    //   orderAddFlag: true
                    // })
                    setTimeout(function () {
                        wx.navigateBack({
                            delta: 3
                        })
                    }, 1500)
                } else {
                    this.setData({
                        loadingButtonFlag: false
                    })
                }
            })

        } else if (this.data.type == 4) {
            let result = this.checkForm();
            if (!result.flag) {
                wx.showToast({
                    title: result.msg,
                    image: '/static/image/warning.png',
                    duration: 1000
                })
                return
            }
            let settlementTypeList = this.data.settlementTypeList
            let settlementTypeID = ''
            let settlementTypeName = ''

            settlementTypeList.forEach(element => {
                if (element.checked) {
                    settlementTypeID = element.typeId
                    settlementTypeName = element.typeName
                }
            });
            if (settlementTypeID == '') {
                wx.showToast({
                    title: "请选择收款方式",
                    image: '/static/image/warning.png',
                    duration: 1000
                })
                this.setData({
                    loadingButtonFlag: false
                })
                return
            }

            this.setData({
                loading: true,
                loadingButtonFlag: true
            })
            let form = this.data.form
            let param = {}
            let fileList_ = this.data.fileList
            let fileList = []
            fileList_.forEach(item => {
                fileList.push(
                    {
                        url: item.FilePath,
                        type: 'image',
                        name: '',
                        createTime: util.formatDataTime(new Date())
                    })
            })
            param.annexPaths = fileList
            param.staffId = Number(form.staffID) // 业务员
            param.orgId = Number(form.orgID) // 业务部门
            param.salesChannel = Number(form.salesChannelID)// 渠道
            param.customerId = form.customer.customerId //客户
            //收款
            param.sReceiptId = Number(form.sreceiptId)
            param.sReceiptNo = form.sreceiptNo
            param.settlementType = settlementTypeID
            param.customerCode = form.customer.customerCode
            param.customerName = form.customer.customerName
            param.sumAmount = -1 * form.sumAmount
            param.receiptDirection = -1
            param.docCode = "客户取款"
            param.balanceSumAmount = form.balanceSumAmount ? form.balanceSumAmount : 0
            param.balanceAmount = ((form.balanceAmount + form.sumAmount) > 0 ? (form.balanceAmount + form.sumAmount) : 0)  //剩余可用 - 之前可用加上本次退款（退款是负的 故相加）
            param.sumRefundAmount = -1 * form.sumAmount //使用额
            param.cpId = app.globalData.user.cpId,
                param.addressFull = form.customer.addressFull //详细地址
            param.salesChannelName = form.salesChannelName //渠道
            param.refundAccount = form.refundAccount //退款账号
            param.organizationCode = form.orgCode //组织结构编码
            param.staffCode = form.staffCode //业务员编码
            param.decisionMakerName = form.customer.decisionMakerName  //决策者
            param.decorationStyleName = form.customer.fitupStyleName  //风格
            param.customerAgeGroupName = form.customer.ageCompositionName  //年龄 （80后）
            param.settlementTypeName = settlementTypeName //结算方式
            param.homeHouseTypeName = form.customer.houseTypeName //房屋类型    
            param.customerCode = form.customer.customerCode //客户编码
            param.customerTelephone = form.customer.customerCode //客户编码
            param.erpPushStatus = Constants.ERP_PUSH_STATUS.NO_PUSH_STATUS
            param.remarks = form.remarks
            param.editTime = form.editTime ? form.editTime : null
            param.receiptId = Number(form.receiptId) ? Number(form.receiptId) : null

            api.request(Constants.ORDER_RECEIPT_PC_API + 'insert', 'POST', param).then(res => {
                this.setData({
                    loading: false
                })
                if (res.data.code === 200) {
                    wx.showToast({
                        title: '保存成功',
                        image: '/static/image/success.png',
                        duration: 1000
                    })
                    this.setData({
                        disabledSave: false
                    })
                    var pages = getCurrentPages();
                    var prevPage = pages[pages.length - 2];

                    setTimeout(function () {
                        wx.navigateBack({
                            delta: 2
                        })
                    }, 1500)
                } else {
                    this.setData({
                        loadingButtonFlag: false
                    })
                }
            })
        }
    },
    getNetwork() {
        return new Promise((resolve, reject) => {
            wx.getNetworkType({
                success(res) {
                    const networkType = res.networkType; if (networkType === 'none') {
                        console.log('无网络，返回false')
                        resolve(false)
                    } else {
                        console.log('有网络，返回true')
                        resolve(true)
                    }
                }
            })
        })
       
    },
    //tab切换
    onChangeTabs(e) {

        let title = e.detail.title
        if (title == '结算方式') {
            this.setData({
                active: 0
            })


        }
        if (title == '附件') {
            this.setData({
                active: 1
            })
        }
    },


    onChangeBankAccount(e) {

        let form = this.data.form
        form.customer.bankAccount = e.detail
        this.setData({
            form: form
        })
    },

    /**
     * @desc : 订单上传附件方法
     * @author : 于继渤
     * @date : 2022/6/02 16:16
     */
    afterRead(event) {
        const _this = this;
        const {
            file
        } = event.detail;

        let typeForm = _this.data.typeForm
        let arr = _this.data.fileList;
        var annexPaths = _this.data.annexPaths
        let type = this.data.type
        let formDataUrl = 't_order/annex_paths'
        if (type == 0 || type == 4) {
            //客户收款
            formDataUrl = 't_receipt/receipt'
        } else {
            annexPaths = typeForm.annexPaths ? typeForm.annexPaths : []
        }

        file.forEach(res => {
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            wx.uploadFile({
                url: `${config.server_add}:${config.server_port}` + '/basic-server/file/upload',
                filePath: res.path,
                name: 'file',
                formData: {
                    'folder': formDataUrl
                },
                header: {
                    'Authorization': 'Bearer ' + app.globalData.token
                },
                success(res) {
                    let data = JSON.parse(res.data)

                    if (data.code === 200) {
                        if (type == 0) {
                            let fileList_ = _this.data.form.fileList
                            fileList_.push({
                                url: data.data.absolutelyPath,
                                FilePath: data.data.relativePath,
                                deletable: true
                            })
                        }

                        arr.push({
                            url: data.data.absolutelyPath,
                            FilePath: data.data.relativePath,
                            deletable: true
                        })
                        let annexPathsTemp = []
                        let file = data.data.relativePath.split('/')
                        annexPathsTemp.push({
                            url: data.data.relativePath,
                            type: 'image',
                            insertFlag:true,
                            docType: '客户收款',
                            name: file[file.length - 1],
                            createTime: util.formatDataTime(new Date())
                        })
                        annexPaths.push({
                            url: data.data.relativePath,
                            type: 'image',
                            docType: '客户收款',
                            insertFlag:true,
                            name: file[file.length - 1],
                            createTime: util.formatDataTime(new Date())
                        })

                        typeForm.annexPaths = annexPaths
                        _this.setData({
                            fileList: arr,
                            annexPaths: annexPathsTemp,
                            typeForm: typeForm
                        })
                    }
                },
            })
        })

    },

    /**
* @desc : 删除图片
* @author : 于继渤
* @date : 2022/5/31 18:16
*/
    deleteImg(e) {
        let index = e.detail.index;
        let arr = this.data.fileList;
        arr.splice(index, 1);
        this.setData({
            fileList: arr,
            annexPaths: arr
        })
        console.log('annexPaths', this.data.annexPaths)
        console.log('fileList', this.data.fileList)
    },

    changeField(e) {

        let form = this.data.form
        form.remarks = e.detail
        this.setData({ form: form })
    },
})