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: 'saleOutBoundReturn',
    table: Constants.tables.order,
    orderService: app.globalData['orderService'],
    saleOutBoundReturnService: app.globalData['saleOutBoundReturnService'],
    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") }
    ],
    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: 'outingQty', type: 'step', title: mixins.$t("count"), required: true },
      { code: 'priceOut', type: 'number', title: mixins.$t("priceSale"), required: true },
      {
        code: 'whId', name: 'whName', choosePopupType: 'inventorySku', title: mixins.$t("warehouseId"), type: 'choose', urlKey: 'selectInventorySku',
      },
      { code: 'nonStdCode', title: mixins.$t("goodsBatch"), type: 'str', },
      { code: 'flgGift', title: mixins.$t("flgGift"), type: 'checkbox', },
    ],
  },



  /**
     * @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({
          btnFormData: JSON.stringify(btnFormData)
        })
      });
    }
  },

  /**
   * @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.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 : 于继渤
    */
  saveButton(e) {
    console.log(e)
    let name = e.detail.name
    if (name == 'save') { //保存
      this.save({})
    } else if (name == 'collection') { //收款

    }
  },

  /**
    * @desc : 设置保存参数
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  setParams(params) {
    let itemIndex = 0
    params.goodsList.forEach(res => {
      res['sOutId'] = res.soutId
      res['sOutItemId'] = res.soutItemId
      res['sOrderItemId'] = res.sorderItemId
      res['sOrderId'] = res.sorderId
      res.itemIndex = itemIndex++
    })


    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.objectId = params.cusId
    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.other || this.data.formMode == Constants.formMode.add) { //关联源单新建退货
      return this.excute(this.data.service, this.data.service.outboundInsert, this.data.params);
    }
    if (this.data.formMode == Constants.formMode.detail) { //办理
      return this.excute(this.data.service, this.data.service.saleReturnHandleOutbound, this.data.params);
    }
    if (this.data.formMode == Constants.formMode.other && this.data.formType == Constants.formMode.edit) { //编辑
      return this.excute(this.data.service, this.data.service.otherOutboundUpdate, this.data.params);
    }
  },

  /**
    * @desc : 查询商品明细
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  getItemDetal(id, service, API) {
    if (!API) {
      API = 'getOutReturnForUpdate'
      service = 'service'
    }
    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
        //销售订单列表转出库
        if (!API) {
          formData.fromNo = formData.formNo
        } else {
          formData.fromNo = formData.orderNo
        }
        //处理地址
        formData.address = this.setAddress(formData)
        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)
    })
    //查询商品明细
    this.getItemDetal(data.orderId)
  },

  /**
    * @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: 'outingQty', 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,
    })
  },
  /**
    * @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
      sumAmount += item.outingQty * item.priceOut //没有售价默认取标价
      sumQuantity += item.orderQty //数量
    })
    formData.sumStandard = sumStandard
    formData.saleDiscount = Number((sumAmount / sumStandard) * 100).toFixed(2)
    formData.sumAmount = sumAmount
    formData.canUseCollect = 0
    formData.useCollect = 0
    formData.sumQuantity = 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 : 于继渤
     */
  toEdit() {
    let this_ = this
    wx.navigateTo({
      url: this_.data.route.add.url,
      events: {
        // 保存成功后刷新页面
        refresh: function (data) {
        }
      },
      success: function (res) {
        res.eventChannel.emit('params', {
          formMode: Constants.formMode.other, id: this_.data.id, formType: Constants.formMode.edit
        });
      }
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  loadInit() {
    let formData = JSON.parse(this.data.formData)
    if (this.data.formMode == Constants.formMode.detail) { //详情
      //详情办理
      wx.setNavigationBarTitle({
        title: '销售退货详情'
      })
      //设置只读
      this.setFormMain()
      //查询信息
      this.getItemDetal(this.data.id)
    } else if (this.data.formMode == Constants.formMode.add) {  //新建
      //处理默认值  业务员业务部门
      formData = this.setStaffOrg(formData)
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('params', function (data) {
        console.log('新建', data)
      })
    } else if (this.data.formMode == Constants.formMode.other && this.data.formType !== Constants.formMode.edit) {
      //转退货
      //查询信息
      this.getItemDetal(this.data.item.orderId, 'orderService', 'getOrderForReturn')
    } else if (this.data.formMode == Constants.formMode.other && this.data.formType == Constants.formMode.edit) { //编辑
      wx.setNavigationBarTitle({
        title: '编辑销售退货'
      })
      //查询信息
      this.getItemDetal(this.data.id)
    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },

})