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: true }),
    pageFlag: false,
    pageFlag: false,
    flgAutoIvt: false,
    showPopFlag: true,
    stepperFlag: true,
    cardList: [
      { 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: 'staffId', name: 'staffName', title: mixins.$t("procureStaff"), type: 'choose', urlKey: 'chooseStaff'
        },
        {
          code: 'orgId', name: 'orgName', title: mixins.$t("procureOrg"), type: 'choose', urlKey: 'chooseOrg'
        }
      ],
      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
    }
    if (code == "staffId") { //员工
      formData.staffId = data.id
      formData.staffName = data.name
    }
    if (code == "orgId") { //员工
      formData.orgId = data.id
      formData.orgName = data.name
    }
    //选择源单
    if (code == 'fromNo') {
      console.log('e.detail',e.detail)
      if (data.itemList && data.itemList.length > 0) {
     
        formData.goodsList = data.itemList
        formData.fromNo = data.fromNo
        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) : ''
    params.flgAutoHandle = btnFormData ? btnFormData.flag : false //自动出入库标识 
    // params.flgHandleSetting = btnFormData ? btnFormData.flag : false //自动出入库标识 
    params.itemList = params.goodsList
    params.orgId = app.globalData.user.orgId
    params.staffId = app.globalData.user.staffId
    params.makeStaff = app.globalData.user.staffId

    params.intoDate = utils.formatDayTime(new Date())
    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.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 : 于继渤
*/
  handleData() {
    wx.navigateBack({
      data: 1
    })
  },
  //展开
  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 formData = JSON.parse(this.data.formData)
    // let goodsList = e.detail.data
    // let sumReturnAmt = Number(0) //合计金额
    // let sumReturnQty = Number(0)
    // goodsList.forEach(res => {
    //   res.priceReturn = res.priceStandard * -1
    //   sumReturnAmt += res.priceReturn * res.itemQty
    //   res.itemAmt = Number(res.priceReturn * res.itemQty)
    //   res.itemQtyMax = res.usableQty * -1
    //   res.itemQtyMin = -1
    //   res.itemQty = res.itemQty * -1
    // })
    // formData.sumReturnAmt = sumReturnAmt.toFixed(2)
    // this.setData({
    //   formData: JSON.stringify(formData)
    // })
    this.calculateTotal()
  },
  /**
* @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
    })
    formData.returnAmt = sumReturnAmt
    formData.returnQty = sumReturnQty
    let cardList = this.data.cardList
    let contentList = this.data.contentList
    cardList[1].sumReturnAmt = sumReturnAmt.toFixed(2)
    if (contentList.length > 0) {
      contentList[2].content = sumReturnAmt.toFixed(2)
    }
    let beforeSumAmount = this.data.beforeSumAmount
    let afterSumAmount = beforeSumAmount - sumReturnAmt

    console.log('sumReturnAmt', sumReturnAmt)
    this.setData({
      afterSumAmount: afterSumAmount,
      cardList: cardList,
      contentList: contentList,
      formData: JSON.stringify(formData),
      sumReturnAmt: sumReturnAmt.toFixed(2),
      sumReturnQty: sumReturnQty,
    })

    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(() => { }).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 => {
      res['itemQty'] = res.returnQty
      res['itemQtyMin'] = Number(res.sintoItemIntoQty * -1)
      res['itemQtyMax'] = Number(-1)
      res['priceReturn'] = res.priceInto * -1
    })
    formData = data
    this.setData({
      beforeSumAmount: data.returnAmt,
      formData: JSON.stringify(formData)
    })
    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) {
      if (that.data.formMode != Constants.formMode.edit && that.data.formType != Constants.formMode.add) {
        let formData = that.data.formData
        formData = {
          goodsList: data.choooseInboundItemList
        }
        console.log('data', data)
        that.setData({
          formData: JSON.stringify(formData),
          beforeSumAmount: Number(data.beforeSumAmount),
          tableData: data.choooseInboundItemList,
          item: JSON.parse(data.item)
        })
        that.calculateTotal()
      } else if (that.data.formMode == Constants.formMode.add && that.data.formType == Constants.formMode.add) {
        let cardList = that.data.cardList
        that.setData({
          cardList: [
            { name: 'main' },
            { name: 'relation' },
            { name: 'items', title: mixins.$t("goodsDetail"), chooseGoodsFlag: true },
            { name: 'other', title: mixins.$t("otherInfo") }
          ]
        })
      }

    })
  },


})