// package-basic-data/pages/test/add/add.js
const mixins = require('@/mixins/index.js')
const Constants = require('@/utils/Constants');
const config = require('@/config/config.js')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    intoStatusflag: true,
    // 弹出按钮
    buttonList: [{
      name: 'merge',
      title: ''
    }],
    contentList: [{
      code: 'need',
      title: mixins.$t("totalAmount"), //合计金额
      type: 'str'
    }, {
      code: 'amount',
      content: 2000,
      type: 'number'
    }],
    cardList: [{
      name: 'warehouse',
    }, {
      name: 'relation'
    }, {
      name: 'items',
      title: mixins.$t("goodsDetail"), //'商品明细'
      chooseGoodsFlag: '',
      itemAmt: '',
      displayNum: 2
    }, {
      name: 'other',
      title: mixins.$t("otherInfo") //'其他信息'
    }],
    contentObj: {
      warehouse: [{ //入库仓库
        code: 'whId',
        name: 'whName',
        title: mixins.$t("whName"),
        type: 'choose',
        urlKey: 'chooseWh',
        readonlyItem: true,
      }],
      relation: [{
        code: 'sourceNo',
        name: 'fromNo',
        type: 'choose',
        controlChooseFlag: true,
        title: mixins.$t("sourceOrder"), //'关联源单'
        urlKey: 'choosePurchaseOrder',
        readonlyItem: true,
      }],
      items: [],

      other: [{
        code: 'remarks',
        type: 'textarea',
        title: mixins.$t("remarks"), //'备注'
      }, {
        code: 'file',
        type: 'uploader',
        title: mixins.$t("uploader"), //'附件'
      }]
    },
    popContent: [{
        code: 'priceInto',
        type: 'number',
        title: mixins.$t("inboundPrice"),
        required: true
      }, {
        code: 'itemQty',
        type: 'step',
        title: mixins.$t("count"), //'数量',
        required: true
      },
      {
        code: 'packageBox',
        type: 'packageBox',
        title: mixins.$t("packageBox"),
        readonly: true
      },
      {
        code: 'whId',
        name: 'whName',
        title: mixins.$t("warehouseId"), //'仓库',
        type: 'drop',
        dropType: 'warehouse'
      },
      {
        code: 'skuSpec',
        title: mixins.$t("goodSpec"), //'规格',
        type: 'str',
        readonly: true
      },
      {
        code: 'brandName',
        title: mixins.$t('brandName'), 
        type: 'str',
        readonly:true,
    },
      {
        code: 'nonStdCode',
        title: mixins.$t("goodsBatch"), //'色号',
        type: 'str',
        tip: mixins.$t('tipPop'),
      },
    ],


    inboundService: app.globalData['inboundService'],
    inboundProcessingService: app.globalData['inboundProcessingService'],
    // 路由
    routeObjName: 'inbound',
  },
  /**
   * @desc : （编辑）
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  toEdit(e) {
    let intoId = e.currentTarget.dataset.item.intoId
    wx.navigateTo({
      url: this.data.route.add.url,
      events: {
        // 回调后，在这里给页面赋值
        bandData: function (e) {}
      },
      success: function (res) {
        res.eventChannel.emit('params', {
          id: intoId,
          formMode: Constants.formMode.edit
        })
      }
    })
  },
  /**
   * @desc : dk-from choose 回调事件
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  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 == "whId") { //商品品牌
      formData.whId = data.id
      formData.whName = data.name
    }

    this.setData({
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : 给表单赋值
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setValuesByEdit(data) {
    let cardList_ = this.data.cardList
    let contentList_ = this.data.contentList
    let sumitemAmt = 0
    let formType = this.data.formType
    if (this.data.formType == 2) { //查询采购订单表 未入库的 详细 
      this.setData({
        buttonList: [{
          name: 'merge',
          title: mixins.$t("close"), //'关闭'
        }],
      })
    } else {
      this.setData({
        buttonList: [{
          name: 'merge',
          title: mixins.$t("inProcessing"), //'入库办理'
        }],
      })
    }


    data.goodsList.forEach(element => { //删掉查出的无用数据 
      if (element.intoStatus == Constants.intoStatus.inBounded) //"入库状态-已入库"
      {
        element.itemAmt = element.priceInto * element.intoQty
        element.itemQty = element.intoQty
        element.box = element.intoBox
        element.piece = element.intoPiece
      } else {
        element.itemAmt = element.priceInto * element.intoingQty
        element.itemQty = element.intoingQty
        element.box = element.intoingBox
        element.piece = element.intoingPiece
      }
      //设置商品明细输入数量 最大 最小限制 
      element['itemQty_max'] = element.itemQty
      element['itemQty_min'] = 1
      if (data.whId) {
        element.whId = data.whId
        element.whName = data.whName
      }
      if (element.skuImages && element.skuImages.length > 0) {
        element.skuImages.forEach(item => {
          item.url = config.image_url + item.path
        });
        element.imagesUrl = element.skuImages[0].url
      }
      if (element.flgSubUnit) {
        element.calculationFormula = element.packBox + element.unitName + '= 1' + element.subUnitName
        element.packageBox = element['box'] + element.subUnitName + element['piece'] + element.unitName 
      }
      element.sumPrice =   element.priceInto * element.itemQty
    });

    sumitemAmt = data.goodsList.sum("itemAmt")
    cardList_.forEach(card => {
      if (card.name === 'items') {
        if (formType == 1) {
          card.info = "（" + mixins.$t('warehousingProcessing') + "）",
            card.color = "#E4002B"
        } else {
          card.info = "（" + mixins.$t("checkined") + "）",
            card.color = "#1B365D"
        }
        card.itemAmt = sumitemAmt
        card.itemQty = data.goodsList.sum("itemQty")
      }
    })
    contentList_[1].content = sumitemAmt

    // 刷新商品明细 显示 查看更多
    let card = this.data.cardList.filter(it => it.name == 'items');
    this.selectComponent('#' + this.data.formName).handleContentObj(card[0])
    console.log(data);
    this.setData({
      itemData: data,
      cardList: cardList_,
      contentList: contentList_,
      intoStatusflag: data.intoStatus !== Constants.intoStatus.inBounded,
      formData: JSON.stringify(data),
      sumitemAmt
    })

  },

  /**
   * @desc : 外露设置产品方法 
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setGoods(e) {
    let contentList_ = this.data.contentList
    let cardList = this.data.cardList
    let formData = JSON.parse(this.data.formData)
    let totalAmout = Number(0)
    // 各个明细的金额数量
    formData.goodsList.forEach(element => { //循环出商品总共价格    
      element.intoingQty = element.itemQty
      element.priceInto = element.priceInto ? element.priceInto : element.pricePurchase
      element.intoingAmt = element.priceInto * element.itemQty
      element.intoAmt = 0 //  已入库金额
      element.intoQty = 0 //  已入库数量
      totalAmout += Number(element.priceInto) * Number(element.itemQty)
    })
    // 左下角的合计金额
    contentList_.forEach(card => {
      if (card.code === 'amount') {
        card.content = totalAmout
      }
    })
    // 明细的合计金额
    cardList.forEach(card => { //循环出商品总共价格
      if (card.name === 'items') {
        //合计金额
        card.itemAmt = totalAmout
        card.itemQty = formData.goodsList.sum("itemQty")
      }
    })
    console.log(formData.goodsList);
    this.setData({
      contentList: contentList_,
      cardList,
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : 保存的參數設置
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setParams(params) {

    let formData = JSON.parse(this.data.formData)
    formData.goodsList.forEach(element => {
      element.sPurId = element.fromId //来源id
      element.sPurItemId = element.fromItemId //来源单明细id
    });
    params.allEdit = true //大编辑
    params.itemList = formData.goodsList //商品明细
    params.deleteItemList = []
    params.fromId = formData.fromId //来源id
    params.fromNo = formData.fromNo //来源单号 
    params.orgId = formData.orgId //组织部门
    params.staffId = formData.staffId // 员工
    params.supId = formData.supId // 供应商
    params.whId = formData.whId // 仓库
    params.remarks = formData.remarks // 备注
    params.makeStaff = formData.staffId // 制单人
    params.intoDate = this.formatDate()
    console.log("save", this.data.params);
    return params
  },
  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  saveData() {
    if (this.data.formType == 1) {
      return this.excute(this.data.inboundProcessingService, this.data.inboundProcessingService.inBoundHandle, this.data.params)
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },
  formatDate() {
    var date = new Date();
    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2);
    var day = ("0" + date.getDate()).slice(-2);

    return year + "-" + month + "-" + day;
  },
})