const Constants = require('@/utils/Constants.js');
import Dialog from '@/dist/dialog/dialog.js';
const mixins = require('@/mixins/index.js')
const utils = require('@/utils/util')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 路由
    routeObjName: 'outbound',
    table: Constants.tables.order,
    orderService: app.globalData['orderService'],
    saleOutBoundService: app.globalData['saleOutBoundService'],
    commonService: app.globalData['commonService'],
    btnFormData: JSON.stringify({ flag: true }),
    cardList: [
      { name: 'main', title: mixins.$t("customerInformation") },
      { name: 'relation' },
      { name: 'items', title: mixins.$t("goodsDetail"), chooseGoodsFlag: true, itemAmt: '', displayNum: 2 },
      { name: 'other', title: mixins.$t("otherInfo") },

    ],
    cardContentList: [
      { code: 'whId', name: 'whName', title: mixins.$t("warehouseId"), type: 'choose', urlKey: 'openingInventory' }
    ],
    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', type: 'drop', required: true, dropType: 'saleChannel', title: mixins.$t('saleChannel') },
        { code: 'cusFrom', name: 'cusFromName', type: 'drop', required: false, dropType: 'customerFrom', title: mixins.$t('customerSource') },
      ],
      relation: [{
        code: 'fromNo',
        name: 'fromNo',
        type: 'choose',
        controlChooseFlag: true,
        title: mixins.$t("sourceOrder"),//'关联源单'
        urlKey: 'selectSourceSaleOrder'
      }],
      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: true },
        { 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: 'outQty', type: 'step', title: mixins.$t("count"), required: true },
      { code: 'priceOut', type: 'number', title: mixins.$t("priceSale"), required: true, readonly: false },
      {
        code: 'whId', name: 'whName', choosePopupType: 'inventorySku', title: mixins.$t("warehouseId"), type: 'choose', urlKey: 'selectInventorySku',
      },
      { code: 'nonStdCode', title: mixins.$t("goodsBatch"), type: 'str', },
    ],
    popupTopObj: [{ leftTitle: '库存量', leftCode: 'usableQty', rightTitle: '可售量', rightCode: 'invQty' }],
    titpsFlag: true
  },
  /**
     * @desc :   编辑
     * @date : 2024/2/1 15:49
     * @author : 于继渤
     */
  toEdit() {
    let this_ = this
    wx.navigateTo({
      url: this_.data.route.add.url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) {
        }
      },
      success: function (res) {
        res.eventChannel.emit('params', {
          formMode: 'detailEdit', id: this_.data.id
        });
      }
    })
  },

  /**
     * @desc :   自动办理事件
     * @date : 2024/2/1 15:49
     * @author : 于继渤
     */
  saveChange(e) {
    let btnFormData = JSON.parse(this.data.btnFormData)
    let that = this
    if (!btnFormData.flag) {
      //提示
      Dialog.confirm({
        message: mixins.$t("saleOutBoundInfo"),
      }).then(() => { }).catch(() => {
        btnFormData.flag = true
        that.setData({
          titpsFlag: true,
          btnFormData: JSON.stringify(btnFormData)
        })
      });
    }

    this.setData({
      titpsFlag: JSON.parse(this.data.btnFormData).flag,
      popupTopObj: JSON.parse(this.data.btnFormData).flag ? [{ leftTitle: '库存量', leftCode: 'usableQty', rightTitle: '可售量', rightCode: 'invQty' }] : [],
    })

  },




  /**
    * @desc : 底部按钮事件
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  saveButton(e) {
    console.log(e)
    let name = e.detail.name
    if (name == 'save') { //保存
      //校验库存
      let btnFormData = JSON.parse(this.data.btnFormData)
      let titpsFlag = this.data.titpsFlag
      if (!btnFormData.flag) {




      }
      this.save({})
    } else if (name == 'collection') { //收款

    }
  },

  /**
    * @desc : 设置保存参数
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  setParams(params) {
    //设置转出库参数
    if (this.data.formMode == 'other') {

    }
    params.fromId = params.orderId
    params.outingAmt = params.outAmt
    params.outingQty = params.outQty
    params.outAmt = null
    params.outQty = null
    params.goodsList.forEach(res => {
      res.outingAmt = res.outAmt
      res.outingQty = res.outQty
      res.outAmt = null
      res.outQty = null
    })

    params.itemList = params.goodsList //明细
    params.makeStaff = app.globalData.user.staffId
    // params.deleteItemList = params.deleteList ? params.deleteList : []
    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出库标识 
    params.addressName = params.address.addressName
    params.outDate = utils.formatDayTime(new Date())
    delete params['goodsList']
    delete params['orderItemResponseList']
    console.log('params', params)
    // return
    return params
  },
  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  saveData() {
    if (this.data.formMode == Constants.formMode.detailEdit) { //编辑
      //limitEdit 编辑标识 true 大
      this.data.params.limitEdit = true
      return this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.outboundUpdate, this.data.params);
    } else if (this.data.formMode == Constants.formMode.add || this.data.formMode == Constants.formMode.other) { //新建
      return this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.outboundInsert, this.data.params);
    } else if (this.data.formMode == Constants.formMode.detail) { //办理
      return this.excute(this.data.saleOutBoundService, this.data.saleOutBoundService.handleOutbound, this.data.params);
    }
  },

  /**
    * @desc : 查询商品明细
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  getItemDetal(id, Service, API) {  //get_outbound_for_update
    if (!Service) {
      Service = 'orderService'
      API = 'getOrderForOut'
    }
    return this.excute(this.data[Service], this.data[Service][API] + '/' + id, {}).then(res => {
      if (res.data.code == 200) {
        let formData = JSON.parse(this.data.formData)
        formData = res.data.data.data
        //销售订单列表转出库
        formData.fromNo = formData.orderNo
        //处理地址
        formData.address = this.setAddress(formData)
        //处理明细
        if (res.data.data.dataItem && res.data.data.dataItem.length > 0) {
          let list = []
          res.data.data.dataItem.forEach(item => {
            item.outQty = item.orderQty ? item.orderQty : item.outingQty //出库数量
            item.outQtyMax = item.canOutingQty //可出库最大值
            item.outQtyMin = 1  //可出库最小值
            list.push({
              skuId: item.skuId,
              nonStdCode: item.nonStdCode,
              whId: item.whId
            })
          })

          //批量查库存
          this.getInventory({ skuIdNonStdCodeWhIdList: list }).then(item => {
            res.data.data.dataItem.forEach(res => {
              if (item.length > 0) {
                item.forEach(it => {
                  if (it.nonStdCode == res.nonStdCode && it.skuId == res.skuId && it.whId == res.whId) {
                    res.invId = it.invId
                    res.invQty = it.invQty ? it.invQty : 0
                    res.usableQty = it.usableQty ? it.usableQty : 0
                  } else {
                    res.invQty = 0
                    res.usableQty = 0
                  }
                })
              } else {
                res.invQty = 0
                res.usableQty = 0
              }

            })
            this.setData({
              formData: JSON.stringify(formData)
            })
            //处理库存量
            this.calculationSalesUsableQty()
          })


        }
        formData.goodsList = res.data.data.dataItem
        //处理默认值  业务员业务部门
        formData = this.setStaffOrg(formData)
        //设置选商品不可用
        let cardList = this.data.cardList
        cardList[2].chooseGoodsFlag = false
        this.calculateAmount(formData)
        this.setData({
          cardList: cardList,
          formData: JSON.stringify(formData)
        })

      }
    });
  },
  /**
     * @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)
    })
    if (this.data.formMode == 'edit') { //编辑  办理页
      //处理商品
      this.calculateAmount(data)
    } else {
      //查询商品明细
      this.getItemDetal(data.orderId)
    }
  },





  /**
   * @desc : 设置商品
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  setGoods(e) {
    //设置需收款
    let contentSaveList = this.data.contentSaveList
    let formData = JSON.parse(this.data.formData)
    let itemIndex = 0
    let list = []
    formData.goodsList.forEach(res => {
      res.itemIndex = itemIndex++
      list.push({
        skuId: res.skuId,
        nonStdCode: res.nonStdCode,
        whId: res.whId
      })
    })
    //批量查库存
    this.getInventory({ skuIdNonStdCodeWhIdList: list }).then(item => {
      formData.goodsList.forEach(res => {
        if (item.length > 0) {
          item.forEach(it => {
            if (it.nonStdCode == res.nonStdCode && it.skuId == res.skuId && it.whId == res.whId) {
              res.invId = it.invId
              res.invQty = it.invQty ? it.invQty : 0
              res.usableQty = it.usableQty ? it.usableQty : 0
            } else {
              res.invQty = 0
              res.usableQty = 0
            }
          })
        } else {
          res.invQty = 0
          res.usableQty = 0
        }

      })
      //组件显示 需收款
      contentSaveList[2]['content'] = Number(formData.sumAmount)
      this.setData({
        formData: JSON.stringify(formData),
        contentSaveList: contentSaveList
      })
      //处理库存量
      this.calculationSalesUsableQty()
    })
  },


  /**
    * @desc : 查询库存
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  getInventory(params) {
    return new Promise((resolve, reject) => {
      this.excute(this.data.commonService, this.data.commonService.getInventoryByList, params).then(res => {
        if (res.data.code == 200) {
          console.log(res.data.data)
          resolve(res.data.data)

        }
      })
    })

  },

  editItems() {
    //处理库存量
    this.calculationSalesUsableQty()
  },

  //计算可售量相关
  calculationSalesUsableQty() {
    let formData = JSON.parse(this.data.formData)
    formData.goodsList.forEach(res => {
      if (res.invId) {
        //选择的数量大于可售量
        if (Math.abs(res.outQty) > res.usableQty) {
          res['usableQtyInsufficientFlag'] = true  //可售量不足
          res['usableQty'] = res.usableQty  //可售量
          res['titpsItemColorFlagKey'] = true
          res['titpsLabel'] = '缺货'
        } else {
          res['usableQtyInsufficientFlag'] = false  //可售量不足
          res['usableQty'] = res.usableQty  //可售量
          res['titpsItemColorFlagKey'] = false
          res['titpsLabel'] = '有货'
        }
      } else {
        // res['usableQtyInsufficientFlag'] = true  //可售量不足
        // res['usableQty'] = res.usableQty  //可售量
        res['titpsItemColorFlagKey'] = true
        res['titpsLabel'] = '缺货'
      }

    })
    let usableQtyInsufficientFlagList = formData.goodsList.filter(item => {
      return item.usableQtyInsufficientFlag
    })
    this.setData({
      formData: JSON.stringify(formData),
      goodsTagColor: usableQtyInsufficientFlagList.length > 0 ? '#E4002B' : null  //设置颜色
    })
  },








  /**
   * @desc   : 选择回调
   * @author : 于继渤
   * @date   : 2024/1/26 11:46
   */
  chooseData(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.objectId = item.cusId
      formData.cusName = item.cusName
      formData.cusPhone = item.cusPhone
      formData.cusFromName = item.cusFromName
      formData.cusFrom = item.cusFrom
      //处理地址
      formData.address = this.setAddress(item)
      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 == 'fromNo') {
      if (item.itemList && item.itemList.length > 0) {
        formData.goodsList = item.itemList
        formData.fromNo = item.fromNo
        this.calculateAmount(formData)
      }
    }
    this.setData({
      formData: JSON.stringify(formData)
    })

  },



  /**
    * @desc : 处理地址
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  setAddress(item) {
    let address = {
      address: item.addressFull,
      addressFull: item.addressFull,
      addressArea: item.addressArea,
      addressGcj02: item.addressGcj02,
      addressName: item.addressName,
    }
    return address
  },

  /**
    * @desc   : 计算金额
    * @author : 于继渤
    * @date   : 2024/1/26 11:46
    */
  calculateAmount(formData) {
    ///设置总单信息
    let sumStandard = Number(0)
    let sumAmount = Number(0)
    let sumQuantity = Number(0)
    formData.goodsList.forEach(item => {
      //标价合计 =  商品标价 x  商品数量
      sumStandard += item.amtStd
      item.outAmt = item.outQty * item.priceOut
      sumAmount += item.outQty * item.priceOut
      sumQuantity += item.outQty //数量
    })
    formData.sumStandard = sumStandard
    formData.saleDiscount = Number((sumAmount / sumStandard) * 100).toFixed(2)
    formData.sumAmount = sumAmount
    formData.outAmt = sumAmount
    formData.canUseCollect = 0
    formData.useCollect = 0
    formData.sumQuantity = sumQuantity
    formData.outQty = sumQuantity
    let cardList = this.data.cardList
    let contentSaveList = this.data.contentSaveList
    cardList[2].sumAmount = formData.sumAmount
    cardList[2].sumStandard = formData.sumStandard
    cardList[2].sumQuantity = formData.sumQuantity
    cardList[2].saleDiscount = formData.saleDiscount
    //详情 办理
    if (this.data.formMode == Constants.formMode.detail) {
      contentSaveList[1].content = formData.sumAmount
    } else {
      contentSaveList[2].content = formData.sumAmount
    }

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

  },

  /**
    * @desc : 设置顶部默认值
    * @date : 2024/3/28 15:49
    * @author : 于继渤
    */
  setStaffOrg(formData) {
    formData['staff'] = {
      text: formData.staffName ? formData.staffName : app.globalData.user.staffName,
      value: [formData.staffId ? formData.staffId : app.globalData.user.staffId]
    }
    formData['org'] = {
      text: formData.orgName ? formData.orgName : app.globalData.user.orgName,
      value: [formData.orgId ? formData.orgId : app.globalData.user.orgId]
    }
    formData.orgId = formData.orgId ? formData.orgId : app.globalData.user.orgId
    formData.staffId = formData.staffId ? formData.staffId : app.globalData.user.staffId
    return formData
  },



  /**
      * @desc : 设置表单 
      * @date : 2024/2/1 15:49
      * @author : 于继渤
      */
  setFormMain() {
    let contentObj = this.data.contentObj
    let cardList = this.data.cardList
    let buttonSaveList = this.data.buttonSaveList
    let contentSaveList = this.data.contentSaveList
    let popContent = this.data.popContent
    contentObj.main = [
      { code: 'cusName', type: 'str', readonly: true, required: false, title: mixins.$t('customerName') },
      { code: 'cusPhone', type: 'str', readonly: true, required: false, title: mixins.$t('cusPhone') },
      { code: 'addressFull', type: 'str', readonly: true, required: false, title: mixins.$t('addressFull') },
      { code: 'addressNo', type: 'str', readonly: true, required: false, title: mixins.$t('addressNo') },
      { code: 'channelName', type: 'str', readonly: true, required: false, title: mixins.$t('saleChannel') },
      { code: 'cusFromName', type: 'str', readonly: true, required: false, title: mixins.$t('customerSource') },
    ]
    contentObj.relation = [{
      code: 'fromNo',
      type: 'str',
      title: mixins.$t("sourceOrder"),//'关联源单'
      readonly: true,
    }],

      contentObj.other = [
        { code: 'contractNo', type: 'str', readonly: true, required: false, title: mixins.$t('contractNumber') },
        { code: 'deliveryDate', type: 'str', readonly: true, required: false, title: mixins.$t('delivery_Time') },
        { code: 'remarks', type: 'str', readonly: true, required: false, title: mixins.$t('remarks') },
        { code: 'file', type: 'uploader', title: mixins.$t("uploader") }
      ]

    cardList = [
      { name: 'main', title: mixins.$t("customerInformation") },
      { name: 'relation' },
      { name: 'items', title: mixins.$t("goodsDetail"), chooseGoodsFlag: false, itemAmt: '', displayNum: 2 },
      { name: 'other', title: mixins.$t("otherInfo") }
    ]
    //详情(办理)
    if (this.data.formMode == Constants.formMode.detail) {
      //按钮
      buttonSaveList = [
        { code: 'save', title: mixins.$t("outProcessing"), width: '120rpx', color: '#1B365D' }
      ]
      contentSaveList = [
        { code: 'need', title: mixins.$t("saleCollection"), type: 'str' },
        { code: 'receivable', content: 0, type: 'number' }
      ]
      popContent = [
        { code: 'outQty', type: 'step', title: mixins.$t("count"), required: true, readonly: true },
        { code: 'priceOut', type: 'number', title: mixins.$t("priceSale"), required: true, readonly: true },

        { code: 'whName', title: mixins.$t("warehouseId"), type: 'str', readonly: true, readonly: true },
        { code: 'nonStdCode', title: mixins.$t("goodsBatch"), type: 'str', readonly: true },
      ]
    }
    this.setData({
      contentObj: contentObj,
      cardList: cardList,
      popContent: popContent,
      contentSaveList: contentSaveList,
      buttonSaveList: buttonSaveList,
    })

  },


  /**
   * 生命周期函数--监听页面加载
   */
  loadInit() {
    let formData = JSON.parse(this.data.formData)
    console.log(this.data.formMode)
    if (this.data.formMode == Constants.formMode.other) { //转出库
      //查询可出库销售订单/商品
      this.setFormMain()
      this.getItemDetal(this.data.item.orderId)
    } else if (this.data.formMode == Constants.formMode.add) {  //新建
      //处理默认值  业务员业务部门
      formData = this.setStaffOrg(formData)
    } else if (this.data.formMode == Constants.formMode.detail) { //详情
      //详情办理
      wx.setNavigationBarTitle({
        title: '销售出库详情'
      })
      //设置只读
      this.setFormMain()
      this.getItemDetal(this.data.id, 'saleOutBoundService', 'getOutboundForUpdate')
    } else if (this.data.formMode == Constants.formMode.detailEdit) {
      //编辑
      wx.setNavigationBarTitle({
        title: '编辑销售出库'
      })
      this.getItemDetal(this.data.id, 'saleOutBoundService', 'getOutboundForUpdate')
    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },

})