
import { sys_group_query, queryPlanDispatchGroup } from '../api.js';

export default {
  data() {
    this.cacheChildren = {}
    return {
      t1_checkedList: [],
      GROUP_DISPATCH_PLAN: [],
      t1_expRecord: null,
      changeExpandedRowKeys: [],
      t1_expandedRowKeys: [],
      mainSelectData: [],


      vxeMaxHeight: 400,
      treeConfig: { toggleMethod: this.toggleMethod, reserve: false, lazy: true, transform: true, rowField: 'id', parentField: 'pId', hasChild: 'hasChild', loadMethod: this.loadChildrenMethod }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.vxeMaxHeight = this.$refs.t1_table.$el.parentNode.offsetHeight
    })


  },
  computed: {

  },
  methods: {
    toggleMethod({ expanded, row, column, columnIndex }) {
      if (expanded) {
        this.GROUP_DISPATCH_PLAN = this.options?.GROUP_DISPATCH_PLAN.filter((item) => !row.selectValue.includes(item.value));
        this.t1_visible = true;
        this.t1_expRecord = () => {
          let reloadTreeExpand = this.$refs.t1_table.reloadTreeExpand
          this.cacheChildren[row.id] = row
          return reloadTreeExpand(row)
        };
        return false
      } else {
        this.t1_expRecord = null
        return true
      }

    },
    rowClassName({ row, rowIndex, $rowIndex }) {
      //     return !this.isDisabled(row);
      return row.disabled && 'row--checked'
    },
    sumNum(list, field) {
      let count = 0

      list.forEach(item => {
        let n = item[field]
        if (n < 0) {
          n = 0
        }
        count += Number(n)
      }, this)

      return Math.round((count + Number.EPSILON) * 1000) / 1000
    },
    colspanMethod({ $rowIndex, column, columnIndex, $columnIndex, _columnIndex, data }) {
      if (_columnIndex === 0) {
        return { colspan: 0 };
      } else if (_columnIndex === 1) {
        return { colspan: 2 }
      }
    },



    footerMethod({ columns, data }) {
      const means = []
      const sums = []
      const others = []

      columns.forEach((column, columnIndex) => {
        if (columnIndex === 1) {
          // means.push('平均')
          sums.push('合计',)
          // others.push('其他')
        } else {
          let sumCell = null
          switch (column.property) {
            case 'consigneeQty':
            case 'oderQty':
            case 'carrierUnitQty':
            case 'totalWeight':
            case 'totalVolume':
            case 'planTotalVehicleQty':
            case 'totalPcs':
            case 'transfiniteQty':
            case 'totalPlanBillQty':
            case 'totalShipbillQty':
              sumCell = this.sumNum(data, column.property)
              break
          }
          sums.push(sumCell)
        }
      })

      // 返回一个二维数组的表尾合计
      return [sums]
    },
    checVisibleMethod({ row }) {
      //是否允许勾选的方法，该方法，的返回值用来决定这一行的 checkbox 是否显示
      return row.oderQty > 0

    },
    checCheckboxkMethod({ row }) {

      //是否允许勾选的方法，该方法的返回值用来决定这一行的 checkbox 是否可以勾选
      if (row.oderQty <= 0) {

        return false
      }
      return !row.disabled ? true : false


      // if (this.actiovOrderItme) {
      //   // row--checked
      //   const { uuid } = this.actiovOrderItme
      //   return !uuid.includes(row.id)
      // }
      // return true
    },
    // checCheckboxkMethod2({ row }) {
    //   return !this.isDisabled(row);

    // },

    removeGroupRow(row) {
      row.checked = false;
      row.disabled = false
      let obj = this.actiovOrderItme
      row.hasChild=true
      if (obj) {
        let form = this.getForm(obj.key);

        let mainSelectData = this.getCheckboxRecords()
        this.$emit('selectData', mainSelectData);
        if (!mainSelectData.length) {
          form.resetFields();
          obj.uuData = {};
          obj.itemList = []
          obj.planDetailIdsArr =[]
          obj.planDetailIds = ''


        } else {
          delete obj.uuData[row.key]
          let planDetailIds = row.planDetailIds?.split(',') ?? []
          obj.planDetailIdsArr = new Set(obj.planDetailIdsArr)
          planDetailIds.forEach(planDetailIds => {
            obj.planDetailIdsArr.delete(planDetailIds)
          });

          obj.planDetailIdsArr = Array.from(obj.planDetailIdsArr)
          obj.itemList = []
          this.cache.addOderItem(false);


        }



        let setRowExpand = this.$refs.t1_table.setRowExpand
        setRowExpand(row, false);

        this.actiovOrderItme = obj
        delete this.actiovOrderItme.uuData[row.id]
      }

    },
    getCheckboxRecords() {
      return this.$refs.t1_table.getCheckboxRecords()

    },
    updateFooter() {
      return this.$refs.t1_table.updateFooter()

    },
    remove(item) {
      return this.$refs.t1_table.remove(item);

    },
    checkboxChange({ checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) {
      this.mainSelectData = this.getCheckboxRecords()?.filter(item => !item.disabled)
      this.$emit('selectData', this.mainSelectData)
    },

    loadChildrenMethod({ row }) {
      let record = row
      return new Promise(resolve => {

        if (this.t1_visible && this.t1_expRecord) {
          this.t1_visible = false
          return queryPlanDispatchGroup({
            groupDimensionList: this.t1_checkedList,
            planDetailIds: record.planDetailIds
          }).then(res => {
            this.t1_expRecord = null;

            if (res.success) {
              res.data = res.data.groupQueryDTOS;
              if (res.data.length === 0) {

                this.$exception({
                  message: '没有查询到分组数据！',
                });

                if (!row.children.length) {
                  row.hasChild = false
                }
                return resolve()

              }

              this.t1_expandedRowKeys = this.changeExpandedRowKeys;
              res.data.forEach((item) => {
                item.selectValue = [...row.selectValue, ...this.t1_checkedList]
                item.oderQty = item.loadingPlanDetailQty;

                if (!record.rootId) {
                  item.rootId = record.id;
                } else {
                  item.rootId = record.rootId;
                }
                item.pId = record.id;
                let i = item.selectValue.length >= this.options.GROUP_DISPATCH_PLAN.length;
                if (!i) {
                  item.hasChild = true;
                } else {
                  item.hasChild = false;
                }
              }, this);
              this.t1_checkedList = []
              this.cacheChildren[row.id] = row
              return resolve(res.data)
            } else {
              this.$exception(res)
              return resolve()
            }
          })


        }
      })


    },
    visibleMethod({ row, type }) {
      let xTree = this.$refs.xTree
      if (type === 'body') {
        this.bodyMenus.forEach(list => {
          list.forEach(item => {
            if (['clearLoaded', 'reloadNodes'].includes(item.code)) {
              item.disabled = !row.hasChild || !xTree.isTreeExpandLoaded(row)
            } else if (['expand', 'contract'].includes(item.code)) {
              if (row.hasChild) {
                let isExpand = xTree.isTreeExpandByRow(row)
                item.disabled = ['expand'].includes(item.code) ? isExpand : !isExpand
              } else {
                item.disabled = true
              }
            }
          })
        })
      }
      return true
    },

    customOderQty(text, record) {

      let { done } = this.cache
      let { loadingPlanDetailQty,planDetailIds } = record
      let oderQty = loadingPlanDetailQty
      if (oderQty == 2) {

      }
      let idArr = planDetailIds?.split(',') ?? null;
      let _disabledIds = this.disabledIds.concat(done);
      console.log(_disabledIds)

      if (idArr) {
        for (let i = 0; i < idArr.length; i++) {
          if (_disabledIds.includes(idArr[i])) {
            oderQty--
          }
        }
        if (!record.pId) {
          record.oderQty = oderQty
        }
      }

      if (oderQty < 0) {
        oderQty = 0
      }

      record.oderQty = oderQty
      if (oderQty <= 0) {
        record.hasChild=false
      } else {
        record.hasChild=true

      }
      return oderQty
    },


    hideModal() {
      this.t1_expRecord?.()

    },



  }
}