<template>
  <view class="location-wrap">
    <view class="header-title">
      <view v-for="(item, index) in list" :key="index" :class="{ 'active-view': item.id === selectItem.id }"
            @tap="tabClick(item)">{{ item.name }}
      </view>
    </view>
    <view class="content-wrap">
      <view class="title">{{ $t('区域') }}</view>
      <view v-if="selectItem.children" class="location-wrap">
        <view>
          <view v-for="(val, i) in selectItem.children" :key="i" :class="{ 'area-item': val.selected }"
                @tap="areaClick(val)">{{ val.name || val.code }}
          </view>
        </view>
      </view>
      <view class="title">{{ $t('仓位') }}</view>
      <view v-if="selectAreaItem.positionList" class="position-group">
        <view v-for="(pos, k) in selectAreaItem.positionList" :key="k" class="position">
          <view v-if="!pos.children" class="position-item" :class="{ 'position-item-active': pos.selected }"
                @tap="locationClick(pos)">{{ pos.name || pos.code }}
          </view>
          <view v-else v-for="(loc, m) in pos.children" :key="m" class="position-item"
                :class="{ 'position-item-active': loc.selected }" @tap="locationChildClick(loc)">{{
              loc.name || loc.code
            }}
          </view>
        </view>
      </view>
      <view class="title">{{ $t('已选择') }}</view>
      <view>{{
          locationList.map(v => v.areaName + (v.locationName === null ? '' : v.locationName) || v.code || v.name).join(',')
        }}
      </view>
    </view>
    <view class="foot-btn">
      <button class="mini-btn" type="primary" size="mini" @tap="confirm">{{ $t('确认') }}</button>
      <button class="mini-btn" style="color: #007aff" size="mini" @tap="cancel">{{ $t('取消') }}</button>
    </view>
  </view>
</template>

<script>
import {getByWarehouseId} from '@/api/cons'

export default {
  name: 'cons-location',
  data() {
    return {
      consId: '',
      warehouseId: '', //null
      list: [],
      selectItem: {},
      selectAreaItem: {},
      locationList: [],
      callback: null, // 来源页面的会点方法名
      extra: null, // 来源页面回调需要的额外参数
    };
  },
  created() {
    // #ifdef H5
    // 从退场跳转过来选择储位的时候，由于是在unipopup的弹层操作，body的禁止了浮动溢出导致此页面无法滚动，所以需要做特殊处理
    if (document.getElementsByTagName('body')[0].style.overflow == 'hidden') {
      document.getElementsByTagName('body')[0].style.overflow = 'visible'
      this.overflowCorected = true
    }
    // #endif
  },
  beforeDestroy() {
    // #ifdef H5
    // 恢复created中的浮动溢出修正
    if (this.overflowCorected) {
      document.getElementsByTagName('body')[0].style.overflow = 'hidden'
    }
    // #endif
  },
  methods: {
    tabClick(item) {
      this.selectItem = item
      this.selectAreaItem = {}
    },
    areaClick(item) {
      item.selected = !item.selected
      this.selectAreaItem = item
      if (item.selected && Array.isArray(item.positionList)) {
        item.positionList?.forEach((value) => {
          if (value.children && Array.isArray(value.children)) {
            value.selected = false
            value.children?.forEach(val => {
              val.selected = false
            })
          }
        })
      }
      this.locationList = this.inputValue()
      this.$forceUpdate();
    },
    locationClick(item) {
      console.log('locationClick', item)
      item.selected = !item.selected
      this.selectAreaItem.selected = false
      let p = []
      this.selectAreaItem.positionList?.forEach((value, index) => {
        p.push(value)
        if (value.children && Array.isArray(value.children)) {
          p = p.concat(value.children)
        }
      })
      const t = p.filter(v => v.selected)
      this.selectAreaItem.selected = t.length <= 0;
      this.locationList = this.inputValue()
      this.$forceUpdate()
    },
    locationChildClick(item) {
      item.selected = !item.selected
      this.selectAreaItem.selected = false
      let p = []
      this.selectAreaItem.positionList?.forEach((value, index) => {
        p.push(value)
        if (value.children && Array.isArray(value.children)) {
          p = p.concat(value.children)
        }
      })
      const t = p.filter(v => v.selected)
      this.selectAreaItem.selected = t.length <= 0;
      this.locationList = this.inputValue()
      this.$forceUpdate();
    },
    isSelected(arrName, item) {
      return !!this[arrName].find(v => v.id === item.id)
    },
    inputValue() {
      const result = []
      this.list?.forEach(e => {
        // 仓库
        e.children?.forEach(f => {
          // 区域
          if (f.selected) result.push({
            consId: this.consId,
            wareId: f.pid,
            areaId: f.id,
            code: f.code
          })
          else if (f.positionList) f.positionList?.forEach(g => {
            // 位置
            if (g.selected) result.push({
              consId: this.consId,
              wareId: g.domainId,
              areaId: g.areaId,
              locationId: g.id,
              code: f.code + g.code,
            })
            else {
              Array.isArray(g.children) && g.children?.forEach(k => {
                // 子位置
                if (k.selected) result.push({
                  consId: this.consId,
                  wareId: k.domainId,
                  areaId: k.areaId,
                  locationId: k.id,
                  code: f.code + k.code
                })
              })
            }
          })
        })
      })
      return result
    },
    confirm() {
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      if (this.callback) {
        prevPage.$vm[this.callback](this.locationList, this.extra)
      } else {
        prevPage.$vm.orderLocationCreateReqVOList = this.locationList
      }
      uni.navigateBack();
    },
    cancel() {
      uni.navigateBack()
    }
  },
  onLoad: function (option) {
    uni.setNavigationBarTitle({
      title: this.$t('储位')
    })
    // 默认选择的库区和仓位
    let selectedArea = [], selectedLocation = []
    if ('locationList' in option) {
      this.locationList = JSON.parse(option.locationList) || [];
      this.locationList.forEach(item => {
        selectedArea.push(item.areaId)
        selectedLocation.push(item.locationId)
      })
    }

    if ('warehouseId' in option) {
      this.warehouseId = option.warehouseId;
      getByWarehouseId({warehouseId: this.warehouseId}).then(data => {
        this.list = data;
        this.selectItem = this.list[0]
        if (this.locationList.length > 0) {
          this.list?.forEach(item => {
            // 仓库
            item.children?.forEach(val => {
              // 储位信息有时候没有code字段，改用id判断
              if (selectedArea.indexOf(val.id) > -1) {
                val.selected = true
              }
              if (val.positionList) {
                val.positionList?.forEach(value => {
                  // 仓位
                  if (selectedLocation.indexOf(value.id) > -1) {
                    value.selected = true
                  }
                  value.children?.forEach(child => {
                    // 子仓位
                    if (selectedLocation.indexOf(value.id) > -1) {
                      value.selected = true
                    }
                  })
                })
              }
            })
          })
        }
      });
    }
    if ('consId' in option) {
      this.consId = option.consId;
    }

    if (option.callback) {
      this.callback = option.callback
    }
    if (option.extra) {
      this.extra = option.extra
    }
  }
};
</script>

<style lang="scss" scoped>
.location-wrap {
  .header-title {
    display: flex;
    justify-content: center;
    font-size: 16px;
    background: #2f4dae;
    padding: 0 0 24px;

    > view {
      padding: 12px;
      color: #fff;
    }

    .active-view {
      border-bottom: 2px solid #fff;
    }
  }

  .content-wrap {
    background: #fff;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    margin-top: -8px;
    padding: 0 16px;

    .title {
      line-height: 40px;
      font-size: 16px;
    }

    > .location-wrap {
      > view {
        display: flex;
        flex-wrap: wrap;

        > view {
          width: calc(50% - 8px);
          background: #eee;
          line-height: 40px;
          text-align: center;
          border-radius: 4px;
        }

        > .area-item {
          background: #4085e3;
          color: #fff;
        }

        > view:nth-of-type(n + 1) {
          margin-top: 8px;
        }

        > view:nth-of-type(2n) {
          margin-left: 8px;
        }
      }
    }
  }
}

.position-group {
  display: flex;
  background-color: #EFEFEF;
  border: 1px #EFEFEF solid;
  gap: 1px;
  min-height: 92px;
  flex-flow: wrap;
}

.position {
  width: calc(25% - 1px);
  height: 92px;
  display: flex;
  flex-direction: column;
  gap: 1px;
  user-select: none;
}

.position-item {
  width: 100%;
  background-color: #FFFFFF;
  flex: 1;
  cursor: pointer;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.position-item-active {
  background-color: #4085e3;
  color: white;
}
</style>
