<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-stock-update">
    <view class="tab">
      <view class="tab-item">
        {{ activeName==='warehouse' ? $t('cangKuKuCun') : $t('menDianKuCun') }}
      </view>
    </view>
    <view class="box">
      <view class="item-box">
        <view class="label-box">
          <view class="label">
            {{ activeName === 'warehouse' ? $t('cangKuMingCheng') : $t('menDianMingCheng') }}
          </view>
          <view
            v-if="activeName === 'station'"
            class="label"
          >
            {{ $t('zhuangTai') }}
          </view>
          <view class="label">
            {{ $t('kuCun') }}
          </view>
        </view>
        <view
          v-for="item in dataList"
          :key="item.id"
          class="input-box"
        >
          <view class="name">
            {{ activeName === 'warehouse' ? item.warehouseName : item.stationName }}
          </view>
          <view
            v-if="activeName === 'station'"
            class="name"
          >
            {{ [$t('guanBi'),$t('yingYe'),$t('weiGuiXiaXian'),$t('shenHeZhong'),$t('shenHeShiBai')][item.status] }}
          </view>
          <view class="input-val">
            <input
              v-model="item.stock"
              class="input"
              type="number"
              :min="0"
              :maxlength="7"
              :placeholder="$t('qingTianXie-0')"
              placeholder-class="placeholder-class"
              :disabled="showProd"
              :class="[showProd?'disabled-text':'']"
              @input="onStockInput(item)"
              @blur="onPushStockPointList(item)"
            >
          </view>
        </view>
      </view>
    </view>
    <common-btn
      :btn-config="prodManaBtnConfig"
      class="common-btn"
      @handle-click-more-btn="submitBtn"
    />
  </view>
</template>

<script setup>
const prodStore = useProdStore()
const prodManaBtnConfig = {
  isPlain: true,
  btnList: [
    {
      btnText: $t('queDing'),
      isPlain: false
    }
  ]
}

let index = null // 修改的索引
const isSpuMold = ref(false)
// const stockModeStr = ref('') // warehouse：仓库 station：门店
const showProd = ref(false)
onLoad((options) => {
  showProd.value = options.showProd === 'true'
  isSpuMold.value = prodStore.dataForm.mold || 0
  index = Number(options.indexValue)
  activeName.value = options.stockModeStr
  init()
})

onShow(() => {
  // 加载导航标题
  uni.setNavigationBarTitle({
    title: $t('kuCunSheZhi')
  })
})

onReachBottom(() => {
  if (pageData.value.pages > searchForm.current) {
    ++searchForm.current
    onGetPageData()
  }
})

let stockPointList = [] // 库存点及库存信息列表（提交时使用）
const visible = ref(false)
const activeName = ref('warehouse')
let specificationInfo = {} // 多库存传递的参数
/**
 * 初始化
 */
const init = () => {
  searchForm.current = 1
  searchForm.size = 20
  visible.value = true
  if (index === -1) {
    stockPointList = prodStore.stockPointList ? JSON.parse(JSON.stringify(prodStore.stockPointList)) : []
  } else {
    specificationInfo = uni.getStorageSync('bbcMsSpecificationInfo') || {}
    const sku = specificationInfo.dataForm?.[index]
    stockPointList = sku.stockPointList ? JSON.parse(JSON.stringify(sku.stockPointList)) : []
  }
  onGetPageData(true)
}

let tempSearchForm = null // 保存上次点击查询的请求条件
// 头部搜索表单
const searchForm = reactive({
  size: 10,
  current: 1,
  stockMode: 2
})
const pageData = ref({
  total: 0,
  pages: 0
})
const dataList = ref([])
const pageLoading = ref(true)
let typeIdStr = '' // 当前请求的字段键名
// 获取数据列表
const onGetPageData = (newData = false) => {
  uni.showLoading()
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  } else {
    tempSearchForm.current = searchForm.current
    tempSearchForm.size = searchForm.size
  }
  let url
  if (activeName.value === 'warehouse') {
    url = '/m/warehouse/page'
    typeIdStr = 'warehouseId'
  } else {
    typeIdStr = 'stationId'
    url = '/admin/station/page'
  }
  http.request({
    url,
    method: 'get',
    data: tempSearchForm
  }).then(({ data }) => {
    uni.hideLoading()
    pageData.value.pages = data.pages
    pageData.value.total = data.total
    const list = cidyArray(data.records, stockPointList)
    if (tempSearchForm.current === 1) {
      dataList.value = list
    } else {
      dataList.value = dataList.value.concat(list)
    }
    pageLoading.value = false
  }).catch(() => {
    uni.hideLoading()
    pageLoading.value = false
  })
}

/**
 * 整理回显库存数量
 * @param {Array} pointList 请求来的仓库/门店列表（id为[typeIdStr]字段）
 * @param {Array} stockList 存储点库存数列表（id为'stockPointType'字段）
 */
const cidyArray = (pointList, stockList) => {
  // 如果未有存储点设置库存，则直接返回整理的数据
  const nowStockPointType = activeName.value === 'warehouse' ? 1 : 2
  if (!(stockList && stockList.length)) {
    return pointList.map((item) => {
      return {
        ...item,
        stock: 0, // 库存
        stockPointId: item[typeIdStr], // 存储点ID
        stockPointType: nowStockPointType, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
        type: activeName.value === 'warehouse' ? item.type : 1, // 仓库需要返回仓库类型（0 默认仓库 1 非默认仓库）
        stockMode: activeName.value === 'station' ? item.stockMode : undefined
      }
    })
  }
  const list = []
  for (let i = 0; i < pointList.length; i++) {
    let flag = false
    for (let j = 0; j < stockList.length; j++) {
      if (pointList[i][typeIdStr] === stockList[j].stockPointId && stockList[j].stockPointType === nowStockPointType) {
        list.push({
          ...pointList[i],
          stock: stockList[j].stock, // 库存
          stockPointId: pointList[i][typeIdStr], // 存储点ID
          stockPointType: nowStockPointType, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
          type: activeName.value === 'warehouse' ? pointList[i].type : 1, // 仓库需要返回仓库类型（0 默认仓库 1 非默认仓库）
          stockMode: activeName.value === 'station' ? pointList[i].stockMode : undefined,
          skuId: stockList[j].skuId,
          status: activeName.value === 'station' ? pointList[i].status : undefined
        })
        flag = true
        break
      }
    }
    // 当前循环的仓库/门店未设置库存
    if (!flag) {
      list.push({
        ...pointList[i],
        stock: 0, // 库存
        stockPointId: pointList[i][typeIdStr], // 存储点ID
        stockPointType: nowStockPointType, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
        type: activeName.value === 'warehouse' ? pointList[i].type : 1, // 仓库需要返回仓库类型（0 默认仓库 1 非默认仓库）
        stockMode: activeName.value === 'station' ? pointList[i].stockMode : undefined
      })
    }
  }
  return list
}
// 将设置的库存数存储起来
const onPushStockPointList = (row) => {
  row.stock = row.stock ? row.stock : 0
  const nowStockPointType = activeName.value === 'warehouse' ? 1 : 2
  if (!(stockPointList && stockPointList.length)) {
    stockPointList.push({
      stock: row.stock, // 库存
      stockPointId: row.stockPointId, // 存储点ID
      stockPointType: row.stockPointType, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
      type: activeName.value === 'warehouse' ? row.type : 1, // 仓库需要返回仓库类型（0 默认仓库 1 非默认仓库）
      stockMode: activeName.value === 'station' ? row.stockMode : undefined,
      status: activeName.value === 'station' ? row.status : undefined,
      sameCityDelivery: activeName.value === 'station' ? row.sameCityDelivery : undefined,
      selfPickup: activeName.value === 'station' ? row.selfPickup : undefined
    })
    return
  }
  let flag = false
  for (let i = 0; i < stockPointList.length; i++) {
    if (stockPointList[i].stockPointId === row[typeIdStr] && stockPointList[i].stockPointType === nowStockPointType) {
      // 当前修改的库存存在原库存，则直接修改
      if (row.skuId) {
        // 记录库存的改变
        if (stockPointList[i].changeStock) {
          // 如果存在库存改变（非首次修改），则计算 原库存（stockPointList[i].stock） 与 修改库存（row.stock） 的差值再与记录的changeStock相加
          const diff = row.stock - (stockPointList[i].stock || 0)
          stockPointList[i].changeStock += diff
        } else {
          // 如果不存在库存改变（首次修改）且oldStock不为空，则修改的库存为 原库存（stockPointList[i].stock） 与 修改库存（row.stock） 的差值
          stockPointList[i].changeStock = row.stock - (stockPointList[i].stock || 0)
        }
      } else if (!row.stock) {
        // 不存在库存的新增库存点则移除
        stockPointList.splice(i, 1)
        break
      }
      stockPointList[i].stock = row.stock || 0
      flag = true
      break
    }
  }
  if (!flag && row.stock > 0) {
    // 当前修改的库存未有记录，则新建一条
    stockPointList.push({
      stock: row.stock,
      stockPointId: row.stockPointId,
      stockPointType: row.stockPointType,
      type: activeName.value === 'warehouse' ? row.type : 1, // 仓库需要返回仓库类型（0 默认仓库 1 非默认仓库）
      stockMode: activeName.value === 'station' ? row.stockMode : undefined,
      status: activeName.value === 'station' ? row.status : undefined,
      sameCityDelivery: activeName.value === 'station' ? row.sameCityDelivery : undefined,
      selfPickup: activeName.value === 'station' ? row.selfPickup : undefined
    })
  }
}

const onStockInput = (row) => {
  if (row.stock) {
    row.stock = row.stock.toString().replace(/[^\d]/g, '')
    row.stock = row.stock > 9999999 ? 9999999 : Number(row.stock)
  }
}

const submitBtn = () => {
  const { warehouseStock, stationStock, stocks } = prodStore.calcSkuStock(stockPointList)
  if (index === -1) {
    prodStore.stockPointList = stockPointList
    prodStore.dataForm.warehouseStock = warehouseStock
    prodStore.dataForm.stationStock = stationStock
    prodStore.dataForm.totalStocks = stocks
  } else {
    specificationInfo.dataForm[index].stockPointList = stockPointList
    specificationInfo.dataForm[index].warehouseStock = warehouseStock
    specificationInfo.dataForm[index].stationStock = stationStock
    specificationInfo.dataForm[index].stocks = stocks
    uni.setStorageSync('bbcMsSpecificationInfo', specificationInfo)
  }
  uni.navigateBack() // 返回之前的页面
}

</script>

<style lang="scss" scoped>
.page-stock-update {
  background-color: #eee;
  min-height: 100vh;
  .disabled-text {
    width: 70%;
    padding: 0 20rpx;
    font-size: 32rpx;
    color: grey;
  }
  .tab {
    display: flex;
    justify-content: flex-start;
    padding: 24rpx 0;
    background: #fff;
    font-size: 26rpx;
    position: fixed;
    width: 100%;
    z-index: 1;
    top: 0;
    .tab-item {
      display: block;
      min-width: 33.33%;
      text-align: center;
      flex-grow: 1;
    }
  }

  .box {
    padding-bottom: 110rpx;
    padding-top: 106rpx;

    .item-box {
      font-size: 26rpx;
      padding: 0 20rpx;
      padding-bottom: 20rpx;
      background-color: #fff;
      border-radius: 5rpx;
      .label-box,
      .input-box {
        display: flex;
        align-items: center;
        min-height: 100rpx;
        border-bottom: 1px solid #ebeef5;
      }
      .label {
        font-size: 28rpx;
        font-weight: bold;
        font-family: PingFang SC Bold;
        color: #333333;
        margin: 0 8rpx;
        flex: 1;
      }
      .name,
      .input-val {
        flex: 1;
      }
      .name{
        margin: 0 8rpx;
        line-break: anywhere;
      }
      .input-val{
        margin: 0 8rpx;
      }
    }
  }

  .common-btn {
    position: fixed;
    bottom: 0;
    background-color: #fff;
  }
}
</style>
