<template>
  <uni-popup ref="popup" background-color="#fff" :is-mask-click="false">
    <view class="pop-container">
      <!-- <uni-nav-bar fixed="true" statusBar="true" :title="cargoSpace">
      </uni-nav-bar> -->
      <view class="tools-box">
        <uni-easyinput
          prefixIcon="search"
          v-model="searchVal"
          placeholder="编码、名称"
        ></uni-easyinput>
      </view>
      <view class="dialog-title">
        <text class="text-success">货位{{ cargoSpace }}</text>
        <view class="all">
          <div>选中调拨 {{ selected }}/{{ tableData.length }} 项</div>
        </view>
      </view>
      <view class="scroll-wrapper">
        <!-- <AssetsCard
        v-for="item in showTable"
        :key="item.produceId"
        :item="item"
      /> -->
        <view class="card-list" v-for="(item, index) in showTable" :key="index">
          <view class="title">
            {{ item.assetName }}（{{ item.assetCode }}）
          </view>
          <view class="card-row">
            <view
              class="card-col"
              v-for="(itm, index) in tableHeader(item.assetType)"
              :key="index"
            >
              <text class="label">{{ itm.label }}</text>
              <template v-if="itm.formatter">{{
                itm.formatter(item)
              }}</template>
              <template v-else>{{ item[itm.prop] }}</template></view
            >
            <view class="card-col">
              <text class="label">类型</text
              >{{ getDictValue('物品类型', item.assetType) }}</view
            >
            <view class="card-col">
              <text class="label">库存数量</text>{{ item.stocker
              }}{{ item.isUnpack ? item.unit : item.minPackUnit }}</view
            >
            <view class="card-col">
              <text class="label">可调拨数量</text>{{ item.max
              }}{{ item.isUnpack ? item.unit : item.minPackUnit }}</view
            >
          </view>
          <view class="card-footer">
            <view style="margin-top: -40rpx">调拨数量</view>
            <u-number-box
              v-if="item.takeStockPattern"
              v-model="item.amount"
              :min="0"
              :max="+item.max"
            ></u-number-box>
            <text class="text-primary num" @click="handleDetail(item)" v-else>{{
              (item.detailReqList && item.detailReqList.length) || 0 || '选择'
            }}</text>
          </view>
        </view>
        <u-empty text="暂无数据" v-if="!showTable.length"> </u-empty>
      </view>
      <view class="footer">
        <u-button size="large" @click="cancel">返回</u-button>
        <u-button size="large" type="success" @click="confirm">提交</u-button>
      </view>
    </view>
    <DetailDialog
      ref="detailRef"
      :assetsList="assetsList"
      :preAssetsList="preAssetsList"
    />
  </uni-popup>
</template>

<script>
import DetailDialog from './DetailDialog'
import AssetsCard from './AssetsCard'
import { tableHeader } from '../../common'
import { get } from '@/utils/api.js'
import dictMixins from '@/mixins/dictMixins'
export default {
  components: { AssetsCard, DetailDialog },
  mixins: [dictMixins],
  props: {
    assetsList: {
      type: Array,
      default: () => []
    },
    preAssetsList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      tableData: [],
      cargoSpace: '',
      searchVal: '',
      selectAll: false
    }
  },
  created () {
    this.requestDict('物品类型')
  },
  computed: {
    showTable () {
      return this.tableData.filter(item => {
        if (this.searchVal) {
          if (
            String(assetName).indexOf(this.searchVal) != -1 ||
            String(assetCode).indexOf(this.searchVal) != -1
          ) {
            return true
          }
          return false
        }
        return true
      })
    },
    selected () {
      // let sum = 0
      // this.tableData.forEach(item => {
      //   if (item.takeStockPattern) {
      //     sum += +item.amount
      //   } else {
      //     sum += item.detailReqList?.length || 0
      //   }
      // })
      return this.tableData.filter(item => {
        if (item.takeStockPattern) {
          return !!+item.amount
        } else {
          return !!item.detailReqList?.length
        }
      }).length
    }
  },
  methods: {
    tableHeader,
    async open (warehouse) {
      this.cargoSpace =
        warehouse.warehouseName +
        '-' +
        warehouse.areaName +
        '-' +
        warehouse.shelfCode +
        '-' +
        warehouse.cargoSpaceCode
      this.warehouse = warehouse
      this.$refs.popup.open('right')

      const res = await get(
        this.apiUrl +
          `/conventionalStockTransfer/warehouse/getGoodsDetail/${warehouse.cargoSpaceId}`
      )
      if (res?.success) {
        this.tableData = res.data.map(i => {
          // 唯一id 添加相同判断
          i.curId = warehouse.cargoSpaceId + i.assetCode

          let preAmount = 0
          let tempAmount = 0

          // 预调入数量需展示，但不可修改，展示剩余可调拨
          const index1 = this.preAssetsList.findIndex(
            item => item.curId === i.curId
          )
          if (index1 > -1) {
            preAmount = this.preAssetsList[index1].amount
          }

          i.stocker = +i.amount

          i.amount = 0

          const index = this.assetsList.findIndex(
            item => item.curId === i.curId
          )
          if (index > -1) {
            tempAmount = this.assetsList[index].amount
          }

          i.max = i.stocker - preAmount - tempAmount

          delete i.id
          return i
        })
      }
    },
    handleAllChange (e) {
      this.tableData.map(item => {
        item.checked = !!e.detail.value.length
      })
    },
    handleDetail (item) {
      this.$refs.detailRef.open(item, this.warehouse.cargoSpaceId, res => {
        this.$set(
          item,
          'detailReqList',
          res.filter(i => i.checked)
        )
      })
    },
    confirm () {
      const selection = this.tableData.filter(item => {
        Object.assign(item, this.warehouse)
        if (!item.takeStockPattern) {
          item.amount = item.detailReqList?.length
        }
        return item.amount > 0
      })
      if (!selection.length) {
        uni.showToast({
          title: '请至少选择一条数据',
          icon: 'none'
        })
        return
      }

      this.$emit('success', selection)
      this.cancel()
    },
    cancel () {
      this.$refs.popup.close()
      this.$emit('cancel')
      this.tableData = []
    }
  }
}
</script>
<style lang="scss" scoped>
view {
  box-sizing: border-box;
}

.pop-container {
  padding-top: $tab-height;
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  .scroll-wrapper {
    flex: 1;
    overflow: auto;
    padding-bottom: 220rpx;
  }
}

.card-list {
  font-size: 28rpx;

  padding: 10rpx 20rpx;
  .title {
    margin-bottom: 20rpx;
    font-size: 32rpx;
    font-weight: bold;
  }
  .card-row {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0rpx 20rpx;
    .card-col {
      width: 50%;
      margin-bottom: 20rpx;
      .label {
        margin-right: 20rpx;
      }
    }
  }
  .card-footer {
    display: flex;
    // justify-content: flex-end;
    flex-direction: column;
    align-items: flex-end;
    .num {
      margin-bottom: 5rpx;
      display: inline-block;
      border: 1rpx solid $j-primary-green;
      padding: 8rpx 20rpx;
      border-radius: 10rpx;
    }

    /deep/.u-number-box {
      align-items: stretch;
      height: 60rpx;

      .u-number-box__input {
        width: 80rpx !important;
        height: auto !important;
      }
      .u-number-box__minus,
      .u-number-box__plus {
        height: auto !important;
      }
    }
  }
}
::v-deep.scroll-wrapper {
  // height: 50vh;
  overflow: auto;

  .assets-cell {
    & + .assets-cell {
      margin-top: 10px;
    }
  }
}

.tools-box {
  padding: 12rpx;
  .all {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12rpx 0 0;
  }
}
.dialog-title {
  width: 100vw;
  text-align: left;
  display: flex;
  justify-content: space-between;
  position: relative;
  text-align: center;
  font-size: 28rpx;
  padding: 20rpx;
  // background-color: $j-primary-border-green;

  span {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
}
</style>
