/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：选品
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		于继渤		 2024-1-23			1.00		    选品
 *******************************************************************************/
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const mixins = require('@/mixins/index.js')
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    firstFlag:true,
    orderBy: [
      {
        "text": "可售量升序",
        "value": 1
      },
      {
        "text": "可售量降序",
        "value": 2
      }
    ],
    routeObjName: 'goodsSku',
    dataItem:  null,
    choosedGoodsList: [],
    commonService: app.globalData['commonService'],
    inventoryService: app.globalData['inventoryService'],
    typeList: [
      {
        catName: '全部分类'
      }
    ],
    catId: null,
    active: 0,
    popContent:
      [
        { code: 'itemQty', type: 'step', title: '数量', required: true },
        { code: 'whId', name: 'whName', title: '仓库', type: 'choose', urlKey: 'chooseWh' },
        { code: 'skuSpec', title: '规格', type: 'str', readonly: true, dropType: '' },
        { code: 'nonStdCode', title: '商品批次', type: 'str', },
      ],
    popupTopObj: [{ leftTitle: '库存量', leftCode: 'usableQty', rightTitle: '可售量', rightCode: 'invQty' }],
    // 确定按钮
    buttonList: [{
      name: 'confirm',
      title: '确定'
    }],
    contentList: []
  },


  /**
   * @desc : 加载数据
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  loadInit() {
    this.setData({
      billType: this.data.item
    })
    //销售选品
    console.log(this.data.item)
    if (this.data.item == Constants.billType.sale || this.data.item == Constants.billType.saleOut) {
      let buttonList = this.data.buttonList
      buttonList = [{ name: 'confirm', title: '结算', color: '#CAA977' }]
      this.setData({
        buttonList: buttonList,
        contentList: [
          { code: 'need', title: mixins.$t("totalAmount"), type: 'str' },
          { code: 'amount', content: 0, type: 'number' },
          { type: 'count', code: 'count', quantity: 0 }
        ]
      })
    }
    if (this.data.item == Constants.billType.saleOut) {
      this.setData({
        popContent: [{ code: 'itemQty', 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', },]
      })
    } 
    let controlFlags = this.data.controlFlags
     //根据传过来的 控制标识实现对应的逻辑  wyj 不懂问我 
     if(controlFlags){ 
       //controlFlags.paramsByWhId 查询商品列表 是否开启顶部选择库区的 库区id 作为参数查询  
      //controlFlags.choosewhReadonly 顶部的选择库区是否可点击选择  直接用布尔值在xml控制了
      //controlFlags.chooseWhByUserDefault 顶部的选择库区是否选择用户默认的库区
   }

  },
  /**
    * @desc : 顶部切换
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  changeTag(e) {
    this.setData({
      active: e.detail.index
    })
  },
  /**
  * @desc : 分类切换
  * @date : 2024/2/1 15:49
  * @author : 于继渤
  */
  changeSidebar(e) {
    console.log(e.detail)
    let index = e.detail
    let typeList = this.data.typeList
    this.setData({
      catId: typeList[index].catId
    })
    this.searchData()
  },


  /**
   * @desc : 设置查询参数
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  setSearchParams(params) {
    params.categoryId = this.data.catId //种类id
    let controlFlags = this.data.controlFlags
    if(this.data.firstFlag&&controlFlags.chooseWhByUserDefault){ //顶部的选择库区是否选择用户默认的库区
      let form = this.data.form||{}
      form.whId = app.globalData.user.defaultWhId
      form.whName = app.globalData.user.defaultWhName 
      this.setData({
        form:form
      })
     }
    if(controlFlags.paramsByWhId){
      params.whId = this.data.form.whId //仓库
    }   
    this.setData({
      firstFlag : false
    })
    return params
  },
  /**
   * @desc : 查询
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getData(params) {
    if (this.data.item == Constants.billType.sale) {
      return this.excute(this.data.commonService, this.data.commonService.getGoodsForOrderByPage, params);
    } else if (this.data.item == Constants.billType.out || this.data.item == Constants.billType.purReturn) {
      return this.excute(this.data.inventoryService, this.data.inventoryService.selectByCond, params);
    } else if (this.data.item == Constants.billType.saleOut) {
      return this.excute(this.data.commonService, this.data.commonService.getGoodsForOrder, params);
    } else {
      return this.excute(this.data.service, this.data.service.selectByCond, params);
    }
  },

  /**
     * @desc :   处理接口返回数据
     * @date : 2024/2/1 15:49
     * @author : 于继渤
     */
  handleSearchData(tableData) {
    //设置默认仓库
    if(this.data.item != "out"){
      tableData.forEach(res => {
        res.whId = app.globalData.user.defaultWhId
        res.whName = app.globalData.user.defaultWhName 
      })
      this.setData({
        tableData: tableData
      })
    }

    if(  this.data.controlFlags.sourcePage == "inventory-adjustment"){ //库存调整 设置
      let popContent = this.data.popContent
      let tableData = this.data.tableData
      let index = popContent.findIndex(t => t.code == 'oWhId')
      if(index>=0){ //进入说明 调整类型是 仓库调整
        popContent[index].urlKey = '' 
        let form = this.data.form
        tableData.forEach(res => { //取上面的选择库区组件的值附到源库区 把目标库区 先清掉
         res.oWhId = form.whId
         res.oWhName = form.whName
         res.whId = ''
         res.whName = ''
       }) 
      }
      let index_ = popContent.findIndex(t => t.code == 'oNonStdCode')
      if(index_>=0){ //进入说明 调整类型是 非标号调整
        popContent[index_].urlKey = ''  
        tableData.forEach(res => { //取上面的选择库区组件的值附到源库区 把目标库区 先清掉
         res.oNonStdCode = res.nonStdCode
         res.nonStdCode = '' 
       }) 
      }
    this.setData({
     popContent:popContent,
     tableData:tableData
    })
 }
   
  },
  /**
* @desc : 获取种类
* @date : 2024/2/1 15:49
* @author : 于继渤
*/
  getGoodsCategoryNoPage() {
    return this.excute(this.data.commonService, this.data.commonService.getGoodsCategoryNoPage, {}).then(res => {
      console.log('goodsCategoryListBy', res.data.data)
      this.setData({
        typeList: this.data.typeList.concat(res.data.data)
      })
    })
  },
  /**
* @desc : 打开商品
* @date : 2024/2/1 15:49
* @author : 于继渤
*/
  openAddItemInfo(e) {
    console.log('openAddItemInfo',e)
    let item = e.currentTarget.dataset.item
    item.itemQty = 1   //打开 popur 数量默认为1
    // item.nonStdCode = "-" //不要在这赋值非标号 想赋值去查询回来处理的方法去赋值
    if (this.data.item == Constants.billType.saleOut) { //跟进仓库批次号cpid 查询库存
      console.log('globalData', app.globalData)
      this.getInventory(
        {
          skuId:item.skuId, 
          cpId:app.globalData.user.cpId, 
          nonStdCode:item.nonStdCode, 
        }
      )
    }

    this.setData({
      dataItem: JSON.stringify(item),
      showPop: true,
    })
  },

  /**
    * @desc : 查询库存
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  getInventory(params) {
    return this.excute(this.data.commonService, this.data.commonService.getInventory, params);
  },
  /**
    * @desc : 商品确认事件
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  editItems(e) {
    let choosedGoodsList = this.data.choosedGoodsList
    choosedGoodsList.push(e.detail.form)
    this.setData({
      choosedGoodsList: choosedGoodsList
    })
    //销售订单需要计算底部按钮
    if (this.data.item == Constants.billType.sale || this.data.item == Constants.billType.saleOut) {
      this.calculateParameters()
    }
  },



  /**
  * @desc : 计算数量金额 销售用
  * @date : 2024/2/1 15:49
  * @author : 于继渤
  */
  calculateParameters() {
    let contentList = this.data.contentList
    let choosedGoodsList = this.data.choosedGoodsList
    let sumAmt = Number(0)
    let sumQty = Number(0)
    choosedGoodsList.forEach(res => {
      sumAmt += (res.priceStandard * res.itemQty)
      sumQty += res.itemQty
    })
    contentList[1].content = sumAmt
    contentList[2].quantity = sumQty
    this.setData({
      contentList: contentList
    })
  },



  /**
    * @desc : 结算按钮
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  submit() {
    const eventChannel = this.getOpenerEventChannel();
    const choosedGoodsList = this.data.choosedGoodsList
    const chooseRoute = this.data.chooseRoute
    let that = this
    if (chooseRoute) { //跳转到上一个页面传过来的url
      wx.navigateTo({
        url: chooseRoute,
        events: {
          // 回调后
          bindData: function (data) { }
        },
        success: function (res) {
          let data = { item: choosedGoodsList }
          if(that.data.formType == 'customer-reception'){ //客户接待跳转过来
            data['formItem'] = that.data.formItem
          }
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('params', data)
        }
      })
    } else {
      eventChannel.emit('bindData', { choosedGoodsList })
      wx.navigateBack({
        delta: 1
      })
    }

  },

  /**
   * @desc : 下拉多选事件
   * @author : 于继渤
   * @date : 2022/5/26 12:16
   */
  dropdowncommit(e) { 
    this.setData({
      whFlag: true
    })
  },
    /**
   * @desc : 下拉多选确定
   * @author : 王英杰
   * @date : 2023年9月8日
   */
  mutiSearch(e) { 
    let id = e.target.id
    let form = this.data.form||{}
    
    if (id === 'warehouse') {
      form.whId = e.detail.item.id
      form.whName = e.detail.item.name
      this.setData({
        whFlag: false,
        form: form
      })
      this.selectComponent("#statusItemWareHouse").toggle(false)
      // this.searchData()
    }
  },
  /**
    * @desc : 初始化
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
  onLoad() {
    this.getGoodsCategoryNoPage()
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      }
    }) 
  },
})