const Constants = require('@/utils/Constants.js');
import Dialog from '@/dist/dialog/dialog.js';
const mixins = require('@/mixins/index.js')
const app = getApp()
const utils = require('@/utils/util')
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    routeObjName: 'inboundReturn',
    tableData: [],
    btnFormData: JSON.stringify({ flag: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false }),
    // 系统参数
    flgHandleSetting: app.globalData.setting[Constants.settingCode.IVT001] == "true" ? true : false,
    pageFlag: false,
    pageFlag: false,
    flgAutoIvt: false,
    showPopFlag: true,
    stepperFlag: true,
    cardList: [
      { name: 'main', title: '' },
      { name: 'relation', title: '' },
      { name: 'items', title: mixins.$t("goodsDetail"), chooseGoodsFlag: false, sumReturnAmt: 0, displayNum: 2 },
      { name: 'other', title: mixins.$t("otherInfo") }
    ],

    cardContentList: [
      { code: 'whId', name: 'whName', title: mixins.$t("warehouseId"), type: 'choose', urlKey: 'openingInventory' }
    ],

    contentObj: {
      main: [
        { code: 'supId', name: 'supName', title: mixins.$t("supplier"), type: 'choose', required: true, urlKey: 'chooseSupplier' },
        { code: 'returnAddress', type: 'address', title: mixins.$t('returnAddress'), required: true },
        { code: 'intoDate', type: 'date', required: false, title: mixins.$t("returnDate"), required: false },
      ],
      relation: [{
        code: 'fromNo',
        name: 'fromNo',
        type: 'choose',
        controlChooseFlag: true,
        title: mixins.$t("sourceOrder"),//'关联源单'
        urlKey: 'selectSourcePurchaseOrder'
      }],
      other: [{
        code: 'remarks',
        type: 'textarea',
        title: mixins.$t("remarks")
      }, {
        code: 'file',
        type: 'uploader',
        title: mixins.$t("uploader")
      }]
    },
    buttonList: [{
      name: 'merge',
      title: mixins.$t("save"),//'保存'
    }],
    contentList: [{
      code: 'flag',
      title: mixins.$t("antoHandle"),//'自动入库办理',
      type: 'checkbox'
    }, {
      code: 'need',
      title: mixins.$t("totalReturn"),//'合计金额',
      type: 'str'
    }, {
      code: 'sumReturnAmt',
      content: 0,
      type: 'number'
    }],


  },
  /**
   * @desc   : 绑定数据
   * @author : 于继渤
   * @date   : 2024年3月12日
   */
  chooseData(e) {
    console.log("t", e, this.data.formData);
    let formData = JSON.parse(this.data.formData)
    let code = e.detail.code
    let data = e.detail.data.data
    if (code == "supId") { //供应商
      formData.supId = data.id
      formData.supName = data.name
      console.log('supId', data.item.returnAddress)
      formData.returnAddress = data.item.returnAddress
      //处理地址
      formData.address = {
        address: data.item.returnAddress,
        addressFull: data.item.returnAddress,

      }
    }
    ///设置主从业务员
    if (code == 'staff') {
      formData.staff = e.detail.data.staffItem
      formData['staffId'] = e.detail.data.staffMain.staffId
      formData['staffName'] = e.detail.data.staffMain.staffName
      formData['staffList'] = e.detail.data.staffList
      console.log(e.detail.data.staffList)
    }
    ///设置主从业务部门
    if (code == 'org') {
      console.log('data', e.detail.data)
      formData.org = e.detail.data.orgItem
      formData['orgId'] = e.detail.data.orgMain.orgId
      formData['orgName'] = e.detail.data.orgMain.orgName
      formData['orgList'] = e.detail.data.orgList
    }
    //选择源单
    if (code == 'fromNo') {
      console.log('e.detail', e.detail)
      if (data.itemList && data.itemList.length > 0) {
        data.itemList.forEach(item => {
          item.returnQty = item.itemQty
          item.returnAmt = item.itemAmt
        })
        console.log('data', data)
        formData.goodsList = data.itemList
        formData.fromNo = data.itemList[0].intoNo
        this.setData({
          formData: JSON.stringify(formData),
          beforeSumAmount: Number(data.beforeSumAmount)
        })
        this.calculateTotal()
      }
    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
* @desc : 设置保存参数
* @date : 2024/3/19 15:49
* @author : 于继渤
*/
  setParams(params) {
    if (this.data.formMode !== 'edit' && this.data.formType !== 'add') {
      params.fromId = this.data.item.purId ? this.data.item.purId : params.purId //采购订单id
      params.fromNo = this.data.item.purNo ? this.data.item.purNo : params.purNo //采购订单id
      params.supId = this.data.item.supId
    } else {
      //没源单的明细
      let itemIndex = 0
      params.goodsList.forEach(res => {
        res.itemIndex = itemIndex++
      })
    }

    let btnFormData = this.data.btnFormData ? JSON.parse(this.data.btnFormData) : ''
    if (this.data.flgHandleSetting) {
      params.flgAutoHandle = true
    } else {
      params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出入库标识 
    }
    // 系统参数
    params.flgHandleSetting = this.data.flgHandleSetting
    params.itemList = params.goodsList
    params.orgId = app.globalData.user.orgId
    params.staffId = app.globalData.user.staffId
    params.makeStaff = app.globalData.user.staffId
    params.returnQty = this.data.sumReturnQty
    params.returnAmt = Number(this.data.sumReturnAmt)
    params.limitEdit = this.data.formMode == 'edit' ? true : false
    delete params['goodsList']
    delete params['sumReturnAmt']
    delete params['sumReturnQty']
    console.log('params', params)
    // return
    return params
  },

  /**
    * @desc : 保存数据服务
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  saveData() {
    if (this.data.formType == 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);
    }
  },


  //展开
  collapseFlagChange(e) {
    this.setData({
      collapseFlag: !this.data.collapseFlag
    })
  },

  /**
  * @desc :商品明细数量加减事件
  * @date : 2024/2/1 15:49
  * @author : 于继渤
  */
  onChangeStepper(e) {
    let index = e.detail.index
    let formData = JSON.parse(this.data.formData)
    formData.goodsList[index].itemQty = e.detail.item
    formData.goodsList[index].returnQty = e.detail.item
    this.setData({
      formData: JSON.stringify(formData)
    })
    this.calculateTotal()
  },

  /**
     * @desc : 外露设置产品方法 
     * @date : 2024/2/1 15:49
     * @author : 于继渤
     */
  setGoods(e) {
    console.log('外露设置产品方法', e)
    let contentObj = this.data.contentObj
    contentObj.relation = [{
      code: 'fromNo',
      name: 'fromNo',
      type: 'choose',
      controlChooseFlag: true,
      readonlyReturn: true,
      title: mixins.$t("sourceOrder"),//'关联源单'
      urlKey: 'selectSourcePurchaseOrder'
    }]
    this.setData({
      contentObj: contentObj
    })
    this.calculateTotal()
  },

  /**
* @desc :删除
* @date : 2024/2/1 15:49
* @author : 于继渤
*/
  delItem() {
    let formData = JSON.parse(this.data.formData)
    if (formData.goodsList.length == 0) {
      let contentObj = this.data.contentObj
      contentObj.relation = [{
        code: 'fromNo',
        name: 'fromNo',
        type: 'choose',
        controlChooseFlag: true,
        readonlyReturn: false,
        title: mixins.$t("sourceOrder"),//'关联源单'
        urlKey: 'selectSourcePurchaseOrder'
      }]
      this.setData({
        contentObj: contentObj
      })
    }

  },
  /**
* @desc :计算金额
* @date : 2024/2/1 15:49
* @author : 于继渤
*/
  calculateTotal(goodsList) {
    let formData = JSON.parse(this.data.formData)
    let sumReturnAmt = Number(0) //合计金额
    let sumReturnQty = Number(0) //合计金额
    formData.goodsList.forEach(res => {
      if (this.data.formMode != 'edit') {
        res.returnQty = res.itemQty
      }
      res.returnAmt = Number(res.returnQty * res.priceReturn * -1)
      sumReturnAmt += res.returnAmt
      sumReturnQty += res.returnQty
    })
    let cardList = this.data.cardList
    let contentList = this.data.contentList
    formData.returnAmt = sumReturnAmt
    formData.sumReturnAmt = sumReturnAmt
    formData.returnQty = sumReturnQty
    if (this.data.formMode = 'add') {
      cardList[2].sumReturnAmt = sumReturnAmt.toFixed(2)
    } else {
      cardList[0].sumReturnAmt = sumReturnAmt.toFixed(2)
    }
    if (contentList.length > 0) {
      contentList[2].content = sumReturnAmt.toFixed(2)
    }
    let beforeSumAmount = this.data.beforeSumAmount
    let afterSumAmount = beforeSumAmount - sumReturnAmt
    this.setData({
      afterSumAmount: afterSumAmount,
      cardList: cardList,
      contentList: contentList,
      formData: JSON.stringify(formData),
      sumReturnAmt: sumReturnAmt.toFixed(2),
      sumReturnQty: sumReturnQty,
    })
    if (this.data.formType !== 'edit') {
      this.calculationSalesUsableQty()
    }
    // this.calculationSalesUsableQty()
  },
  /**
   * @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(() => {
        that.setData({
          goodsTagText: null
        })
      }).catch(() => {
        btnFormData.flag = true
        that.setData({
          btnFormData: JSON.stringify(btnFormData)
        })
      });
    }
  },


  /**
    * @desc : 给表单赋值
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  setValuesByEdit(data) {
    let formData = JSON.parse(this.data.formData)
    data.goodsList.forEach(res => {
      //处理图片
      if (res.skuImages) {
        res['imagesUrl'] = res.skuImages.length > 0 ? res.skuImages[0].url : null
      }
      res['itemQty'] = res.returnQty
      res['itemQtyMin'] = res.sintoItemIntoQty ? Number(res.sintoItemIntoQty * -1) : Number(res.invQty * -1)
      res['itemQtyMax'] = Number(-1)
      res['priceReturn'] = res.priceInto * -1
      if (res.fromId) {
        //有关联源单
        res['swipeDisabled'] = true
      }
    })
    formData = data
    //处理地址
    formData.address = {
      address: data.returnAddress,
      addressFull: data.returnAddress,
    }
    this.setData({
      beforeSumAmount: data.returnAmt,
      formData: JSON.stringify(formData)
    })
    //设置业务员业务部门
    this.setStaffOrg()
    this.calculateTotal()
  },


  //计算可售量相关
  calculationSalesUsableQty() {
    let formData = JSON.parse(this.data.formData)
    formData.goodsList.forEach(res => {
      //选择的数量大于可售量
      if (Math.abs(res.itemQty) > res.usableQty) {
        res['usableQtyInsufficientFlag'] = true  //可售量不足
        res['usableQty'] = res.usableQty  //可售量
      } else {
        res['usableQtyInsufficientFlag'] = false  //可售量不足
        res['usableQty'] = res.usableQty  //可售量
      }
    })
    let usableQtyInsufficientFlagList = formData.goodsList.filter(item => {
      return item.usableQtyInsufficientFlag
    })
    this.setData({
      formData: JSON.stringify(formData),
      goodsTagText: usableQtyInsufficientFlagList.length > 0 ? '备货不足' : '备货齐套', //
      goodsTagColor: usableQtyInsufficientFlagList.length > 0 ? '#E4002B' : null  //设置颜色
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //接收父页面传递的参数
    let that = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('params', function (data) {
      console.log('formMode', that.data.formMode)
      console.log('formType', that.data.formType)
      if (that.data.formMode !== Constants.formMode.edit && that.data.formType !== Constants.formMode.add) {
        let formData = that.data.formData
        formData = {
          goodsList: data.choooseInboundItemList
        }
        let item = data.item ? JSON.parse(data.item) : null
        if (item) {
          formData.fromNo = item.fromNo
          formData.supId = item.supId
          formData.supName = item.supplierName
          formData.returnAddress = item.returnAddress
          //处理地址
          formData.address = {
            address: item.returnAddress,
            addressFull: item.returnAddress,
          }
          formData.intoDate = utils.formatDayTime(new Date())

        }
        that.setData({
          formData: JSON.stringify(formData),
          beforeSumAmount: Number(data.beforeSumAmount),
          tableData: data.choooseInboundItemList,
          item: item
        })
        //设置业务员业务部门
        that.setStaffOrg()
        that.calculateTotal()
      } else if (that.data.formMode == Constants.formMode.add && that.data.formType == Constants.formMode.add) {
        console.log('源单跳转来的2')
        that.setStaffOrg()
        that.setData({
          cardList: [
            { name: 'main' },
            { name: 'relation' },
            { name: 'items', title: mixins.$t("goodsDetail"), chooseGoodsFlag: true },
            { name: 'other', title: mixins.$t("otherInfo") }
          ]
        })
      }
    })
  },


  /**
    * @desc : 设置业务员业务部门
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  setStaffOrg() {
    let formData = JSON.parse(this.data.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)
    })
  },
  loadInit() {

    let flgHandleSetting = this.data.flgHandleSetting //true为自动办理  false 为手动办理
    let contentList = this.data.contentList
    if (flgHandleSetting) { //系统参数中的自动办理参数  隐藏左下角cheakbox
      // 使用 filter 方法删除 code 为 flag 的项  
      contentList = contentList.filter(item => item.code !== 'flag');
      this.setData({
        contentList: contentList,
      })
    }
    if (this.data.formMode != Constants.formMode.edit) {
      let formData = JSON.parse(this.data.formData)
      formData.intoDate = utils.formatDayTime(new Date())
      //设置业务员业务部门
      this.setStaffOrg()
      this.setData({
        formData: JSON.stringify(formData)
      })
    }

  }

})