/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：选品
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		于继渤		 2024-1-23			1.00		    选品
 *******************************************************************************/
const mixins = require('@/mixins/index.js')
import Dialog from '@/dist/dialog/dialog.js';
const config = require('@/config/config.js');
const app = getApp()
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {

    imageUrl: config.image_url + '/static/img/',
    routeObjName: 'goodsSku',
    dataItem: '{}',
    toAddOtherWarehousingUrl: '/package-inventory/pages/other-warehousing/other-warehousing',
    choosedGoodsList: [],
    commonService: app.globalData['commonService'],
    inventoryService: app.globalData['inventoryService'],
    typeList: [{
      brandName: '全部品牌'
    }],
    brandId: null,
    active: 0,
    popContent: [{
        code: 'itemQty',
        type: 'step',
        title: '数量',
        required: true
      },
      {
        code: 'packageBox',
        type: 'packageBox',
        title: mixins.$t("packageBox"),
      },
      {
        code: 'priceSale',
        type: 'number',
        title: '销售单价  ',
        required: true
      },
      {
        code: 'whId',
        name: 'whName',
        title: '库区',
        type: 'choose',
        urlKey: 'openingInventory',
        readonly:true,
        
      },
      {
        code: 'brandName',
        title: mixins.$t('brandName'), 
        type: 'str',
        readonly:true,
    },
      {
        code: 'nonStdCode',
        title: '色号',
        type: 'str',
        tip: mixins.$t('tipPop'),
        readonly:true,
      },
    ],
    // 确定按钮
    buttonList: [{
      name: 'confirm',
      title: '结算'
    }],
    contentList: [{
        code: 'amount',
        content: 0,
        type: 'number',
        title: mixins.$t("totalAmount")
      },
      { 
        type: 'count',
        code: 'count',
        quantity: 0
      }
    ],
    saleChannelService: app.globalData['saleChannelService'],
  },
  /**
   * @desc : 设置销售渠道
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getDefChannel() {
    this.excute(this.data.saleChannelService, this.data.saleChannelService.selectByCond, {
      flgDefault: true
    }).then(res => {
      if (res.data.code == 200) {
        if (res.data.data.list && res.data.data.list.length > 0) {
          this.setData({
            channelId: res.data.data.list[0].channelId,
            channelName: res.data.data.list[0].channelName,
            channelCode: res.data.data.list[0].channelCode
          })
        }

      }
    })
  },
  /**
   * @desc : 删除已选
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  delChoosedGoodsItem(e) {
    console.log('delChoosedGoodsItem', e)
    let index = e.currentTarget.dataset.index
    let choosedGoodsList = this.data.choosedGoodsList
    choosedGoodsList.splice(index, 1)
    this.setData({
      choosedGoodsList: choosedGoodsList
    })
    this.calculateParameters()
  },
  /**
   * @desc   : 再次打开箱片的弹框
   * @author : 周兴
   * @date   : 2024/1/26 11:46
   */
  openPackageBox(e) {
    console.log("openPackageBox-", e);
    let dataItem = JSON.parse(this.data.dataItem)
    this.setData({
      popContentBox: [{
          code: 'box',
          type: 'step',
          title: dataItem.subUnitName,
          required: true
        },
        {
          code: 'piece',
          type: 'step',
          title: dataItem.unitName,
          required: true
        },
      ],
      showPopBox: true,
    })
  },
  /**
   * @desc : 数量改变事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  changeStep(e) {
    let dataItem = JSON.parse(this.data.dataItem)
    let key = e.detail.key
    let value = e.detail.value
    dataItem[key] = value
    //箱片的取值逻辑： 箱 =(数量/包装）取整，片= （数量%包装）取余数
    if (key == 'itemQty') {
      dataItem['itemQty'] = value
      dataItem['box'] = parseInt(value / dataItem.packBox)
      dataItem['piece'] = Number(value % dataItem.packBox)
      dataItem.packageBox = dataItem['box'] + dataItem.subUnitName + dataItem['piece'] + dataItem.unitName
      dataItem.sumPrice = dataItem['itemQty'] * dataItem.priceSale
    }
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },
  /**
   * @desc : 商品确认事件--箱片的确认
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  editItemsBox(e) {
    let dataItem = JSON.parse(this.data.dataItem)
    dataItem['itemQty'] = Number(dataItem['box']) * Number(dataItem['packBox']) + Number(dataItem['piece']) 
    dataItem.packageBox = dataItem['box'] + dataItem.subUnitName + dataItem['piece'] + dataItem.unitName
    dataItem.sumPrice = dataItem.priceSale * dataItem.itemQty
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },

  /**
   * @desc   : 修改数值离开框的值
   * @author : 周兴
   * @date   : 2024/2/2 11:46
   */
  blurNumberField(e) {
    console.log("blurNumberField", e);
    let dataItem = JSON.parse(this.data.dataItem)
    if (dataItem.priceLimited) { //如果有销售限价 那就判断下
      if (dataItem.priceLimited > e.detail.value) { //低于限价 那就把下限付给销售价格
        dataItem.priceSale = dataItem.priceLimited
      } else {
        dataItem.priceSale = e.detail.value
      }
    } else {
      dataItem.priceSale = e.detail.value
    }

    dataItem.sumPrice = dataItem['itemQty'] * dataItem.priceSale
    this.setData({
      dataItem: JSON.stringify(dataItem)
    })
  },

  /**
   * @desc : 新建其他入库
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  toAddOtherWarehousing() {
    let this_ = this
    wx.navigateTo({
      url: this.data.toAddOtherWarehousingUrl,
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {
          formMode: 'add',
          formType: 'shopping'
        })
      }
    })
  },


  /**
   * @desc : 左侧分类切换
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  changeSidebar(e) {
    console.log(e.detail)
    let index = e.detail
    let typeList = this.data.typeList
    this.setData({
      brandId: typeList[index].brandId
    })
    this.searchData()
  },
  /**
   * @desc : 查询
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  doSearch() {
    this.searchData()
  },

  /**
   * @desc : 设置查询参数
   * @author : 于继渤
   * @date : 2024/1/23 9:16
   */
  setSearchParams(params) {
    params.brandId = this.data.brandId //品牌id 
    params.flgZero = true
    return params
  },
  /**
   * @desc : 查询
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getData(params) {
    return this.excute(this.data.inventoryService, this.data.inventoryService.selectByCond, params);
  },

  /**
   * @desc : 处理返回数据
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  handleSearchData(tableData) {
    if (tableData && tableData.length > 0) {
      tableData.forEach(res => {
        // res.whId = app.globalData.user.defaultWhId
        // res.whName = app.globalData.user.defaultWhName
        if (res.skuImages && res.skuImages.length > 0) {
          res.skuImages.forEach(item => {
            item.url = config.image_url + item.path
          });
          res.imagesUrl = res.skuImages[0].url
        }
      })

      this.setData({
        tableData: tableData
      })
    }
  },

  /**
   * @desc : 加载数据
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  loadInit() {
    this.setData({
      billType: this.data.item
    })
    this.getDefChannel()
  },


  /**
   * @desc : 获取种类
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  getGoodsCategoryNoPage() {
    return this.excute(this.data.commonService, this.data.commonService.getGoodsCategoryNoPage, {}).then(res => { 
      this.setData({
        typeList: this.data.typeList.concat(res.data.data)
      })
    })
  },
  /**
   * @desc : 获取品牌
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  getGoodsBrandNoPage() {
    return this.excute(this.data.commonService, this.data.commonService.getGoodsBrandNoPage, {}).then(res => {
      console.log('getGoodsBrandNoPage', 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(e)
    let item = e.currentTarget.dataset.item
    item.itemQty = 1 //打开 popur 数量默认为1
    item['box'] = parseInt(item.itemQty / item.packBox)
    item['piece'] = Number(item.itemQty) % Number(item.packBox)
    item.packageBox = item['box'] + item.subUnitName + item['piece'] + item.unitName
    //选了辅助计量单位 正好 包装也有值 那么直接给出公式
    if (item.flgSubUnit && item.subUnitName) {
      item.calculationFormula = item.packBox + item.unitName + '= 1' + item.subUnitName
    }
    if (this.data.channelName) { //受默认渠道影响 取价格体系
      switch (this.data.channelName) {
        case '分销':
          item.priceSale = item.priceWholesale //批发价
          break;
        case '零售':
          item.priceSale = item.priceStandard //销售价
          break;
        default:
          item.priceSale = item.priceOther //其他价
          break;
      }
    } else { //没默认渠道 就取值销售价 
      item.priceSale = 0 //销售价 
    }
    if (this.data.gradeCode == 'STD') { //标准版
      item.priceSale = 0
    }
    item.sumPrice = item['itemQty'] * item.priceSale
    this.setData({
      dataItem: JSON.stringify(item),
      showPop: true,
    })
  },
  /**
   * @desc : 商品确认事件
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  editItems(e) {
    console.log('editItems', e)
    let choosedGoodsList = this.data.choosedGoodsList
    let item = e.detail.form
    item.priceSale = Number(item.priceSale)
    //校验销售价格输入是否符合规则
    //销售价格不能低于销售限价
    console.log(item.priceSale, item.priceLimited)
    if (item.flgPrice  && item.priceSale < item.priceLimited) {
      Dialog.alert({
        title: mixins.$t('messages'),
        message:  mixins.$t('priceLimited'),//销售价格不能低于销售限价
      }).then(() => {})
      return
    }
    choosedGoodsList.push(item)
    this.setData({
      choosedGoodsList: choosedGoodsList
    })
    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 += Number(res.sumPrice)
      sumQty += Number(res.itemQty)
    })
    contentList[0].content = sumAmt
    contentList[1].quantity = sumQty
    this.setData({
      contentList: contentList
    })
  },


  /**
   * @desc : 顶部切换
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  changeTag(e) {
    this.setData({
      active: e.detail.index
    })
  },
  selectedProduct(e) {
    this.setData({
      active: e.currentTarget.dataset.active
    })
  },

  /**
   * @desc : 结算按钮
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  submit() {
    //跳转销售订单
    let that = this
    let url = that.data.route.saleOrder.url
    // // 购物车-结算跳转页面；免费版跳转销售出库新建；专业版:：跳转销售订单新建  
    //  240611 恢复成开单
    // if (this.data.gradeCode == 'STD') { //标准版  
    //   url = that.data.route.salesOutbound.url
    // } else {
    //   url = that.data.route.saleOrder.url
    // }

    wx.navigateTo({
      url: url,
      success: function (res) {
        res.eventChannel.emit('params', {
          goodsList: that.data.choosedGoodsList,
          formMode:'add'
        })
        that.setData({ // 购物车点击结算清空已选
          choosedGoodsList:[]
        })
        that.calculateParameters()
      }
    })
  
  },

  onShow() {
    if (this.data.refreshByAdd) {
      // 执行查询方法
      this.searchData()
    }
  },

  /**
   * @desc : 初始化
   * @date : 2024/2/1 15:49
   * @author : 于继渤
   */
  onLoad() {
    this.getGoodsBrandNoPage()
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          gradeCode: app.globalData.company.gradeCode,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      }
    })
  },
})