<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="goodsList" :empty-text="emptyTableText">
        <el-table-column label="商品名称" align="left" min-width="150">
          <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" min-width="250" :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="140" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="openAdjust(scope.row)" v-hasPermi="['agri:seller:stock:adjust:edit']">调整</el-button>
            <el-button size="mini" type="text" @click="openRecords(scope.row)" v-hasPermi="['agri:seller:stock:adjust: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="库存调整" :visible.sync="adjustOpen" width="560px" append-to-body @close="resetAdjust">
      <div v-if="currentRow" class="adjust-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>
      </div>
      <el-form ref="adjustFormRef" :model="adjustForm" :rules="adjustRules" label-width="90px" size="small">
        <el-form-item label="调整方式" prop="adjustMode">
          <el-radio-group v-model="adjustForm.adjustMode" @change="handleAdjustModeChange">
            <div class="mode-option">
              <el-radio label="1">增量更新</el-radio>
              <p class="mode-tip">在现有库存上增加或减少配额数量，调整数量为负数表示减少</p>
            </div>
            <div class="mode-option">
              <el-radio label="2">覆盖更新</el-radio>
              <p class="mode-tip">将原有库存数量进行覆盖，覆盖后更新为调整数量填写的库存数量</p>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量" prop="adjustQty">
          <el-input-number
            v-model="adjustForm.adjustQty"
            :min="adjustQtyMin"
            :precision="0"
            controls-position="right"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adjustOpen = false">取 消</el-button>
        <el-button type="primary" :loading="adjustSubmitting" @click="submitAdjust">确 认</el-button>
      </div>
    </el-dialog>

    <!-- 调整记录弹窗 -->
    <el-dialog title="记录" :visible.sync="recordsOpen" width="760px" append-to-body @close="resetRecords">
      <div v-if="currentRow" class="records-toolbar">
        <el-select v-model="recordQuery.adjustType" placeholder="调整类型" clearable size="small" style="width: 160px" @change="loadRecords">
          <el-option v-for="item in adjustTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <el-table border v-loading="recordsLoading" :data="recordList" max-height="420" :empty-text="recordsEmptyText">
        <el-table-column label="调整类型" align="center" prop="adjustTypeText" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.adjustTypeText || adjustTypeLabel(scope.row.adjustType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调整前数量" align="center" prop="stockBefore" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.stockBefore != null ? scope.row.stockBefore : '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调整后数量" align="center" prop="stockAfter" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.stockAfter != null ? scope.row.stockAfter : '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作账号" align="center" prop="operatorName" width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.operatorName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) || '—' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerStockAdjust,
  confirmSellerStockAdjust,
  listSellerStockAdjustRecords
} from "@/api/agri/seller/stock/adjust"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

const ADJUST_TYPE_MAP = {
  "1": "增加库存",
  "2": "减少库存",
  "3": "覆盖库存"
}

export default {
  name: "AgriSellerStockAdjust",
  data() {
    const validateAdjustQty = (rule, value, callback) => {
      if (value == null || value === "") {
        callback(new Error("请输入调整数量"))
        return
      }
      if (!Number.isInteger(Number(value))) {
        callback(new Error("请输入正确的库存数量"))
        return
      }
      if (this.adjustForm.adjustMode === "1") {
        if (Number(value) === 0) {
          callback(new Error("调整数量不能为 0"))
          return
        }
      } else if (Number(value) < 0) {
        callback(new Error("请输入正确的库存数量"))
        return
      }
      callback()
    }
    return {
      loading: false,
      showSearch: true,
      total: 0,
      goodsList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined
      },
      currentRow: null,
      adjustOpen: false,
      adjustSubmitting: false,
      adjustForm: {
        adjustMode: "1",
        adjustQty: 1
      },
      adjustRules: {
        adjustMode: [{ required: true, message: "请选择调整方式", trigger: "change" }],
        adjustQty: [{ validator: validateAdjustQty, trigger: "blur" }]
      },
      recordsOpen: false,
      recordsLoading: false,
      recordList: [],
      recordQuery: {
        adjustType: undefined
      },
      adjustTypeOptions: [
        { value: "1", label: "增加库存" },
        { value: "2", label: "减少库存" },
        { value: "3", label: "覆盖库存" }
      ]
    }
  },
  computed: {
    hasSearchFilter() {
      return !!this.queryParams.keyword
    },
    emptyTableText() {
      return this.hasSearchFilter ? "未找到符合条件的商品" : "暂无可调整商品"
    },
    adjustQtyMin() {
      return this.adjustForm.adjustMode === "2" ? 0 : undefined
    },
    recordsEmptyText() {
      return this.recordQuery.adjustType ? "未找到符合条件的调整记录" : "暂无数据"
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    specText(text) {
      const val = text ? String(text).trim() : ""
      return val && val !== "—" ? val : "—"
    },
    adjustTypeLabel(type) {
      return ADJUST_TYPE_MAP[type] || "—"
    },
    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
      listSellerStockAdjust(this.queryParams).then(response => {
        this.goodsList = 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()
    },
    openAdjust(row) {
      this.currentRow = row
      this.adjustForm = {
        adjustMode: "1",
        adjustQty: 1
      }
      this.adjustOpen = true
      this.$nextTick(() => {
        if (this.$refs.adjustFormRef) {
          this.$refs.adjustFormRef.clearValidate()
        }
      })
    },
    handleAdjustModeChange(mode) {
      if (mode === "2" && this.adjustForm.adjustQty != null && this.adjustForm.adjustQty < 0) {
        this.adjustForm.adjustQty = 0
      }
      this.$nextTick(() => {
        if (this.$refs.adjustFormRef) {
          this.$refs.adjustFormRef.clearValidate("adjustQty")
        }
      })
    },
    resetAdjust() {
      this.currentRow = null
      this.adjustSubmitting = false
      this.adjustForm = {
        adjustMode: "1",
        adjustQty: 1
      }
      if (this.$refs.adjustFormRef) {
        this.$refs.adjustFormRef.resetFields()
      }
    },
    submitAdjust() {
      if (!this.currentRow || !this.currentRow.goodsId) {
        return
      }
      this.$refs.adjustFormRef.validate(valid => {
        if (!valid) {
          return
        }
        this.adjustSubmitting = true
        confirmSellerStockAdjust(this.currentRow.goodsId, {
          adjustMode: this.adjustForm.adjustMode,
          adjustQty: Number(this.adjustForm.adjustQty)
        }).then(() => {
          this.$modal.msgSuccess("调整成功")
          this.adjustOpen = false
          this.adjustSubmitting = false
        }).catch(() => {
          this.adjustSubmitting = false
        })
      })
    },
    openRecords(row) {
      this.currentRow = row
      this.recordQuery.adjustType = undefined
      this.recordsOpen = true
      this.loadRecords()
    },
    loadRecords() {
      if (!this.currentRow || !this.currentRow.goodsId) {
        return
      }
      this.recordsLoading = true
      listSellerStockAdjustRecords(this.currentRow.goodsId, this.recordQuery).then(response => {
        this.recordList = response.data || []
        this.recordsLoading = false
      }).catch(() => {
        this.recordList = []
        this.recordsLoading = false
      })
    },
    resetRecords() {
      this.currentRow = null
      this.recordList = []
      this.recordQuery.adjustType = undefined
      this.recordsLoading = 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;
}
.adjust-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 {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}
.mode-option {
  margin-bottom: 12px;
  &:last-child {
    margin-bottom: 0;
  }
}
.mode-tip {
  margin: 4px 0 0 24px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
.records-toolbar {
  margin-bottom: 12px;
}
</style>
