<template>
  <div class="component-stock-upload">
    <el-dialog
      v-model="visible"
      :show-close="false"
      width="650"
      @closed="onCloseDialog"
    >
      <div class="title">
        <el-tabs
          v-model="activeName"
          class="tabs"
          @tab-change="onActiveChange"
        >
          <el-tab-pane
            label="仓库库存"
            name="warehouse"
          />
        </el-tabs>
        <div
          class="close-btn"
          @click="visible = false"
        >
          <el-icon><Close /></el-icon>
        </div>
      </div>
      <div class="content">
        <el-table
          v-loading="pageLoading"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            prop="warehouseName"
            label="仓库名称"
          />
          <el-table-column
            prop="stock"
            label="商品库存"
          >
            <template #default="scope">
              <el-input
                v-model.number="scope.row.stock"
                :min="0"
                maxlength="7"
                class="stock-number"
                @input="onStockInput(scope.row)"
                @change="onPushStockPointList(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <pagination
        v-show="pageData.total > 0"
        v-model:page="searchForm.pageNum"
        v-model:limit="searchForm.pageSize"
        style="text-align: right"
        :total="pageData.total"
        @pagination="onChangePage"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="visible = false"
          >
            {{ $t('table.cancel') }}
          </el-button>
          <el-button
            type="primary"
            @click="onSubmit()"
          >
            {{ $t('table.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import * as api from '@/api/stock/stock.js'

const emit = defineEmits(['setStockCallback', 'close'])

let stockPointList = [] // 库存点及库存信息列表（提交时使用）
let index = null // 修改的索引
const visible = ref(false)
const activeName = ref('warehouse')
const isSpuMold = ref(false)
/**
 * 初始化
 * @param {object} sku sku信息
 * @param {number} indexValue 索引值（回调中返回给父组件修改数据用,-1则表示无）
 * @param {boolean} mold 1虚拟商品 0实物商品
 */
const init = (sku, indexValue = -1, mold = 0) => {
  activeName.value = 'warehouse'
  searchForm.pageNum = 1
  searchForm.pageSize = 10
  visible.value = true
  index = indexValue
  isSpuMold.value = mold
  stockPointList = sku.stockPointList ? JSON.parse(JSON.stringify(sku.stockPointList)) : []
  onGetPageData(true)
}

let tempSearchForm = null // 保存上次点击查询的请求条件
// 头部搜索表单
const searchForm = reactive({
  pageSize: 10,
  pageNum: 1
})
const pageData = ref({
  total: 0,
  pages: 0
})
const dataList = ref([])
const pageLoading = ref(true)
// 获取数据列表
const onGetPageData = (newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  } else {
    tempSearchForm.pageNum = searchForm.pageNum
    tempSearchForm.pageSize = searchForm.pageSize
  }
  api.getPageList(tempSearchForm).then(res => {
    pageData.value.pages = res.pages
    pageData.value.total = res.total
    dataList.value = cidyArray(res.list, stockPointList)
    pageLoading.value = false
  }).catch(() => {
    pageLoading.value = false
  })
}

/**
 * 整理回显库存数量
 * @param {Array} pointList 请求来的仓库列表
 * @param {Array} stockList 存储点库存数列表（id为'stockPointType'字段）
 */
const cidyArray = (pointList, stockList) => {
  // 如果未有存储点设置库存，则直接返回整理的数据
  if (!(stockList && stockList.length)) {
    return pointList.map((item) => {
      return {
        ...item,
        stock: 0, // 库存
        stockPointId: item.warehouseId, // 存储点ID
        stockPointType: 1, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
        type: item.type // 仓库类型（0 默认仓库 1 非默认仓库）
      }
    })
  }
  const list = []
  for (let i = 0; i < pointList.length; i++) {
    let flag = false
    for (let j = 0; j < stockList.length; j++) {
      if (pointList[i].warehouseId === stockList[j].stockPointId) {
        list.push({
          ...pointList[i],
          stock: stockList[j].stock, // 库存
          stockPointId: pointList[i].warehouseId, // 存储点ID
          stockPointType: 1, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
          type: pointList[i].type, // 仓库类型（0 默认仓库 1 非默认仓库）
          skuId: stockList[j].skuId
        })
        flag = true
        break
      }
    }
    // 当前循环的仓库/门店未设置库存
    if (!flag) {
      list.push({
        ...pointList[i],
        stock: 0, // 库存
        stockPointId: pointList[i].warehouseId, // 存储点ID
        stockPointType: 1, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
        type: pointList[i].type
      })
    }
  }
  return list
}
// 将设置的库存数存储起来
const onPushStockPointList = (row) => {
  /* if (!(stockPointList && stockPointList.length)) {
    stockPointList.push({
      stock: row.stock || 0, // 库存
      stockPointId: row.stockPointId, // 存储点ID
      stockPointType: row.stockPointType, // 存储点类型（当前请求的列表为仓库则类型为1，请求的列表为门店则类型为2）
      type: row.type
    })
    return
  } */
  let flag = false
  for (let i = 0; i < stockPointList.length; i++) {
    if (stockPointList[i].stockPointId === row.warehouseId) {
      // 当前修改的库存存在原库存，则直接修改
      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 {
          // 如果不存在库存改变（首次修改），则修改的库存为 原库存（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: row.type
    })
  }
}

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

const onChangePage = () => {
  onGetPageData()
}

const onActiveChange = () => {
  onGetPageData(true)
}

const onSubmit = () => {
  const sum = stockPointList.reduce((total, item) => {
    return total + item.stock
  }, 0)
  visible.value = false
  emit('setStockCallback', stockPointList, sum, index)
}

const onCloseDialog = () => {
  emit('close')
}

defineExpose({
  init,
  visible
})
</script>

<style lang="scss" scoped>
.component-stock-upload {
  :deep(.el-dialog__header){
    display: none;
  }
  :deep(.el-dialog__body) {
    padding: 0;
  }
  .title {
    position: relative;
    :deep(.el-tabs__nav-scroll) {
      padding: 10px 0 0 20px;
    }
    .close-btn {
      font-size: 18px;
      color: #909399;
      position: absolute;
      top: 10px;
      right: 10px;
      &:hover {
        color: #155bd4;
        cursor: pointer;
      }
    }
  }
  .content {
    padding: 20px;
    .stock-number {
      width: 100px;
    }
  }
  .dialog-footer {
    text-align: center;
  }
}
</style>
