<template>
  <el-drawer
    title="商品出库"
    :visible.sync="localVisible"
    direction="rtl"
    size="85%"
    append-to-body
    :wrapper-closable="false"
    custom-class="outbound-form-drawer"
    @close="handleClose"
  >
    <div class="drawer-body">
      <h4 class="section-header">基本信息</h4>
      <el-form ref="baseFormRef" :model="form" :rules="baseRules" label-width="90px" size="small" class="base-form">
        <el-form-item label="出库类型" prop="outboundType">
          <el-radio-group v-model="form.outboundType">
            <el-radio label="3">过期出库</el-radio>
            <el-radio label="2">订单出库</el-radio>
            <el-radio label="4">其他出库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
            style="max-width: 640px"
          />
        </el-form-item>
      </el-form>

      <h4 class="section-header">出库商品</h4>
      <div class="goods-toolbar">
        <el-button type="primary" size="mini" icon="el-icon-goods" @click="openGoodsPicker">选择商品</el-button>
        <!-- <el-button size="mini" icon="el-icon-upload2" @click="handleImportTip">导入商品</el-button>
        <div class="barcode-wrap">
          <el-input
            v-model="barcodeInput"
            placeholder="请输入商品条码"
            clearable
            size="small"
            style="width: 280px"
            @keyup.enter.native="handleBarcodeConfirm"
          >
            <i slot="prefix" class="el-input__icon el-icon-full-screen" />
            <el-button slot="append" type="primary" @click="handleBarcodeConfirm">确定(Enter)</el-button>
          </el-input>
        </div> -->
      </div>

      <el-table border size="small" :data="formItems" class="items-table" empty-text="请添加出库商品">
        <el-table-column label="商品信息" min-width="220">
          <template slot-scope="scope">
            <div class="goods-cell">
              <image-preview v-if="scope.row.mainPic" :src="scope.row.mainPic" :width="44" :height="44" />
              <span>{{ scope.row.goodsName || '—' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ specText(scope.row.specText) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="当前可用库存" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.stock != null ? scope.row.stock : '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出库数量" width="160" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="scope.row.stock != null ? scope.row.stock : undefined"
              :precision="0"
              controls-position="right"
              size="small"
              style="width: 120px"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="removeItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="drawer-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">确 认</el-button>
    </div>

    <!-- 商品选择器 -->
    <el-dialog title="选择商品" :visible.sync="pickerOpen" width="820px" append-to-body @close="resetPicker">
      <p class="pick-tip">仅展示当前可用库存 &gt; 0 的商品</p>
      <el-form :inline="true" size="small" @submit.native.prevent>
        <el-form-item label="商品名称">
          <el-input v-model="pickerQuery.keyword" placeholder="名称/编号" clearable style="width: 200px" @keyup.enter.native="searchGoodsOptions" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchGoodsOptions">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="pickerTable"
        border
        v-loading="pickerLoading"
        :data="pickerList"
        max-height="360"
        @selection-change="handlePickerSelection"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="商品信息" min-width="200">
          <template slot-scope="scope">
            <div class="goods-cell">
              <image-preview v-if="scope.row.mainPic" :src="scope.row.mainPic" :width="40" :height="40" />
              <span>{{ scope.row.goodsName || '—' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ specText(scope.row.specText) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="编号" prop="goodsSn" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="可用库存" prop="stock" width="90" align="center" />
      </el-table>
      <pagination
        v-show="pickerTotal > 0"
        :total="pickerTotal"
        :page.sync="pickerQuery.pageNum"
        :limit.sync="pickerQuery.pageSize"
        @pagination="loadGoodsOptions"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmPicker">确 定</el-button>
        <el-button @click="pickerOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 条码多匹配选择 -->
    <el-dialog title="选择商品规格" :visible.sync="barcodePickOpen" width="640px" append-to-body>
      <p class="pick-tip">该条码匹配到多个商品，请选择其一：</p>
      <el-table border :data="barcodeCandidates" @row-click="selectBarcodeCandidate">
        <el-table-column label="商品信息" min-width="180">
          <template slot-scope="scope">
            <div class="goods-cell">
              <image-preview v-if="scope.row.mainPic" :src="scope.row.mainPic" :width="40" :height="40" />
              <span>{{ scope.row.goodsName || '—' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ specText(scope.row.specText) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="可用库存" prop="stock" width="90" align="center" />
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click.stop="selectBarcodeCandidate(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-drawer>
</template>

<script>
import {
  createSellerStockOutbound,
  listStockOutboundGoodsOptions,
  getStockOutboundGoodsByBarcode
} from "@/api/agri/seller/stock/outbound"

export default {
  name: "SellerStockOutboundForm",
  props: {
    visible: { type: Boolean, default: false }
  },
  data() {
    return {
      localVisible: false,
      submitting: false,
      form: {
        outboundType: "3",
        remark: undefined
      },
      formItems: [],
      barcodeInput: "",
      baseRules: {
        outboundType: [{ required: true, message: "请选择出库类型", trigger: "change" }]
      },
      pickerOpen: false,
      pickerLoading: false,
      pickerList: [],
      pickerTotal: 0,
      pickerSelection: [],
      pickerQuery: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined
      },
      barcodePickOpen: false,
      barcodeCandidates: []
    }
  },
  watch: {
    visible(val) {
      this.localVisible = val
      if (val) {
        this.resetForm()
      }
    },
    localVisible(val) {
      this.$emit("update:visible", val)
    }
  },
  methods: {
    specText(text) {
      const val = text ? String(text).trim() : ""
      return val || "—"
    },
    resetForm() {
      this.form = {
        outboundType: "3",
        remark: undefined
      }
      this.formItems = []
      this.barcodeInput = ""
      this.submitting = false
      this.$nextTick(() => {
        if (this.$refs.baseFormRef) {
          this.$refs.baseFormRef.clearValidate()
        }
      })
    },
    handleClose() {
      this.resetForm()
    },
    handleCancel() {
      this.localVisible = false
    },
    openGoodsPicker() {
      this.pickerOpen = true
      this.pickerQuery.pageNum = 1
      this.loadGoodsOptions()
    },
    resetPicker() {
      this.pickerSelection = []
      this.pickerQuery.keyword = undefined
      if (this.$refs.pickerTable) {
        this.$refs.pickerTable.clearSelection()
      }
    },
    searchGoodsOptions() {
      this.pickerQuery.pageNum = 1
      this.loadGoodsOptions()
    },
    loadGoodsOptions() {
      this.pickerLoading = true
      listStockOutboundGoodsOptions(this.pickerQuery).then(response => {
        this.pickerList = response.rows || []
        this.pickerTotal = response.total || 0
        this.pickerLoading = false
      }).catch(() => {
        this.pickerLoading = false
      })
    },
    handlePickerSelection(rows) {
      this.pickerSelection = rows || []
    },
    confirmPicker() {
      if (!this.pickerSelection.length) {
        this.$modal.msgWarning("请选择商品")
        return
      }
      this.pickerSelection.forEach(row => {
        this.appendGoodsRow(row)
      })
      this.pickerOpen = false
    },
    handleImportTip() {
      this.$modal.msgWarning("批量导入功能暂未开放，请使用选择商品或条码录入")
    },
    handleBarcodeConfirm() {
      const code = this.barcodeInput ? String(this.barcodeInput).trim() : ""
      if (!code) {
        this.$modal.msgWarning("请输入商品条码")
        return
      }
      getStockOutboundGoodsByBarcode(code).then(response => {
        const rows = response.data || []
        if (!rows.length) {
          this.$modal.msgError("未找到该条码对应的商品")
          return
        }
        const validRows = rows.filter(row => row.stock != null && row.stock > 0)
        if (!validRows.length) {
          this.$modal.msgError("该商品无可用库存")
          return
        }
        if (validRows.length === 1) {
          this.appendGoodsRow(validRows[0])
          this.barcodeInput = ""
          return
        }
        this.barcodeCandidates = validRows
        this.barcodePickOpen = true
      })
    },
    selectBarcodeCandidate(row) {
      this.appendGoodsRow(row)
      this.barcodePickOpen = false
      this.barcodeCandidates = []
      this.barcodeInput = ""
    },
    itemKey(row) {
      const skuId = row.skuId != null ? row.skuId : ""
      return `${row.goodsId}_${skuId}`
    },
    appendGoodsRow(row) {
      if (!row || row.goodsId == null) {
        return
      }
      if (row.stock == null || row.stock <= 0) {
        this.$modal.msgWarning("该商品无可用库存")
        return
      }
      const key = this.itemKey(row)
      const exist = this.formItems.find(item => this.itemKey(item) === key)
      if (exist) {
        const nextQty = (exist.quantity || 0) + 1
        if (nextQty > exist.stock) {
          this.$modal.msgWarning("出库数量不能大于可用库存")
          return
        }
        exist.quantity = nextQty
        this.$modal.msgSuccess("该商品已在明细中，已合并数量")
        return
      }
      this.formItems.push({
        goodsId: row.goodsId,
        skuId: row.skuId || null,
        goodsName: row.goodsName,
        mainPic: row.mainPic,
        specText: row.specText,
        stock: row.stock,
        quantity: 1
      })
    },
    removeItem(index) {
      this.formItems.splice(index, 1)
    },
    validateItems() {
      if (!this.formItems.length) {
        this.$modal.msgWarning("请添加出库商品")
        return false
      }
      for (let i = 0; i < this.formItems.length; i++) {
        const item = this.formItems[i]
        const qty = item.quantity
        if (qty == null || !Number.isInteger(Number(qty)) || Number(qty) < 1) {
          this.$modal.msgWarning("请输入正确的出库数量")
          return false
        }
        if (item.stock != null && Number(qty) > Number(item.stock)) {
          this.$modal.msgWarning("出库数量不能大于可用库存")
          return false
        }
      }
      return true
    },
    handleSubmit() {
      this.$refs.baseFormRef.validate(valid => {
        if (!valid || !this.validateItems()) {
          return
        }
        const payload = {
          outboundType: this.form.outboundType,
          remark: this.form.remark ? String(this.form.remark).trim() : undefined,
          items: this.formItems.map(item => ({
            goodsId: item.goodsId,
            skuId: item.skuId || null,
            quantity: Number(item.quantity)
          }))
        }
        this.submitting = true
        createSellerStockOutbound(payload).then(response => {
          const data = response.data || {}
          this.$modal.msgSuccess("出库成功")
          this.localVisible = false
          this.$emit("success", data)
          this.submitting = false
        }).catch(() => {
          this.submitting = false
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.drawer-body {
  padding: 0 20px 72px;
}
.section-header {
  margin: 8px 0 12px;
  font-size: 15px;
  color: #303133;
  border-left: 3px solid #409EFF;
  padding-left: 8px;
}
.base-form {
  margin-bottom: 8px;
}
.goods-toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
}
.barcode-wrap {
  margin-left: auto;
}
.items-table {
  margin-top: 4px;
}
.goods-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}
.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 10;
  padding: 12px 20px;
  text-align: right;
  background: #fff;
  border-top: 1px solid #EBEEF5;
}
.pick-tip {
  margin: 0 0 12px;
  font-size: 13px;
  color: #606266;
}
</style>

<style lang="scss">
.outbound-form-drawer .el-drawer__body {
  position: relative;
  padding: 0;
  overflow: auto;
}
</style>
