const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 路由
    routeObjName: 'order',
    customerService: app.globalData['customerService'],
    cardList: [
      { name: 'main', title: mixins.$t("customerInformation") },
      { name: 'items', title: mixins.$t("goodsDetail"), chooseGoodsFlag: true, itemAmt: '', displayNum: 2 },
      { name: 'other', title: mixins.$t("otherInfo") }
    ],
    contentObj: {
      main: [
        { code: 'cusName', type: 'selectIcon', urlKey: 'selectCustomers', required: true, readonly: false, title: mixins.$t('customerName') },
        { code: 'cusPhone', type: 'phone', title: mixins.$t('cusPhone'), required: true },
        { code: 'addressFull', type: 'address', title: mixins.$t('addressFull'), required: true },
        { code: 'addressNo', type: 'str', required: true, title: mixins.$t('addressNo') },
        { code: 'channelId', name: 'channelName', required: true, title: mixins.$t('saleChannel'), type: 'choose', urlKey: 'chooseChannel' },

        { code: 'cusFrom', name: 'cusFromName', required: true, title: mixins.$t('customerSource'), type: 'choose', urlKey: 'choosecusFrom' },

      ],
      items: [
        { code: 'collectType', name: 'collectName', type: 'drop', required: true, dropType: 'collect' },
        { code: 'collectAmount', type: 'number', title: mixins.$t("amountCollected"), required: true }
      ],
      other: [
        { code: 'contractNo', type: 'textarea', title: mixins.$t("contractNumber"), readonly: false },
        { code: 'deliveryDate', type: 'date', required: false, title: mixins.$t("delivery_Time"), required: false },
        { code: 'remarks', type: 'textarea', title: mixins.$t("remarks"), readonly: false },
        { code: 'file', type: 'uploader', title: mixins.$t("uploader") }
      ]
    },
    //按钮
    buttonSaveList: [
      { code: 'collection', title: mixins.$t("collection"), width: '120rpx', color: '#CAA977' },
      { code: 'save', title: mixins.$t("save"), width: '120rpx', color: '#1B365D' }
    ],
    contentSaveList: [
      { code: 'flag', title: mixins.$t("saleOutBoundFlag"), type: 'checkbox' },
      { code: 'need', title: mixins.$t("saleCollection"), type: 'str' },
      { code: 'receivable', content: 0, type: 'number' }
    ],
    popContent: [
      { code: 'itemQty', type: 'step', title: mixins.$t("count"), required: true },
      { code: 'priceSale', type: 'number', title: mixins.$t("priceSale"), required: true },
      {
        code: 'whId', name: 'whName', title: mixins.$t("warehouseId"), type: 'choose', urlKey: 'openingInventory',
      },
      { code: 'nonStdCode', title: mixins.$t("goodsBatch"), type: 'str', },
      { code: 'flgGift', title: mixins.$t("flgGift"), type: 'checkbox', },
    ],
    table: Constants.tables.order,
  },
 

  /**
    * @desc   : 手机号离焦事件
    * @author : 于继渤
    * @date   : 2024/1/26 11:46
    */
  changePhoneblur(e) {
    let formData = JSON.parse(this.data.formData)
    console.log('cusPhone', formData.cusPhone)
    if (formData.cusPhone) {
      this.getCustomerData({ cusPhone: formData.cusPhone })
    }

  },
  /**
     * @desc : 查询客户信息
     * @author : 于继渤
     * @date : 2024/1/23 9:16
     */
  getCustomerData(params) {
    return this.excute(this.data.customerService, this.data.customerService.selectByCondNoPage, params).then(res => {
      if (res.data.code == 200) {
        if (res.data.data.length > 0) {
          console.log('res', res)
          let formData = JSON.parse(this.data.formData)
          let item = res.data.data[0]
          formData.cusCode = item.cusCode
          formData.cusId = item.cusId
          formData.cusName = item.cusName
          // formData.cusPhone = item.cusPhone
          formData.cusFromName = item.cusFromName
          formData.cusFrom = item.cusFrom
          //处理地址
          formData.address = {
            address: item.addressFull,
            addressFull: item.addressFull,
            addressArea: item.addressArea,
            addressGcj02: item.addressGcj02,
            addressName: item.addressName,
          }
          formData.addressArea = item.addressArea
          formData.addressFull = item.addressFull
          formData.addressGcj02 = item.addressGcj02
          formData.addressName = item.addressName
          formData.addressNo = item.addressNo
          //订单销售渠道 ,默认取的部门的渠道
          // formData.salesChannel = item.channelId
          // formData.channelId = item.channelId
          // formData.channelName = item.channelName
          formData.contactPhone = item.contactPhone
          formData.contactPhone = item.contactPhone

          this.setData({
            formData: JSON.stringify(formData)
          })
        }
      }
    });
  },
  /**
   * @desc   : 选择回调
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  chooseData(e) {
    console.log('eee1', e);
    let item = e.detail.data
    let code = e.detail.code
    let formData = JSON.parse(this.data.formData)
    //设置客户信息
    if (code == 'cusName') {
      formData.cusCode = item.cusCode
      formData.cusId = item.cusId
      formData.cusName = item.cusName
      formData.cusPhone = item.cusPhone
      formData.cusFromName = item.cusFromName
      formData.cusFrom = item.cusFrom
      //处理地址
      formData.address = {
        address: item.addressFull,
        addressFull: item.addressFull,
        addressArea: item.addressArea,
        addressGcj02: item.addressGcj02,
        addressName: item.addressName,
      }
      formData.addressArea = item.addressArea
      formData.addressFull = item.addressFull
      formData.addressGcj02 = item.addressGcj02
      formData.addressName = item.addressName
      formData.addressNo = item.addressNo
      //订单销售渠道 ,默认取的部门的渠道
      // formData.salesChannel = item.channelId
      // formData.channelId = item.channelId
      // formData.channelName = item.channelName
      formData.contactPhone = item.contactPhone
      formData.contactPhone = item.contactPhone
    }
    ///设置主从业务员
    if (code == 'staff') {
      formData.staff = item.staffItem
      formData['staffId'] = item.staffMain.staffId
      formData['staffName'] = item.staffMain.staffName
      formData['staffList'] = item.staffList
      console.log(item.staffList)
    }
    ///设置主从业务部门
    if (code == 'org') {
      console.log('item', item)
      formData.org = item.orgItem
      formData['orgId'] = item.orgMain.orgId
      formData['orgName'] = item.orgMain.orgName
      formData['orgList'] = item.orgList
    }
    //销售渠道
    if (code == 'channelId') {
      formData.channelId = item.data.id
      formData.channelCode = item.data.code
      formData.channelName = item.data.name
    }
    //客户来源
    if (code == 'cusFrom') {
      formData.cusFromId = item.data.id
      formData.cusFromCode = item.data.code
      formData.cusFromName = item.data.name
    }
    this.setData({
      formData: JSON.stringify(formData)
    })

  },

  /**
    * @desc : 底部按钮事件
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  saveButton(e) {

    let name = e.detail.name
    if (name == 'save') { //保存
      this.save({})
    } else if (name == 'collection') { //收款
      //跳转收款页
      let formData = JSON.parse(this.data.formData)
      console.log('formData', formData)
      //保存接口并没有计算,因此前台计算
      let list = this.setItemList(formData.goodsList)
      formData.itemList = list //明细
      formData.orderStatus = Constants.orderStatus.STATUS_DEAL //订单状态
      formData.outStatus = Constants.outStatus.unOutBound //出库状态
      formData.makeStaff = app.globalData.user.staffId //制单人
      formData.amtResidue = formData.amtReceivable //剩余应收 = 应收金额 
      formData.deleteItemList = formData.deleteList ? formData.deleteList : []
      formData.salesChannel = formData.channelId
      delete formData['goodsList']
      formData.objInfo = {}
      formData.objInfo['cusPhone'] = formData.cusPhone
      formData.objInfo['cusName'] = formData.cusName
      formData.objInfo['objectId'] = formData.cusId
      formData.objInfo['addressFull'] = formData.addressFull


      let _this = this
      wx.navigateTo({
        url: this.data.route.selectCollectionConfirm.url,
        events: {
          // 回调后
          bindData: function (data) {
            // 保存成功后 回调
            wx.navigateBack({
              data: 2
            })
          }
        },
        success: function (res) {
          //设置参数
          //let item = _this.setSaveData()
          res.eventChannel.emit('params', { item: JSON.stringify(formData), formType: 8 })
        }
      })
    }
  },

  /**
    * @desc : 设置保存参数
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  setParams(params) {
    //保存接口并没有计算,因此前台计算
    let list = this.setItemList(params.goodsList)
    params.itemList = list //明细
    params.orderStatus = Constants.orderStatus.STATUS_DEAL //订单状态
    params.outStatus = Constants.outStatus.unOutBound //出库状态
    params.makeStaff = app.globalData.user.staffId //制单人
    params.amtResidue = params.amtReceivable //剩余应收 = 应收金额 
    params.deleteItemList = params.deleteList ? params.deleteList : []
    params.salesChannel = params.channelId
    delete params['goodsList']
    return params
  },
  /**
    * @desc : 明细,保存接口并没有计算,因此前台计算
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  setItemList(list) {
    for (let i = 0; i < list.length; i++) {
      list[i].itemIndex = i + 1 //序号
    }
    return list
  },
  /**
   * @desc : 设置商品
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setGoods(e) {
    //设置需收款
    let contentSaveList = this.data.contentSaveList
    let formData = JSON.parse(this.data.formData)
    //需收款 = 合计金额 - 使用预存
    let amtReceivable = Number(formData.sumAmount - formData.useCollect)
    //组件显示 需收款
    contentSaveList[2]['content'] = amtReceivable
    //设置应收金额
    formData['amtReceivable'] = amtReceivable
    this.setData({
      formData: JSON.stringify(formData),
      contentSaveList: contentSaveList
    })
  },

  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveData() {
    if (this.data.formMode == Constants.formMode.edit) { //编辑
      return this.excute(this.data.service, this.data.service.update, this.data.params);
    } else { //新建
      return this.excute(this.data.service, this.data.service.insert, this.data.params);
    }
  },



  /**
     * @desc : 给表单赋值
     * @date : 2024/2/1 15:49
     * @author : 于继渤
     */
  setValuesByEdit(data) {
    let cardList = this.data.cardList
    //处理地址
    data.address = {
      address: data.addressFull,
      addressFull: data.addressFull,
      addressArea: data.addressArea,
      addressGcj02: data.addressGcj02,
      addressName: data.addressName,
    }
    cardList[1].sumAmount = data.sumAmount
    cardList[1].sumStandard = data.sumStandard
    cardList[1].sumQuantity = data.sumQuantity
    cardList[1].saleDiscount = data.saleDiscount
    this.setData({
      cardList: cardList,
      formData: JSON.stringify(data)
    })
    //查询商品明细
    this.getItemDetal(data.orderId)


  },
  /**
     * @desc : 查询商品明细
     * @date : 2024/2/1 15:49
     * @author : 于继渤
     */
  getItemDetal(orderId) {
    return this.excute(this.data.service, this.data.service.selectOrderInfoById + '/' + orderId, {}).then(res => {
      if (res.data.code == 200) {
        let formData = JSON.parse(this.data.formData)
        formData.goodsList = res.data.data.orderItem
        this.setData({
          formData: JSON.stringify(formData)
        })
      }
    });
  },

  /**
    * @desc   : 设置顶部默认值
    * @author : 于继渤
    * @date   : 2024/1/26 11:46
    */
  setTopStaffAndOrg(formData) {
    formData['staff'] = {
      text: app.globalData.user.staffName,
      value: [app.globalData.user.staffId]
    }
    formData['org'] = {
      text: app.globalData.user.orgName,
      value: [app.globalData.user.orgId]
    }
    formData.orgId = app.globalData.user.orgId
    formData.orgList = [
      {
        orgId: app.globalData.user.orgId,
        orgName: app.globalData.user.orgName,
        ownerFlag: true,
        allocationRatio: 100,
      }
    ]
    formData.staffId = app.globalData.user.staffId
    formData.staffList = [
      {
        staffId: app.globalData.user.staffId,
        staffName: app.globalData.user.staffName,
        ownerFlag: true,
        allocationRatio: 100
      }
    ]
    this.setData({
      formData: JSON.stringify(formData)
    })
  },




  /**
    * @desc   : 计算金额
    * @author : 于继渤
    * @date   : 2024/1/26 11:46
    */
  calculateAmount(formData) {
    let cardList = this.data.cardList
    ///设置总单信息
    console.log('formData1', formData)
    let sumStandard = Number(0)
    let sumAmount = Number(0)
    let sumQuantity = Number(0)
    formData.goodsList.forEach(item => {
      //标价合计 =  商品标价 x  商品数量
      item.priceStd = item.priceStd ? item.priceStd : item.priceStandard//标价
      item.amtStd = Number(item.priceStd * item.itemQty) //合计标价金额
      item.itemAmt = item.priceSale * item.itemQty
      item.priceDiscount = Number((item.priceSale / item.priceStandard) * 100).toFixed(2)//售价折扣
      sumStandard += item.priceStandard * item.itemQty
      sumAmount += item.itemAmt
      sumQuantity += item.itemQty //数量

    })
    formData.sumStandard = sumStandard
    formData.saleDiscount = Number((sumAmount / sumStandard) * 100).toFixed(2)
    formData.sumAmount = sumAmount
    formData.canUseCollect = 0
    formData.useCollect = 0
    formData.sumQuantity = sumQuantity

    cardList[1].sumAmount = formData.sumAmount
    cardList[1].sumStandard = formData.sumStandard
    cardList[1].sumQuantity = formData.sumQuantity
    cardList[1].saleDiscount = formData.saleDiscount
    console.log('formData2', formData)
    this.setData({
      cardList: cardList,
      formData: JSON.stringify(formData)
    })

  },


  /**
   * 生命周期函数--监听页面加载
   */
  loadInit() {
    console.log('app.globalData.user', app.globalData.user)
    let formData = JSON.parse(this.data.formData)
    if (this.data.formMode == Constants.formMode.edit) {
      wx.setNavigationBarTitle({
        title: '编辑订单'
      })
      this.setData({
        buttonSaveList: [
          { code: 'save', title: mixins.$t("save"), width: '120rpx', color: '#1B365D' }
        ]
      })


    } else {
      //设置默认业务员业务部门
      this.setTopStaffAndOrg(formData)
    }
    let that = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('params', function (data) {
      console.log(data)
      if (data && data.goodsList && data.goodsList.length > 0) {
        formData.goodsList = data.goodsList
        that.calculateAmount(formData)
      }
      //客户接待过来的
      if (data && data.item && data.item.length > 0) {
        if (data.formItem) {
          let formItem = JSON.parse(data.formItem)
          formData.cusCode = formItem.cusCode
          formData.cusId = formItem.cusId
          formData.cusName = formItem.cusName
          formData.cusPhone = formItem.cusPhone
          formData.cusFromName = formItem.cusFromName
          formData.cusFrom = formItem.cusFrom
          //处理地址
          formData.address = {
            address: formItem.addressFull,
            addressFull: formItem.addressFull,
            addressArea: formItem.addressArea,
            addressGcj02: formItem.addressGcj02,
            addressName: formItem.addressName,
          }
          formData.addressArea = formItem.addressArea
          formData.addressFull = formItem.addressFull
          formData.addressGcj02 = formItem.addressGcj02
          formData.addressName = formItem.addressName
          formData.addressNo = formItem.addressNo
          formData.contactPhone = formItem.contactPhone
          formData.contactPhone = formItem.contactPhone
        }
        formData.goodsList = data.item
        that.setGoodsAmount(formData)
        that.calculateAmount(formData)
      }
    })
  },
  setGoodsAmount(formData) {
    let cardList = this.data.cardList

    let index = cardList.findIndex(it => it.name == 'items');
    if (formData.goodsList && formData.goodsList.length > 0) {
      let sumStandard = Number(0)
      let sumAmount = Number(0)
      let sumQuantity = Number(0)
      formData.goodsList.forEach(item => {
        //标价合计 =  商品标价 x  商品数量
        item.priceStd = item.priceStd ? item.priceStd : (item.priceStandard ? item.priceStandard : 0)//标价
        item.amtStd = Number(item.priceStd * item.itemQty) //合计标价金额
        item.priceSale = item.priceSale ? item.priceSale : item.priceStandard
        item.itemAmt = item.priceSale * item.itemQty //商品金额
        item.priceDiscount = item.priceStd ? Number((item.priceSale / item.priceStd) * 100).toFixed(2) : 100//售价折扣
        sumQuantity += item.itemQty //数量
        sumAmount += item.priceSale * item.itemQty //没有售价默认取标价
        console.log('111', item.priceStandard)
        console.log('111', item.priceStd)
        sumStandard += (item.priceStd ? item.priceStd : item.priceStandard) * item.itemQty
      })
      //标价合计
      cardList[index].sumStandard = sumStandard
      //销售折扣 (合计金额/标价合计)
      cardList[index].saleDiscount = sumStandard ? Number((sumAmount / sumStandard) * 100).toFixed(2) : 100
      //合计金额
      cardList[index].sumAmount = sumAmount
      //TODO   需要获取当前客户可用预存
      cardList[index].canUseCollect = 0  //可用
      cardList[index].useCollect = 0  //使用
      formData.sumStandard = sumStandard
      formData.saleDiscount = cardList[index].saleDiscount
      formData.sumAmount = sumAmount
      formData.canUseCollect = 0
      formData.useCollect = 0
      formData.sumQuantity = sumQuantity
    } else {
      cardList[index].sumStandard = 0
      cardList[index].saleDiscount = 0
      cardList[index].sumAmount = 0
      cardList[index].canUseCollect = 0
      cardList[index].useCollect = 0

      formData.sumStandard = 0
      formData.saleDiscount = 0
      formData.sumAmount = 0
      formData.canUseCollect = 0
      formData.useCollect = 0
    }

    this.setData({
      cardList: cardList,
      formData: JSON.stringify(formData)
    })
  },
})