/*******************************************************************************
 * Copyright(c) 2024 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：表单-（开单）
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		周兴		  	2024-1-30    1.00		   	  新建
 *******************************************************************************/
const common = require('@/utils/common');
const util = require('@/utils/util.js')
const Constants = require('@/utils/Constants');
const chooseLocation = requirePlugin('chooseLocation');
const config = require('@/config/config.js')
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 区域
    cardList: {
      type: Array,
      value: []
    },
    // 内容
    contentObj: {
      type: Object,
    },
    // 开单组件类型(sale,pur)
    type: {
      type: String,
    },
     // 外部传入控制的选商品所有标识的集合
    controlFlags:{
      type: Object, // controlFlags 是一个对象  
      value: {}, // 默认值是一个空对象  
    },
    // 类型 sale; basic
    popType: {
      type: String,
      value: 'sale'
    },
    // 路由名称
    routeObjName: {
      type: String
    },
    titleTagCol: {
      type: String,
      value: 'titleTag'
    },
    titleCol: {
      type: String,
      value: 'title'
    },
    iconCol: {
      type: String,
      value: 'iconThumPath'
    },
    // 价格列
    priceCol: {
      type: String,
      value: 'priceSale'
    },
    // 数量列
    quantityCol: {
      type: String,
      value: 'itemQuantity'
    },
    // 数量列
    descCol: {
      type: String,
      value: 'desc'
    },
    // pop底部描述列
    subCol: {
      type: String,
      value: 'desc'
    },
    // 价格标题
    priceTitle: {
      type: String,
    },
    sumStandardCol: {
      type: String,
      value: 'sumStandard'
    },
    discountStandardCol: {
      type: String,
      value: 'discountStandard'
    },
    sumAmountCol: {
      type: String,
      value: 'sumAmount'
    },
    sumAmountColFlag:{
      type: Boolean,
      value: true
    },
    // 可用收款列
    canUseCollectCol: {
      type: String,
      value: 'canUseCollect'
    },
    // 收款列
    useCollectCol: {
      type: String,
      value: 'useCollect'
    },
    // 弹框的内容
    popContent: {
      type: Array,
    },
    popupTopObj:{
      type: Array,
    },
    // 是否只读
    readonly: {
      type: Boolean,
    },
    titpsFlag:{  //商品右上角信息
      type: Boolean,
      value:false
    },
    titpsItemColorFlagKey:{
      type: String,
    },
    titpsLabel:{
      type: String
    },
    stepperFlag: {//步进器 标识
      type: Boolean,
    },
    quantityMin: { //步进器 最小值
      type: String,
    },
    quantityMax: {
      type: String
    },
    showPopFlag: { //弹窗标识  true 不弹窗
      type: Boolean,
    },
    staff: {
      type: String,  //主从业务员
    },
    org: {
      type: String, //主从业务部门
    },
    saleStaffAndOrgFlag: {
      type: Boolean,
      value: true
    },
    cardContentList: { //商品明细下的选单
      type: Array,
    },
    quantityRedCol: { //例  可售量显示字段 key
      type: String,
    },
    quantityRedColFlagKey: { // 显示隐藏整行的key   商品明细控制
      type: String
    },
    quantityRedTitle: {  //右侧显示文字
      type: String,
      value: '可售量：'
    },
    goodsTagText: { //自定义tag
      type: String,
      value: ''
    },
    // 表名，用于上传附件
    table: {
      type: String,
    },
    // 删除时是否进行校验
    delValidFlag: {
      type: Boolean,
    },
    // 对象取值列
    objCol: {
      type: String
    },
    // 对象列名
    objLabel: {
      type: String
    },
    // 对象类型(客户customer；供应商supplier)
    objType: {
      type: String
    },
    // 对象标题
    objTitle: {
      type: String,
      value: 'cusName'
    },
    // 对象副标题
    objSubTitle: {
      type: String,
      value: 'cusPhone'
    },
    // 金额标题
    amountTitle: {
      type: String,
      value: '应收金额'
    },
    // 金额列
    amountCol: {
      type: String,
      value: 'receivableResidue'
    },
    // 对象Id列
    objIdCol: {
      type: String,
      value: 'cusId'
    },
    chooseText: {
      type: String,
    },

    goodsTagColor: { //标签颜色
      type: String,
    },
    // 结果集
    value: {
      type: String,
      observer: function (newVal) {
        if (newVal) {
          this.setData({
            form: JSON.parse(newVal) || {}
          })
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 是否显示pop
    show: false,
    showDate: false,
    showPop: false,
    $t: app.globalData.lang,
    routeUrl: app.globalData['routeUrl'],
    item: null,
    index: null,
    dataItem: null,
    dataIndex: null,
    card: null,
    key: null,
    // 下拉类型
    dropType: null,
    dropCode: null,
    dropName: null,
    itemName: 'goodsList',
    deleteName: 'deleteList',
    selectGoodsUrl: null,
    chooseVisible: true,  // 用于联动控制选商品按钮
    maxSize: Constants.uploadFileConfig.maxSize,
    // popContent:
    //   [{ code: 'quantity', type: 'step', title: '数量', required: true }, { code: 'pricePromotion', type: 'number', title: '销售价格', required: true }, { code: 'warehouseId', name: 'warehouseName', type: 'drop', required: true, dropType: 'warehouse' , required: true}, { code: 'color', type: 'str', title: '批次号' , required: true}, { code: 'giftFlag', type: 'checkbox', title: '赠品标识' }],
    form: {}
  },
  lifetimes: {
    attached: function () {
      // 销售订单
      if (this.data.type == Constants.billType.sale ||  this.data.type == Constants.billType.saleOut ||
        this.data.type == Constants.billType.pur
        ||
        this.data.type == Constants.billType.out || this.data.type == Constants.billType.purReturn) {
        this.setData({
          selectGoodsUrl: '/package-base-select/pages/select-goods/select-goods'
        })
      }
      // 处理contentObj
      this.handleContentObj();
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  pageLifetimes: {
    /**
     * @desc :  生命周期函数--监听页面显示
     * @author : 周兴
     * @date : 2024/2/19 12:16
     */
    show: function () {
      // 设置地址
      this.setAddress();
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * @desc   : 处理ContentObj数据
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    handleContentObj(card) {
      let contentObj = this.data.contentObj;
      let cardList = this.data.cardList;
      let form = this.data.form;
      let items = form[this.data.itemName]
      if (cardList && cardList.length > 0 && contentObj) {
        if (card) {
          cardList = cardList.filter(it => it.name == card.name);
        }
        cardList.forEach((it, index) => {
          // 不是明细
          if (it.name != 'items') {
            if (it.displayNum && contentObj[it.name].length > it.displayNum) {
              for (let i = it.displayNum; i < contentObj[it.name].length; i++) {
                // 如果折叠就把超过的部分隐藏
                if (it.showMore) {
                  contentObj[it.name][i].show = true;
                } else {
                  contentObj[it.name][i].show = false;
                }
              }
            }
          } else {
            // 商品明细
            if (it.displayNum && items && items.length > it.displayNum) {
              for (let i = it.displayNum; i < items.length; i++) {
                // 如果折叠就把超过的部分隐藏//todo
                // console.log('it',it.showMore,items[i]);
                if (it.showMore) {
                  items[i].show = true;
                } else {
                  items[i].show = false;
                }
              }
            }
          }
        })
        this.setData({
          contentObj: contentObj,
          form: form,
          value: JSON.stringify(form)
        })
      }
    },
    /**
     * @desc   : 展开收缩
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    expand(e) {
      let card = e.currentTarget.dataset.card
      let index = e.currentTarget.dataset.index
      let cardList = this.data.cardList
      if (cardList[index]) {
        cardList[index].showMore = !cardList[index].showMore
      }
      this.setData({
        cardList: cardList
      })
      // 处理contentObj
      this.handleContentObj(card);
    },
    /**
     * @desc   : 打开Pop进行修改
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    openChoosedItemInfo(e) {
      if (this.data.showPopFlag) {
        return;
      }
      let ds = e.currentTarget.dataset;
      this.setData({
        dataIndex: ds.index,
        dataItem: JSON.stringify(ds.item),
        showPop: true,
      })

      this.triggerEvent("openChoosedItemInfo", {
        item: ds.item,
        index: ds.index
      })
    },
    /**
     * @desc   : 关闭Pop后修改数据
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    editItems(data) {
      let form = this.data.form;
      let itemName = this.data.itemName;
      if (form[itemName]) {
        form[itemName][this.data.dataIndex] = data.detail.form;
      }
      //计算金额
      if (this.data.type == Constants.billType.sale) {
        this.setGoodsAmount()
      }
      if( this.data.type == Constants.billType.saleOut){
        this.setGoodsOutAmount()
      }
      this.setData({
        form: form,
        value: JSON.stringify(form)
      })
      // 外露关闭pop后事件
      this.triggerEvent("editItems", {
        data: form
      })
    },
    /**
    * @desc :商品明细数量加减事件
    * @date : 2024/2/1 15:49
    * @author : 于继渤
    */
    onChangeStepper(e) {
      this.triggerEvent("onStepper", {
        index: e.currentTarget.dataset.index,
        item: e.detail
      })
    },
    /**
     * @desc   : 打开下拉/跳转选择页面
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    open(e) {
      // 只读 
      if (this.data.readonly) {
        return;
      }
      let item = e.currentTarget.dataset;
      // 明细 只读240320
      if (item.item.readonlyItem) {
        return;
      }
      let that = this
      if (item.item.type == 'drop') {
        this.setData({
          show: true,
          dropCode: item.key,
          dropName: item.name,
          dropType: item.type,
          index: item.index,
          card: item.card
        })
      } else if (item.item.type == 'mutidrop') {
        this.setData({
          mutishow: true,
          dropCode: item.key,
          dropName: item.name,
          dropType: item.type,
          index: item.index,
          card: item.card
        })
      } else if (item.item.type == 'choose') {
        that.setData({
          changeObj: item.item.changeObj,
        })
        // 跳转链接
        if (item.item.urlKey) {
          this.setData({
            index: item.index,
            card: item.card
          })
          let route = this.data.routeUrl[this.data.routeObjName][item.item.urlKey]
          let url = route.url
          if (url) {
            wx.navigateTo({
              url: url,
              events: {
                // 回调后
                bindData: function (data) {
                  //处理明细 给明细赋值  例如选仓库回调赋值
                  if (item.flag) {
                    let form = that.data.form
                    form[that.data.itemName][item.index][item.item.code] = data.data.id
                    form[that.data.itemName][item.index][item.item.name] = data.data.name
                    that.setData({
                      form: form
                    })
                    // 如果有校验信息就清除掉
                    let card = that.data.card;
                    let index = that.data.index;
                    let contentObj = that.data.contentObj;
                    if (card && contentObj[card][index]?.errMsg) {
                      contentObj[card][index].errMsg = undefined;
                      that.setData({
                        contentObj: contentObj
                      })
                    }
                  }  
                  that.triggerEvent("chooseData", { code: item.key, data: data, index: item.index })
                  // 如果需要联动控制选商品按钮
                  if (item.item.controlChooseFlag) {
                    that.setData({
                      chooseVisible: false
                    })
                  }
                }
              },
              success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                console.log('rrre', route.type);
                res.eventChannel.emit('params', { item: item.item, route: route })
              }
            })
          }
        }
      } else if (item.item.type == 'selectIcon') {
        // 跳转链接
        if (item.item.urlKey) {
          let url = this.data.routeUrl[this.data.routeObjName][item.item.urlKey].url
          // TODO
          // url = '/package-base6-select/pages/select-customers/select-customers'
          if (url) {
            wx.navigateTo({
              url: url,
              events: {
                // 回调后
                bindData: function (data) {
                  that.triggerEvent("chooseData", { code: item.key, data: data })
                  // 如果需要联动控制选商品按钮
                  if (item.item.controlChooseFlag) {
                    that.setData({
                      chooseVisible: false
                    })
                  }
                }
              },
              success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit('params', { data: item.item.urlKeyParam })
              }
            })
          }
        }
      }
    },
    /**
     * @desc   : 打开选择主从业务员/业务部门组件
     * @author : 周兴
     * @date   : 2024/2/20 11:46
     */
    openMulti(e) {
      if (this.data.readonly) {
        return;
      }
      let type = e.currentTarget.dataset.type
      let _this = this
      // 选择主从业务员
      if (type == 'staff') {
        wx.navigateTo({
          url: '/package-sales/pages/choose-sale-staff/choose-sale-staff',
          events: {
            // 回调后
            bindData: function (data) {
              _this.triggerEvent("chooseData", { code: type, data: data })
            }
          },
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('params', { data: 'test' })
          }
        })
        // 选择主从业务部门
      } else if (type == 'org') {
        wx.navigateTo({
          url: '/package-sales/pages/choose-sale-org/choose-sale-org',
          events: {
            // 回调后
            bindData: function (data) {
              _this.triggerEvent("chooseData", { code: type, data: data })
            }
          },
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('params', { data: 'test' })
          }
        })
      }
    },
    /**
     * @desc   : 非空校验
     * @author : 周兴
     * @date   : 2024/2/20 11:46
     */
    validData() {
      let flag = true;
      let cardList = this.data.cardList;
      if (!cardList || cardList.length == 0) {
        return flag;
      }
      let form = this.data.form;
      let contentObj = this.data.contentObj;
      cardList.forEach(card => {
        if (contentObj[card.name]) {
          contentObj[card.name].forEach(item => {
            let title = this.$t(item.title ? item.title : item.code)
            // 如果必须输入，就要进行判断
            if (item.required && !form[item.code]) {
              item.errMsg = title + '不为空'
              flag = false;
            }
          })
        }
      })
      this.setData({
        contentObj: contentObj
      })
      return flag;
    },
    /**
     * @desc   : 展开页签
     * @author : 周兴
     * @date   : 2024/2/20 11:46
     */
    expandCard(e) {
      let cardList = this.data.cardList
      let index = e.currentTarget.dataset.index
      if (cardList[index]) {
        // 收缩的时候需要展示信息
        let expand = cardList[index].expand
        cardList[index].info = undefined
        if (expand) {
          let form = this.data.form
          let infoCols = e.currentTarget.dataset.item.infoCols
          if (infoCols && infoCols.length > 0) {
            let info = ''
            infoCols.forEach(it => {
              if (form[it]) {
                info += form[it] + '/'
              }
            })
            if (info.length > 0) {
              info = info.substring(0, info.length - 1);
              cardList[index].info = info
            }
          }
        }
        cardList[index].expand = !expand
        this.setData({
          cardList: cardList
        })
      }
    },
    /**
   * @desc   : 打开日期pop
   * @author : 周兴
   * @date   : 2024/1/26 11:46
   */
    openDatePop(e) {
      // 只读
      if (this.data.readonly) {
        return;
      }
      let item = e.currentTarget.dataset;
      this.setData({
        showDate: true,
        index: item.index,
        key: item.key,
        card: item.card
      })
    },
    /**
     * @desc   : 关闭日期pop
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    cancelDatePop() {
      this.setData({
        showDate: false
      })
    },
    /**
     * @desc   : 选择日期
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    chooseDate(e) {
      let form = this.data.form;
      let index = this.data.index;
      let card = this.data.card;
      let code = this.data.key;
      form[code + '_time'] = e.detail
      form[code] = util.toDateStr(e.detail);
      let contentObj = this.data.contentObj;
      if (card && contentObj[card][index]?.errMsg && e.detail) {
        contentObj[card][index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj,
        showDate: false
      })
    },
    /**
     * @desc   : 打开选择商品明细界面
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    openChooseItems(e) {
      console.log("openChooseItems", e);
      if (this.data.selectGoodsUrl) {
        let _this = this
        wx.navigateTo({
          url: this.data.selectGoodsUrl,
          events: {
            // 回调后
            bindData: function (data) {
              console.log('data', data);
              // 设置商品明细controlChooseFlag
              _this.setGoods({ data: data });
            }
          },
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('params', { choose: true, item: _this.data.type,popContent:_this.data.popContent ,controlFlags:_this.data.controlFlags})
          }
        })
      }
    },
    /**
     * @desc   : 选择数据
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    chooseData(e) {
      let contentObj = this.data.contentObj;
      let form = this.data.form
      if (e.detail.ids) {
        form[this.data.dropCode + 's'] = e.detail.ids;
        form[this.data.dropName + 's'] = e.detail.names;
      } else {
        form[this.data.dropCode] = e.detail.value;
        form[this.data.dropName] = e.detail.text;
      }
      let card = this.data.card;
      // 选择后清空校验提示信息
      if (card && contentObj[card][this.data.index]?.errMsg && e.detail) {
        contentObj[card][this.data.index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
      // 如果处理id，name还需要赋值其他，需要在页面事件中自行处理
      this.triggerEvent("chooseData", { code: this.data.dropCode, item: e.detail.item })
    },
    /**
     * @desc   : 修改输入框的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    changeField(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let item = ds.item
      let form = this.data.form
      form[key] = e.detail
      let contentObj = this.data.contentObj;
      // 输入值后清空校验提示信息
      if (item.errMsg && e.detail) {
        contentObj[ds.card][ds.index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
      this.triggerEvent("changeField", { code: ds.key })
    },
    /**
     * @desc   : 清空输入框的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearField(e) {
      console.log('eee', e);
      let ds = e.currentTarget.dataset
      let key = ds.key
      let form = this.data.form
      form[key] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
      // 如果要清除其他值，需要调用
      this.triggerEvent("clear", { code: ds.key })
    },
    /**
     * @desc   : 清空地址的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearAddress(e) {
      let form = this.data.form
      form['address'] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
      // 如果要清除其他值，需要调用
      this.triggerEvent("clear", { code: ds.key })
    },
    /**
     * @desc   : 清空日期的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearDate(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let form = this.data.form
      form[key] = undefined
      form[key + '_time'] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
    },
    /**
     * @desc   : 清空选单的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearChoose(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let name = ds.name
      let item = ds.item
      // 明细 只读只读240320
      if (item.readonlyItem) {
        return;
      }
      let form = this.data.form
      form[key] = undefined
      form[name] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
      // 如果需要联动控制选商品按钮
      if (item && item.controlChooseFlag) {
        this.setData({
          chooseVisible: true
        })
      }
      // 如果要清除其他值，需要调用
      this.triggerEvent("clear", { code: ds.key })
    },
    /**
     * @desc   : 修改数值输入框的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    changeNumberField(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let item = ds.item
      let form = this.data.form
      form[key] = e.detail.value
      let contentObj = this.data.contentObj;
      // 输入值后清空校验提示信息
      if (item.errMsg && e.detail) {
        contentObj[ds.card][ds.index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
    },
    /**
    * @desc   : 修改数值输入框的值 离焦事件
    * @author : 于继渤
    * @date   : 2024/2/2 11:46
    */
    changeNumberBlur(e) {
      this.triggerEvent("changeNumberBlur", e.detail)
    },
    /**
     * @desc   : 修改电话的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    changePhone(e) {
      let ds = e.currentTarget.dataset;
      let key = ds.key;
      let index = ds.index;
      let card = ds.card;
      let form = this.data.form
      form[key] = e.detail.detail
      let contentObj = this.data.contentObj;
      if (card && contentObj[card][index]?.errMsg && e.detail.detail) {
        contentObj[card][index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
    },
    /**
     * @desc   : 给电话赋值错误信息
     * @author : 周兴
     * @date   : 2024/2/20 11:46
     */
    changePhoneblur(e) {
      let ds = e.currentTarget.dataset
      let errMsg = e.detail.errMsg;
      let card = ds.card;
      let index = ds.index;
      let contentObj = this.data.contentObj;
      if (errMsg && card && contentObj[card][index]) {
        contentObj[card][index].errMsg = errMsg;
        this.setData({
          errMsg: errMsg
        })
      }
      this.triggerEvent("changePhoneblur",ds)
    },
    /**
     * @desc   : 打开选择对象的页面
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    openObjPop() {
      let _this = this
      // 选择客户
      if (this.data.objType == Constants.objType.customer) {
        wx.navigateTo({
          url: '/package-base-select/pages/select-customers/select-customers',
          events: {
            // 回调后
            bindData: function (data) {
              console.log('rr', data);
              let form = _this.data.form
              let objIdCol = _this.data.objIdCol;
              // 赋值对象Id
              if (objIdCol && data[objIdCol]) {
                form[objIdCol] = data[objIdCol]
              }
              console.log('ddd', form);
              form.objInfo = data;
              _this.setData({
                form: form,
                value: JSON.stringify(form)
              })
              _this.triggerEvent("chooseObjTypeData", { data: form, })
            }
          },
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('params', { data: 'test' })
          }
        })
        // 选择供应商
      } else if (this.data.objType == Constants.objType.supplier) {
        wx.navigateTo({
          // url: '/package-base-select/pages/select-suppliers/select-suppliers',
          url: '/package-base-select/pages/select-data/select-data',
          events: {
            // 回调后
            bindData: function (data) {
              let dataitem = data.data.item
              let form = _this.data.form
              let objIdCol = _this.data.objIdCol;
              // 赋值对象Id
              if (objIdCol && dataitem[objIdCol]) {
                form[objIdCol] = dataitem[objIdCol]
              }
              form.objInfo = dataitem;
              _this.setData({
                form: form,
                value: JSON.stringify(form)
              })
              _this.triggerEvent("chooseObjTypeData", { data: form, })
            }
          },
          success: function (res) {
            // 通过eventChannel向被打开页面传送数据
            let item = {}
            console.log('re', _this.data.routeObjName, _this.data.routeUrl);
            let route = _this.data.routeUrl[_this.data.routeObjName];
            res.eventChannel.emit('params', { item: item, route: route['chooseSupplier'] })
          }
        })
      }
    },
    /**
     * @desc : 小程序地图调用
     * @author : 周兴
     * @date : 2024/2/18 18:16
     */
    onClickWxchartAddress(e) {
      // 只读
      if (this.data.readonly) {
        return;
      }
      // 跳转新建地图实例
      common.onClickWxchartAddress();
      let item = e.currentTarget.dataset;
      this.setData({
        index: item.index,
        card: item.card
      })
    },
    /**
     * @desc   : 改变选择框内容
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    onChange(e) {
      // 只读
      if (this.data.readonly) {
        return;
      }
      let key = e.currentTarget.dataset.key
      let checkFlag = e.currentTarget.dataset.value
      let form = this.data.form
      form[key] = !checkFlag
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
      console.log('form', this.data.form);
    },
    /**
     * @desc : 设置地址
     * @author : 周兴
     * @date : 2024/1/19
     */
    setAddress() {
      const location = chooseLocation.getLocation();
      // console.log('loc', location);
      let form = this.data.form
      if (location) {
        form['address'] = location;
        form['addressName'] = location.name;
        form['addressFull'] = form['addressFull'] ? form['addressFull'] : location.address + location.name;
        form['addressGcj02'] = { latitude: location.latitude, longitude: location.longitude };
        form['addressArea'] = {
          province: location.province,
          city: location.city,
          district: location.district == undefined || !location.district ? location.city : location.district
        }
        // 如果有校验信息就清除掉
        let card = this.data.card;
        let index = this.data.index;
        let contentObj = this.data.contentObj;
        if (card && contentObj[card][index]?.errMsg) {
          contentObj[card][index].errMsg = undefined;
          this.setData({
            contentObj: contentObj
          })
        }
      }
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
    },

    /**
     * @desc : 设置商品
     * @author : 周兴
     * @date : 2024/1/19
     */
    setGoods(e) {
      if (e.data) {
        let form = this.data.form
        let goodsList = form[this.data.itemName] || []
        e.data.choosedGoodsList.forEach(it => {
          goodsList.push(it)
        })
        form[this.data.itemName] = goodsList
        // 设置商品总单的金额信息 
        if (this.data.type == Constants.billType.sale) {
          this.setGoodsAmount(e.data);
        }
        if( this.data.type == Constants.billType.saleOut){ //销售出库
          this.setGoodsOutList(e.data)
        }
        if (this.data.type == Constants.billType.purReturn) { //采购退货
          this.setReturnGoodsAmount(e.data);
        }
        if (this.data.type == Constants.billType.pur) {
          // this.setPurGoodsAmount(e.data);
        }
        this.setData({
          form: form,
          value: JSON.stringify(form)
        })
        // 设置是否进行收缩
        let card = this.data.cardList.filter(it => it.name == 'items');
        this.handleContentObj(card[0])
        // 外露setGoods方法
        this.triggerEvent("setGoods", { data: goodsList })
      }
    },
    /**
     * @desc : 删除商品明细
     * @author : 周兴
     * @date : 2024/2/22 18:16
     */
    onCloseDel(e) {
      let deleteFlag = true;
      let item = e.currentTarget.dataset.item
      // 判断删除前是否需要判断
      if (this.data.delValidFlag) {
        // 行不允许删除
        if (item.deleteFlag == false) {
          deleteFlag = false;
        }
      }
      // 不允许删除给出提示信息
      if (!deleteFlag) {
        util.showToast(item.message ? item.message : '不满足删除条件');
      } else {
        const { instance } = e.detail;
        let index = e.currentTarget.dataset.index
        // 删除明细
        this.delItem(index);
        instance.close();
      }
    },
    /**
     * @desc : 删除商品明细
     * @author : 周兴
     * @date : 2024/2/22 18:16
     */
    delItem(index) {
      let form = this.data.form
      let goodsList = form[this.data.itemName] || []
      let deleteList = form[this.data.deleteName] || []
      // 把删除的数据记录下来
      if (goodsList[index]) {
        deleteList.push(goodsList[index])
      }
      goodsList.splice(index, 1)
      form[this.data.itemName] = goodsList
      form[this.data.deleteName] = deleteList
      this.setData({
        form: form,
        value: JSON.stringify(form)
      })
      //计算
      if (this.data.type == Constants.billType.sale) {
        this.setGoodsAmount(goodsList);
      }
      if( this.data.type == Constants.billType.saleOut){
        this.setGoodsOutAmount()
      }
      // 外露setGoods方法
      this.triggerEvent("delItem", { data: goodsList })
    },
    /**
     * @desc : 设置商品明细金额相关信息  采购订单专用
     * @author : 周兴
     * @date : 2024/1/19
     */
    setPurGoodsAmount(data) {
      let form = this.data.form
      let cardList_ = this.data.cardList
      let goodsList = form[this.data.itemName]
      let sumAmountCol = this.data.sumAmountCol

      goodsList.forEach(element => {  //循环出商品总共价格
        element.itemAmt = element.pricePurchase
        element.intoingAmt = element.pricePurchase
        element.intoingQty = element.itemQty
        element.pricePur = element.pricePurchase
        element.priceInto = element.pricePurchase
        element.sumAmountCol = element.pricePurchase * element.itemQty
      })
      cardList_.forEach(card => {  //循环出商品总共价格
        if (card.name === 'items') {
          card.itemAmt = goodsList ? goodsList.sum("pricePurchase") : 0
          card.itemQty = goodsList ? goodsList.sum("itemQty") : 0
          card.intoAmt = 0
          card.intoQty = 0
          card[sumAmountCol] = goodsList ? goodsList.sum("sumAmountCol") : 0
          //合计金额
        }
      })
      form[this.data.itemName] = goodsList
      this.setData({
        cardList: cardList_,
        form: form,
        value: JSON.stringify(form)
      })
    },
    /**
     * @desc : 设置商品明细金额相关信息 TODO 
     * @author : 周兴
     * @date : 2024/1/19
     */
    setGoodsAmount(data) {
      let cardList = this.data.cardList
      let form = this.data.form
      let index = cardList.findIndex(it => it.name == 'items');
      if (form.goodsList && form.goodsList.length > 0) {
        let sumStandard = Number(0)
        let sumAmount = Number(0)
        let sumQuantity = Number(0)
        form.goodsList.forEach(item => {
          //标价合计 =  商品标价 x  商品数量
          item.priceStd = item.priceStd ? item.priceStd : (item.priceStandard ? item.priceStandard : 0)//标价
          item.amtStd = Number(item.priceStd * item.itemQty) //合计标价金额
          item.priceSale = item.priceSale ? item.priceSale : item.priceStandard
          item.itemAmt = item.priceSale * item.itemQty //商品金额
          item.priceDiscount = item.priceStd ?  Number((item.priceSale / item.priceStd) * 100).toFixed(2) : 100//售价折扣
          sumQuantity += item.itemQty //数量
          sumAmount += item.priceSale * item.itemQty //没有售价默认取标价
          console.log('111', item.priceStandard)
          console.log('111',  item.priceStd)
          sumStandard += (item.priceStd ? item.priceStd : item.priceStandard) * item.itemQty
        })
        //标价合计
        cardList[index].sumStandard = sumStandard
        //销售折扣 (合计金额/标价合计)
        cardList[index].saleDiscount = sumStandard ?  Number((sumAmount / sumStandard) * 100).toFixed(2) : 100
        //合计金额
        cardList[index].sumAmount = sumAmount
        //TODO   需要获取当前客户可用预存
        cardList[index].canUseCollect = 0  //可用
        cardList[index].useCollect = 0  //使用
        form.sumStandard = sumStandard
        form.saleDiscount = cardList[index].saleDiscount
        form.sumAmount = sumAmount
        form.canUseCollect = 0
        form.useCollect = 0
        form.sumQuantity = sumQuantity
      } else {
        cardList[index].sumStandard = 0
        cardList[index].saleDiscount = 0
        cardList[index].sumAmount = 0
        cardList[index].canUseCollect = 0
        cardList[index].useCollect = 0

        form.sumStandard = 0
        form.saleDiscount = 0
        form.sumAmount = 0
        form.canUseCollect = 0
        form.useCollect = 0
      }

      this.setData({
        cardList: cardList,
        form: form
      })
    },
  /**
     * @desc : 设置商品明细金额相关信息 销售出库
     * @author : 于继渤
     * @date : 2024/1/19
     */
    setGoodsOutAmount(){
      let cardList = this.data.cardList
      let form = this.data.form
      let index = cardList.findIndex(it => it.name == 'items');
      if (form.goodsList && form.goodsList.length > 0) {
        let sumStandard = Number(0)
        let sumAmount = Number(0)
        let sumQuantity = Number(0)
        form.goodsList.forEach(item => {
          //标价合计 =  商品标价 x  商品数量
          item.priceStd = item.priceStandard//标价
          item.amtStd = Number(item.priceStd * item.itemQty) 
          item.outAmt = item.priceOut * item.outQty
          item.priceDiscount = item.priceStd ?  Number((item.priceOut / item.priceStd) * 100).toFixed(2) : 100//售价折扣
          sumQuantity += item.outQty //数量
          sumAmount += item.priceOut * item.outQty //没有售价默认取标价
          sumStandard += (item.priceStd ? item.priceStd : item.priceStandard) * item.outQty
        })
        //标价合计
        cardList[index].sumStandard = sumStandard
        //销售折扣 (合计金额/标价合计)
        cardList[index].saleDiscount = Number((sumAmount / sumStandard) * 100).toFixed(2)
        //合计金额
        cardList[index].sumAmount = sumAmount
        //TODO   需要获取当前客户可用预存
        form.saleDiscount = cardList[index].saleDiscount
        form.sumAmount = sumAmount
        form.sumQuantity = sumQuantity
        form.outAmt = sumAmount
        form.outQty = sumQuantity
      } 

      this.setData({
        cardList: cardList,
        form: form
      })
    },

  /**
     * @desc :  销售出库设置选品参数
     * @author : 于继渤
     * @date : 2024/1/19
     */
    setGoodsOutList(data){
      let form = this.data.form
      if (form.goodsList && form.goodsList.length > 0) {
        form.goodsList.forEach(item => {
          item.priceOut = item.priceStandard
          item.outQty = item.itemQty 
          item.outAmt = item.priceOut * item.itemQty
          delete item['priceLimited']
          delete item['pricePurchase']
          delete item['priceWholesale']
        })
      }
      this.setData({
        form: form
      })
      this.setGoodsOutAmount()
    },

    /**
  * @desc : 设置商品明细金额相关信息 TODO 
  * @author : 周兴
  * @date : 2024/1/19
  */
    setReturnGoodsAmount(data) {
      let cardList = this.data.cardList
      let form = this.data.form
      let index = cardList.findIndex(it => it.name == 'items');
      if (form.goodsList && form.goodsList.length > 0) {
        let sumReturnAmt = Number(0) //合计金额
        let sumReturnQty = Number(0)
        form.goodsList.forEach(item => {
          item.priceReturn = item.priceStandard * -1
          item.priceInto = item.priceStandard 
          item.itemAmt = Number(item.priceReturn * item.itemQty)
          item.itemQtyMax = -1
          item.itemQtyMin = item.usableQty * -1
          // sumReturnAmt += item.priceReturn * item.itemQty
          // sumReturnQty += item.itemQty
          item.itemQty = item.itemQty * -1
        })
        // form.sumReturnQty = sumReturnQty
        // form.sumReturnAmt = sumReturnAmt
        // cardList[index].sumReturnAmt = sumReturnAmt
      }
      console.log('form', form)
      this.setData({
        cardList: cardList,
        form: form
      })
    },
    /**
     * @desc : 上传附件超出大小
     * @author : 周兴
     * @date : 2024/3/27 16:16
     */
    overSize(e) {
      util.showToast('文件超出' + Constants.uploadFileConfig.maxSizeMB);
    },
    /**
     * @desc : 上传附件
     * @author : 周兴
     * @date : 2024/3/27 16:16
     */
    afterRead(e) {
      // this.setData({
      //     uploadFileFlag:true
      // })
      const _this = this;
      const {
        file
      } = e.detail;
      // 配置存放的文件夹 公司code - 表名 - 年月 -- 日
      let folder = app.globalData.company.cpCode + '/' + this.data.table + '/' + new Date().toYearMonth2() + '/' + new Date().toDay()
      let url = config.upload_url;
      url = url.replace('mdm-server', 'mdm-server' + '-' + app.globalData.company.svcCode.replace('_', '-'))
      file.forEach(res => {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        wx.uploadFile({
          url: url,
          filePath: res.path,
          name: 'file',
          formData: {
            'folder': folder
          },
          header: {
            'Authorization': 'Bearer ' + app.globalData.token
          },
          success(res) {
            let data = JSON.parse(res.data)
            if (data.code === 200) {
              _this.setData({
                uploadFileFlag: false
              })
              let form = _this.data.form
              let annexPaths = form['annexPaths'] || []
              data.data.url = config.image_url + data.data.path
              annexPaths.push(data.data)
              form.annexPaths = annexPaths;
              _this.setData({
                form: form,
                value: JSON.stringify(form)
              })
              console.log('ff', _this.data.form);
            }
          },
        })
      })
    },
    customersChoose() {
      this.triggerEvent("customersChoose", {})
    },
    /**
     * @desc : 获取语言的方法
     * @author : 周兴
     * @date : 2024/1/19
     */
    $t(name) {
      if (this.data.$t[name]) {
        return this.data.$t[name];
      } else {
        return name;
      }
    },
  },
})
