/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述: 销售退货 -- 选择源单
 * 编辑履历：
 *		作者			  日期					版本				修改内容
 *		王英杰		     2022-5-25		        1.00		   	    新建
 *******************************************************************************/
const app = getApp();
const api = require('../../../../utils/api.js');
const Constants = require('../../../../utils/Constants.js');
const util = require('../../../../utils/util.js')
const common = require('../../../../utils/common.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [
      {
        addressArea: {
            city: "沈阳市",
            district: "和平区",
            province: "辽宁省"
            },
            addressFull: "辽宁省沈阳市和平区汤玉麟公馆旧址11111",
            addressGcj02: {
            latitude: 41.79179,
            longitude: 123.421643
            },
            addressName: "汤玉麟公馆旧址",
            addressNo: "11111",
            ageComposition: 98,
            ascpId: 29195,
            contactName: "",
            deliveryPhone: "",
            contractNo: "2312313333",
            cpId: 20760,
            customerFrom: -1,
            customerId: 3915,
            customerName: "12.21.01",
            customerPhone: "45454454444",
            decisionMaker: 102,
            deliveryTime: "2024-01-16T08:00:00+08:00",
            designStatus: "设计状态-无需",
            discountPromotion: 100,
            discountStandard: 11.24,
            docCode: "销售订单",
            editTime: "2024-01-15T17:00:34.375071+08:00",
            fitupStyle: 91,
            fitupType: 87,
            flgToErp: false,
            houseType: 84,
            linkPsiSystem: "DK-IBOSS",
            makingTime: "2024-01-15T17:00:34.439+08:00",
            makingUser: 1005,
            makingUserPur: 968,
            merOrderType: 0,
            orderId: 11767,
            orderItemVOList: [
                {
                activityId: 84,
                activityName: "零售活动方案",
                canReturnQuantity: 3,
                discountPromotion: 100,
                discountStandard: 11.24,
                erpOutItemId: 1435661,
                erpOutNo: "ZJSA72924011500006",
                flgDesign: false,
                flgGift: false,
                hasChild: 0,
                iconThumPath: "haip/2023-04-21/19ae78a2639547d9aa961b58d20dbdbd.png",
                id: "5d8d66b7-5e2c-4e63-b396-3786cef7d85d",
                itemId: 35537,
                itemIndex: 1,
                nonStandardArea: 1,
                nonStandardCode: "-",
                orderAmount: 2997,
                orderId: 11767,
                orderItemId: 35537,
                orderItemQuantity: 1,
                orderNo: "SA-QZHJ-BFJ-202401150RYC",
                orderPriceSale: 999,
                orderQuantity: 3,
                outId: 3382,
                outItemId: 6164,
                outNo: "WO-QZHJ-000-202401150RYD",
                outOutAmount: 2997,
                outOutQuantity: 3,
                outRejectAmount: 0,
                outRejectQuantity: 0,
                outStatus: 3,
                pathType: 2,
                pricePromotion: 999,
                priceSale: 999,
                priceStandard: 8888,
                promotionId: 211,
                promotionItemId: 22944,
                promotionName: "1",
                promotionPriceType: 77,
                promotionType: 1,
                promotionTypeName: "单品促销",
                radio: "0",
                refCostAmt: 9234,
                refCostPrice: 3078,
                skuCode: "EE920A00200B01",
                skuId: 9537580,
                skuModel: "EE920A00200B01",
                skuName: "【已淘汰】智能盖板HE920",
                skuType: 0,
                skuTypeName: "",
                skuVolume: 0.05,
                skuWeight: 0,
                spuCode: "HE920",
                spuId: 65410,
                standardId: 308,
                tItemAmount: 2997,
                tItemQuantity: 3,
                unitName: "PCS",
                whId: 552
                }
                ],
                orderNo: 'SA-QZHJ-BFJ-202401150RYC',
                orderStatus: '订单状态-通过',
                orderType: 2,
                orgId: 32402,
                orgName: '北海富安居店',
                radioAll: 0,
                receiptVOList: [
                    {
                    itemAmount: 0,
                    receiptId: 0,
                    typeId: 465,
                    typeName: "钦州办工行001"
                    },
                    {
                    itemAmount: 0,
                    receiptId: 0,
                    typeId: 466,
                    typeName: "华辰账号-91176"
                    },
                    {
                    itemAmount: 0,
                    receiptId: 0,
                    typeId: 490,
                    typeName: "华辰账号-91175"
                    },
                    {
                    itemAmount: 0,
                    receiptId: 0,
                    typeId: 492,
                    typeName: "钦州办建行002"
                    },
                    {
                    itemAmount: 0,
                    receiptId: 0,
                    typeId: 493,
                    typeName: "北部建材农行001"
                    },
                    {
                    itemAmount: 0,
                    receiptId: 0,
                    typeId: 495,
                    typeName: "富安居代收款"
                    }],
                    receivable: 2997,
                    sale1Id: 20760,
                    sale2Id: 29195,
                    sale2OpeMode: "分销模式-代送",
                    salesChannel: 1,
                    staffId: 1005,
                    staffName: "无库无ERP00001",
                    sumAmount: 2997,
                    sumCollectedAmount: 0,
                    sumFeeAmount: 0,
                    sumGoodsAmount: 2997,
                    sumOutAmount: 2997,
                    sumPromotion: 2997,
                    sumQuantity: 3,
                    sumReceiptAmount: 0,
                    sumRejectAmount: 0,
                    sumStandard: 26664,
                    sumUsePrestore: 0,
                    sumVolume: 0.15,
                    sumWeight: 0,
                    tDiscountPromotion: 100,
                    tDiscountStandard: 11.24,
                    tSumAmount: 2997,
                    tSumGoodsAmount: 2997,
                    tSumPromotion: 2997,
                    tSumQuantity: 3,
                    tSumStandard: 26664,
                    toiletCount: 2,
                    usablePrestore: 8
      }
    ],
    dataListTemp: [
        {
        addressArea: {
        city: "沈阳市",
        district: "和平区",
        province: "辽宁省"
        },
        addressFull: "辽宁省沈阳市和平区汤玉麟公馆旧址11111",
        addressGcj02: {
        latitude: 41.79179,
        longitude: 123.421643
        },
        addressName: "汤玉麟公馆旧址",
        addressNo: "11111",
        ageComposition: 98,
        ascpId: 29195,
        contactName: "",
        deliveryPhone: "",
        contractNo: "2312313333",
        cpId: 20760,
        customerFrom: -1,
        customerId: 3915,
        customerName: "12.21.01",
        customerPhone: "45454454444",
        decisionMaker: 102,
        deliveryTime: "2024-01-16T08:00:00+08:00",
        designStatus: "设计状态-无需",
        discountPromotion: 100,
        discountStandard: 11.24,
        docCode: "销售订单",
        editTime: "2024-01-15T17:00:34.375071+08:00",
        fitupStyle: 91,
        fitupType: 87,
        flgToErp: false,
        houseType: 84,
        linkPsiSystem: "DK-IBOSS",
        makingTime: "2024-01-15T17:00:34.439+08:00",
        makingUser: 1005,
        makingUserPur: 968,
        merOrderType: 0,
        orderId: 11767,
        orderItemVOList: [
        {
        activityId: 84,
        activityName: "零售活动方案",
        canReturnQuantity: 3,
        discountPromotion: 100,
        discountStandard: 11.24,
        erpOutItemId: 1435661,
        erpOutNo: "ZJSA72924011500006",
        flgDesign: false,
        flgGift: false,
        hasChild: 0,
        iconThumPath: "haip/2023-04-21/19ae78a2639547d9aa961b58d20dbdbd.png",
        id: "5d8d66b7-5e2c-4e63-b396-3786cef7d85d",
        itemId: 35537,
        itemIndex: 1,
        nonStandardArea: 1,
        nonStandardCode: "-",
        orderAmount: 2997,
        orderId: 11767,
        orderItemId: 35537,
        orderItemQuantity: 1,
        orderNo: "SA-QZHJ-BFJ-202401150RYC",
        orderPriceSale: 999,
        orderQuantity: 3,
        outId: 3382,
        outItemId: 6164,
        outNo: "WO-QZHJ-000-202401150RYD",
        outOutAmount: 2997,
        outOutQuantity: 3,
        outRejectAmount: 0,
        outRejectQuantity: 0,
        outStatus: 3,
        pathType: 2,
        pricePromotion: 999,
        priceSale: 999,
        priceStandard: 8888,
        promotionId: 211,
        promotionItemId: 22944,
        promotionName: "1",
        promotionPriceType: 77,
        promotionType: 1,
        promotionTypeName: "单品促销",
        radio: "0",
        refCostAmt: 9234,
        refCostPrice: 3078,
        skuCode: "EE920A00200B01",
        skuId: 9537580,
        skuModel: "EE920A00200B01",
        skuName: "【已淘汰】智能盖板HE920",
        skuType: 0,
        skuTypeName: "",
        skuVolume: 0.05,
        skuWeight: 0,
        spuCode: "HE920",
        spuId: 65410,
        standardId: 308,
        tItemAmount: 2997,
        tItemQuantity: 3,
        unitName: "PCS",
        whId: 552
        }
        ],
        orderNo: "SA-QZHJ-BFJ-202401150RYC",
        orderStatus: "订单状态-通过",
        orderType: 2,
        orgId: 32402,
        orgName: "北海富安居店",
        radioAll: "0",
        receiptVOList: [
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 465,
        typeName: "钦州办工行001"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 466,
        typeName: "华辰账号-91176"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 490,
        typeName: "华辰账号-91175"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 492,
        typeName: "钦州办建行002"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 493,
        typeName: "北部建材农行001"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 495,
        typeName: "富安居代收款"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 496,
        typeName: "工商（恒晶公户）"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 497,
        typeName: "其他应付款"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 499,
        typeName: "兴业银行"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 500,
        typeName: "农业银行"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 501,
        typeName: "库存现金"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 503,
        typeName: "过渡账户"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 504,
        typeName: "华夏银行"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 505,
        typeName: "微信"
        },
        {
        itemAmount: 0,
        receiptId: 0,
        typeId: 507,
        typeName: "冲款账户"
        }]}],
        item: {
            addressArea: {
            city: "沈阳市",
            district: "和平区",
            province: "辽宁省"
            },
            addressFull: "辽宁省沈阳市和平区汤玉麟公馆旧址11111",
            addressGcj02: {
            latitude: 41.79179,
            longitude: 123.421643
            },
            addressName: "汤玉麟公馆旧址",
            addressNo: "11111",
            ageComposition: null,
            ageCompositionName: null,
            apvResult: "审-通过",
            apvResultName: "通过",
            apvSubmitId: null,
            apvUserIds: [],
            ascpId: 29195,
            bankAccount: null,
            bankDeposit: null,
            categoryQuantity: 1,
            channelName: null,
            contactName: "",
            deliveryPhone: "",
            contractNo: "2312313333",
            cpId: 20760,
            crmOrderNo: null,
            customerCode: "45454454444-10030R",
            customerFrom: -1,
            customerFromName: null,
            customerId: 3915,
            customerName: "12.21.01",
            customerPhone: "45454454444",
            customerType: null,
            customerTypeName: null,
            decisionMaker: null,
            decisionMakerName: null,
            deliveryTime: "2024-01-16 08:00:00",
            deliveryTypeName: null,
            designRemarks: null,
            designStatus: "设计状态-无需",
            designStatusName: "不需要设计",
            designUser: null,
            designUserName: null,
            discountPromotion: 100,
            discountStandard: 11.24,
            displayStatus: "出库完成",
            docCode: "销售订单",
            earnestAmount: null,
            editTime: "2024-01-15 17:00:34",
            entryStatus: "入库状态-未入",
            entryTime: null,
            erpOrgCode: "",
            erpPushResult: null,
            erpPushStatus: 2,
            estateId: null,
            estateName: null,
            fitupStyle: null,
            fitupStyleName: null,
            fitupType: null,
            fitupTypeName: null,
            flgValid: true,
            houseType: null,
            houseTypeName: null,
            kujialeDesignId: null,
            kujialeNo: null,
            kujialePricePaths: null,
            makingTime: "2024/01/15",
            makingTimeConvert: "2024-01-15 17:00:34",
            makingUser: 1005,
            makingUserName: "无库无ERP00001",
            merOrderType: 0,
            merOrderTypeName: "非跟单",
            orderId: 11767,
            orderItemVOList: null,
            orderNo: "SA-QZHJ-BFJ-202401150RYC",
            orderStatus: "订单状态-通过",
            orderStatusName: "成交",
            orderType: 2,
            orgCode: "GXBH1002",
            orgId: 32402,
            orgList: null,
            orgName: "北海富安居店",
            outStatus: "出库状态-完成",
            outStatusName: "出库完成",
            receiptStatus: "收款状态-未收",
            receiptStatusName: "未收款",
            receivable: 2997,
            rejectStatusString: null,
            remarks: null,
            sale1Id: 20760,
            sale2Id: 29195,
            sale2OpeMode: "分销模式-代送",
            salesChannel: 1,
            salesChannelName: "零售",
            sorderId: null,
            sorderNo: null,
            staffCode: "12222222222@QZHJ",
            staffId: 1005,
            staffList: null,
            staffName: "无库无ERP00001",
            storeCode: "GXBH1002",
            storeId: 4421,
            storeName: "北海富安居店",
            storeType: null,
            storeTypeName: "直营门店",
            sumAmount: 2997,
            sumCollectedAmount: 0,
            sumFeeAmount: 0,
            sumGoodsAmount: 2997,
            sumOutAmount: 2997,
            sumPromotion: 2997,
            sumQuantity: 3,
            sumReceiptAmount: 0,
            sumRejectAmount: 0,
            sumStandard: 26664,
            sumUsePrestore: 0,
            sumVolume: 0.15,
            sumWeight: 0,
            supplierCode: null,
            supplierId: null,
            supplierName: null,
            tdiscountPromotion: 100,
            tdiscountStandard: 11.24,
            toiletCount: null,
            toiletCountName: null,
            tsumAmount: 2997,
            tsumGoodsAmount: 2997,
            tsumPromotion: 2997,
            tsumQuantity: 3,
            tsumStandard: 26664
            },
    loading: false,
    orderAmountSum: 0,
    radioAll: false,
  
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {

   
  },


  doSearch() {


    if (this.data.searchText && this.data.searchText != '') {
      let dataList =  util.copyObj(this.data.dataList)

      if (dataList && dataList.length > 0) {

        if (dataList[0].orderItemVOList && dataList[0].orderItemVOList.length > 0) {
          dataList[0].orderItemVOList = dataList[0].orderItemVOList.filter((item) => {
            return (item.skuCode.indexOf(this.data.searchText) != -1) || (item.skuName.indexOf(this.data.searchText) != -1)
          })
        }
        this.setData({
          dataList: dataList

        })

      }
    } else {
      this.setData({
        dataList: util.copyObj(this.data.dataListTemp)

      })
    }

  },
  /**
   * @desc : 得到订单出库数据 
   * @author : 王英杰
   * @date : 2022/5/23 15:16
   */
  getData(e) {
    this.setData({
      loading: true
    })

    //参数
    let param = {
     
      searchText: this.data.searchText ? this.data.searchText : ''
    }
    if(this.data.item){
      param.orderId = this.data.item.orderId ? this.data.item.orderId : null
    }

    param.cpId = app.globalData.user.cpId
    let toSaleReturnFalg = false
    if(this.data.orderId && this.data.orderId != undefined && this.data.orderId != 'undefined'){
      //销售退货通知跳转
      param.orderId = this.data.orderId
      param.cpId = this.data.cpId
      toSaleReturnFalg = true
    }
    api.request(Constants.COMMON_METHOD + 'get_order_for_return', 'POST', param).then(res => {
      this.setData({
        loading: false
      })

      if (res.data.code === 200) {
        let dataList = this.data.dataList
        dataList = res.data.data.list
        if(toSaleReturnFalg){
          if(dataList && dataList.length > 0){
            let itemObj = this.data.item
            itemObj.customerName = dataList[0].customerName
            itemObj.customerPhone = dataList[0].customerPhone
            itemObj.addressFull = dataList[0].addressFull
            this.setData({
              item:itemObj
            })
          }
        }
        
        //为 radio 选择 添加属性
        dataList.forEach(item => {
          item.radioAll = "0"
          if (item.orderItemVOList && item.orderItemVOList.length > 0) {
            item.orderItemVOList.forEach(element => {
              element.radio = "0"
            });
          }
          if (item.orderItemVOList && item.orderItemVOList.length > 0) {
            item.orderItemVOList = this.setOrderItem(item.orderItemVOList)
          }

        });


        this.setData({
          dataList,
          dataListTemp: dataList
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },
  /**
   * 最底下 总的全退款
   */
  onChangeALL(e) {
    let dataList = this.data.dataList
    let radioAll = this.data.radioAll
    let orderAmountSum = 0
    radioAll = this.data.radioAll == "1" ? "0" : "1"
    dataList.forEach(item => {
      item.radioAll = radioAll
      item.orderItemVOList.forEach(element => {
        element.radio = radioAll

        if (radioAll == "1") {
          if(element.nonStandardArea){
            let num  =  util.AddNumber(util.accMul(element.canReturnQuantity, element.orderPriceSale), orderAmountSum) 
            //退货总额 = (出库数量 - 退货数量)*单价*面积
            orderAmountSum = Number(num * element.nonStandardArea)
          }else{
            let num  =  util.AddNumber(util.accMul(element.canReturnQuantity, element.orderPriceSale), orderAmountSum) 
          //退货总额 = (出库数量 - 退货数量)*单价
          orderAmountSum = num
          }
          
        }
      });
    });
    this.setData({
      radioAll: radioAll,
      dataList,
      orderAmountSum
    });

  },
  /**
   *  每个出库单 总的全退款
   */
  onChangeItmeALL(e) {
    let dataList = this.data.dataList
    let index = e.currentTarget.dataset.index
    let dataListnum = 0
    let radioAll = this.data.radioAll

    dataList[index].radioAll = dataList[index].radioAll == "1" ? "0" : "1" // 把总单 勾选
    if (dataList[index].orderItemVOList) {
      dataList[index].orderItemVOList.forEach(element => { // 总单的明细勾选
        element.radio = dataList[index].radioAll
      });
    }

    let orderAmountSum = 0
    // 当 每个出库单  总的 都勾选上 或者勾选掉  把底部选好了旁边的勾选带上
    dataList.forEach(item => {
      if (item.radioAll == "1") {
        dataListnum++
      }
      if (item.orderItemVOList) {
        item.orderItemVOList.forEach(element => {
          if (element.radio == "1") {

            if(element.nonStandardArea){
              let num  = util.AddNumber(util.accMul(element.canReturnQuantity, element.orderPriceSale), orderAmountSum)
              //退货总额 = (出库数量 - 退货数量)*单价*面积
              orderAmountSum = Number(num * element.nonStandardArea)
            }else{
              let num  = util.AddNumber(util.accMul(element.canReturnQuantity, element.orderPriceSale), orderAmountSum)
              //退货总额 = (出库数量 - 退货数量)*单价
              orderAmountSum =num
            }


          }
        });
      }

    });

    if (dataListnum == dataList.length) {
      radioAll = "1"
    }
    if (dataListnum == 0) {
      radioAll = "0"
    }
    this.setData({
      dataList,
      radioAll,
      orderAmountSum
    });
  },
  /**
   * 单个退款选择
   * @param {*} event 
   */
  onChangeRadio(e) {

    let dataList = this.data.dataList
    let index = e.currentTarget.dataset.index
    let index_ = e.currentTarget.dataset.indexzhangdl
    let dataListnum = 0
    let orderOutItemListnum = 0
    let radioAll = this.data.radioAll
    let orderAmountSum = 0
    dataList[index].orderItemVOList[index_].radio = dataList[index].orderItemVOList[index_].radio == "1" ? "0" : "1"
    // 当 出库单 子radio 都被选择 自动把上面的 总的 勾选上 或者勾选掉  
    dataList[index].orderItemVOList.forEach(element => {
      if (element.radio == "1") {
        orderOutItemListnum++
      }
    });
    if (orderOutItemListnum == dataList[index].orderItemVOList.length) {
      dataList[index].radioAll = "1"
    }
    if (orderOutItemListnum == 0) {
      dataList[index].radioAll = "0"
    }

    // 当 每个出库单  总的 都勾选上 或者勾选掉  把底部选好了旁边的勾选带上
    dataList.forEach(item => {
      if (item.radioAll == "1") {
        dataListnum++
      }
      item.orderItemVOList.forEach(element => {
        if (element.radio == "1") {
          //退货总额 = (出库数量 - 退货数量)*单价
        //  orderAmountSum = util.AddNumber(util.accMul(element.canReturnQuantity, element.orderPriceSale), orderAmountSum)


          if(element.nonStandardArea){
            let num  = util.AddNumber(util.accMul(element.canReturnQuantity, element.orderPriceSale), orderAmountSum)
            //退货总额 = (出库数量 - 退货数量)*单价*面积
            orderAmountSum = Number(num * element.nonStandardArea)
          }else{
            let num  = util.AddNumber(util.accMul(element.canReturnQuantity, element.orderPriceSale), orderAmountSum)
            //退货总额 = (出库数量 - 退货数量)*单价
            orderAmountSum =num
          }

        }
      });
    });
    if (dataListnum == dataList.length) {
      radioAll = "1"
    }
    if (dataListnum == 0) {
      radioAll = "0"
    }
    this.setData({
      dataList,
      radioAll,
      orderAmountSum
    });
  },
  /**
   * @desc : 跳转销售退货
   * @author : 王英杰
   * @date : 2022/5/27 12:16
   */
  toSaleReturn(e) {
      wx.navigateTo({
      url: '../sales-return-confirm/sales-return-confirm' ,
    })
  },


  /**
   * @desc : 计算退换总额
   * @author : 于继渤
   * @date : 2022/7/18 10:16
   */
  getOrderAmountSum(e) {
    let dataList = this.data.dataList
    let index = e.currentTarget.dataset.index
    let orderItemVOList = dataList[index].orderItemVOList
    // if (orderItemVOList && orderItemVOList.length > 0) {
    //   orderItemVOList.forEach(res => {

    //   })
    // }
    // orderAmountSum = (Number(element.orderQuantity) + Number(element.outRejectQuantity) * Number(element.orderPriceSale)) + Number(orderAmountSum)  //退货总额 = (出库数量 - 退货数量)*单价
  },
  /**
       * @desc : 给明细数据赋值
       * @date : 2022/6/30 16:49
       * @author : 周兴
       */
  setOrderItem(orderItemList) {
    let goodsList = []
    orderItemList.forEach(item => {
      item.goodsSkuList = item.bomItems
      goodsList.push(item);
    })
    // 处理图标
    common.setSkuIcon(goodsList);
    return goodsList
  },


})