<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="库存搜索" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入商品名称/商品规格"
            clearable
            style="width: 260px"
            @keyup.enter.native="handleQuery"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleQuery" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="stockList" :empty-text="emptyTableText">
        <el-table-column label="商品信息" align="left" min-width="260">
          <template slot-scope="scope">
            <div class="goods-cell">
              <image-preview v-if="scope.row.mainPic" :src="scope.row.mainPic" :width="44" :height="44" />
              <span class="goods-name">{{ scope.row.goodsName || '—' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" align="center" width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ specText(scope.row.specText) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="可用库存" align="center" width="100">
          <template slot-scope="scope">
            <span :class="{ 'stock-zero': scope.row.stock === 0 }">{{ scope.row.stock != null ? scope.row.stock : '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成本" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.cost != null ? scope.row.cost : '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="openLogs(scope.row)" v-hasPermi="['agri:seller:stock:query:list']">出入库明细</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 出入库明细弹窗 -->
    <el-dialog
      :title="logsDialogTitle"
      :visible.sync="logsOpen"
      width="900px"
      append-to-body
      @close="resetLogs"
    >
      <div v-if="currentRow" class="logs-goods-brief">
        <image-preview v-if="currentRow.mainPic" :src="currentRow.mainPic" :width="48" :height="48" />
        <div class="brief-text">
          <div class="brief-name">{{ currentRow.goodsName || '—' }}</div>
          <div class="brief-spec">规格：{{ specText(currentRow.specText) }}</div>
          <div class="brief-stock">当前可用库存：{{ currentRow.stock != null ? currentRow.stock : '—' }}</div>
        </div>
      </div>
      <el-table border v-loading="logsLoading" :data="logList" max-height="420" :empty-text="logsEmptyText">
        <el-table-column label="商品名称" align="left" min-width="200" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="goods-cell">
              <image-preview v-if="currentRow && currentRow.mainPic" :src="currentRow.mainPic" :width="36" :height="36" />
              <span>{{ scope.row.goodsName || '—' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="出入库类型" align="center" min-width="130" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.ioTypeText || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" align="center" width="110" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ specText(scope.row.specText) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出入库数量" align="center" width="110">
          <template slot-scope="scope">
            <span :class="ioQtyClass(scope.row.ioQty)">{{ formatIoQty(scope.row.ioQty) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出入库时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.ioTime) || '—' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerStockQuery,
  listSellerStockQueryLogs
} from "@/api/agri/seller/stock/query"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

export default {
  name: "AgriSellerStockQuery",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      stockList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined
      },
      logsOpen: false,
      logsLoading: false,
      logList: [],
      currentRow: null
    }
  },
  computed: {
    hasSearchFilter() {
      return !!this.queryParams.keyword
    },
    emptyTableText() {
      return this.hasSearchFilter ? "未找到符合条件的库存记录" : "暂无库存数据"
    },
    logsDialogTitle() {
      return "出入库明细"
    },
    logsEmptyText() {
      return "暂无出入库记录"
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    specText(text) {
      const val = text ? String(text).trim() : ""
      return val && val !== "—" ? val : "—"
    },
    formatIoQty(qty) {
      if (qty == null) {
        return "—"
      }
      return qty > 0 ? `+${qty}` : String(qty)
    },
    ioQtyClass(qty) {
      if (qty == null || qty === 0) {
        return ""
      }
      return qty > 0 ? "qty-in" : "qty-out"
    },
    initPage() {
      this.loadShopContext().then(() => {
        this.getList()
      }).catch(() => {
        this.getList()
      })
    },
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    getList() {
      this.loading = true
      listSellerStockQuery(this.queryParams).then(response => {
        this.stockList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.pageNum = 1
      this.getList()
    },
    openLogs(row) {
      this.currentRow = row
      this.logsOpen = true
      this.loadLogs(row.goodsId)
    },
    loadLogs(goodsId) {
      if (!goodsId) {
        return
      }
      this.logsLoading = true
      listSellerStockQueryLogs(goodsId).then(response => {
        this.logList = response.data || []
        this.logsLoading = false
      }).catch(() => {
        this.logList = []
        this.logsLoading = false
      })
    },
    resetLogs() {
      this.currentRow = null
      this.logList = []
      this.logsLoading = false
    }
  }
}
</script>

<style scoped lang="scss">
.mb8 {
  margin-bottom: 8px;
}
.goods-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}
.goods-name {
  flex: 1;
  min-width: 0;
  line-height: 1.4;
}
.stock-zero {
  color: #F56C6C;
}
.logs-goods-brief {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  background: #fafafa;
  border-radius: 4px;
}
.brief-text {
  flex: 1;
  min-width: 0;
}
.brief-name {
  font-weight: 500;
  color: #303133;
  line-height: 1.4;
}
.brief-spec,
.brief-stock {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}
.qty-in {
  color: #67C23A;
  font-weight: 500;
}
.qty-out {
  color: #F56C6C;
  font-weight: 500;
}
</style>
