<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="80px">
        <el-form-item label="商品编号" prop="goodsSn">
          <el-input v-model="queryParams.goodsSn" placeholder="商品编号" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="queryParams.goodsName" placeholder="商品名称" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="queryParams.shopName" placeholder="店铺名称" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="商品状态" prop="goodsStatus">
          <el-select v-model="queryParams.goodsStatus" placeholder="全部" clearable style="width: 120px">
            <el-option label="待审核" value="1" />
            <el-option label="出售中" value="2" />
            <el-option label="审核失败" value="3" />
            <el-option label="已下架" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-tabs v-model="statusTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane name="1">
          <span slot="label">待审核<el-badge v-if="pendingCount > 0" :value="pendingCount" class="tab-badge" /></span>
        </el-tab-pane>
        <el-tab-pane label="出售中" name="2" />
        <el-tab-pane label="审核失败" name="3" />
        <el-tab-pane label="已下架" name="4" />
      </el-tabs>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-check" size="mini" :disabled="!canBatchAudit" @click="handleBatchAudit(true)" v-hasPermi="['agri:goods:audit']">批量通过</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-close" size="mini" :disabled="!canBatchAudit" @click="batchRejectOpen = true" v-hasPermi="['agri:goods:audit']">批量驳回</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-bottom" size="mini" :disabled="!canBatchOffShelf" @click="handleBatchOffShelf" v-hasPermi="['agri:goods:offshelf']">批量下架</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="店铺名称" align="center" prop="shopName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="商品编号" align="center" prop="goodsSn" width="140" />
        <el-table-column label="主图" align="center" width="80">
          <template slot-scope="scope">
            <image-preview :src="scope.row.mainPic" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="goodsName" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column label="售价" align="center" prop="salePrice" width="90" />
        <el-table-column label="销量" align="center" prop="salesCount" width="70" />
        <el-table-column label="分类" align="center" prop="categoryPath" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="goodsStatus" width="90">
          <template slot-scope="scope">
            <el-tag size="small" :type="goodsStatusTag(scope.row.goodsStatus)">{{ goodsStatusLabel(scope.row.goodsStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['agri:goods:query']">详情</el-button>
            <el-button v-if="scope.row.goodsStatus === '1'" size="mini" type="text" icon="el-icon-check" @click="handleRowAudit(scope.row, true)" v-hasPermi="['agri:goods:audit']">通过</el-button>
            <el-button v-if="scope.row.goodsStatus === '1'" size="mini" type="text" icon="el-icon-close" @click="handleRowReject(scope.row)" v-hasPermi="['agri:goods:audit']">驳回</el-button>
            <el-button v-if="scope.row.goodsStatus === '2'" size="mini" type="text" icon="el-icon-bottom" @click="handleRowOffShelf(scope.row)" v-hasPermi="['agri:goods:offshelf']">下架</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>

    <!-- 详情抽屉 -->
    <goods-detail :visible.sync="detailOpen" :goods-id="currentGoodsId" @success="handleSuccess" />

    <!-- 单行驳回弹窗 -->
    <el-dialog title="审核驳回" :visible.sync="rejectOpen" width="480px" append-to-body>
      <el-form ref="rejectForm" :model="rejectForm" :rules="rejectRules" label-width="90px">
        <el-form-item label="驳回原因" prop="rejectReason">
          <el-input v-model="rejectForm.rejectReason" type="textarea" :rows="4" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitRowReject">确 定</el-button>
        <el-button @click="rejectOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量驳回弹窗 -->
    <el-dialog title="批量审核驳回" :visible.sync="batchRejectOpen" width="480px" append-to-body>
      <el-form ref="batchRejectForm" :model="batchRejectForm" :rules="rejectRules" label-width="90px">
        <el-form-item label="驳回原因" prop="rejectReason">
          <el-input v-model="batchRejectForm.rejectReason" type="textarea" :rows="4" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitBatchReject">确 定</el-button>
        <el-button @click="batchRejectOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoodsPendingCount, auditGoods, offShelfGoods } from "@/api/agri/goods"
import GoodsDetail from "./detail"

export default {
  name: "AgriGoodsAudit",
  components: { GoodsDetail },
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      pendingCount: 0,
      goodsList: [],
      selection: [],
      detailOpen: false,
      currentGoodsId: null,
      rejectOpen: false,
      batchRejectOpen: false,
      rejectTargetIds: [],
      statusTab: "1",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsSn: undefined,
        goodsName: undefined,
        shopName: undefined,
        goodsStatus: "1"
      },
      rejectForm: { rejectReason: "" },
      batchRejectForm: { rejectReason: "" },
      rejectRules: {
        rejectReason: [{ required: true, message: "请填写驳回原因", trigger: "blur" }]
      }
    }
  },
  computed: {
    /** 所选是否全部为待审核 */
    canBatchAudit() {
      return this.selection.length > 0 && this.selection.every(item => item.goodsStatus === "1")
    },
    /** 所选是否全部为出售中 */
    canBatchOffShelf() {
      return this.selection.length > 0 && this.selection.every(item => item.goodsStatus === "2")
    }
  },
  created() {
    this.loadPendingCount()
    this.getList()
  },
  methods: {
    loadPendingCount() {
      getGoodsPendingCount().then(response => {
        this.pendingCount = (response.data && response.data.pendingCount) || 0
      }).catch(() => {})
    },
    getList() {
      this.loading = true
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    goodsStatusLabel(status) {
      const map = { "1": "待审核", "2": "出售中", "3": "审核失败", "4": "已下架" }
      return map[status] || "—"
    },
    goodsStatusTag(status) {
      const map = { "1": "warning", "2": "success", "3": "danger", "4": "info" }
      return map[status] || "info"
    },
    handleTabClick() {
      this.queryParams.goodsStatus = this.statusTab === "all" ? undefined : this.statusTab
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.statusTab = "all"
      this.queryParams.goodsStatus = undefined
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    handleDetail(row) {
      this.currentGoodsId = row.goodsId
      this.detailOpen = true
    },
    handleRowAudit(row, pass) {
      this.$modal.confirm("确认审核通过？").then(() => {
        return auditGoods({ goodsIds: [row.goodsId], pass: pass })
      }).then(() => {
        this.$modal.msgSuccess("审核通过")
        this.handleSuccess()
      }).catch(() => {})
    },
    handleRowReject(row) {
      this.rejectTargetIds = [row.goodsId]
      this.rejectForm.rejectReason = ""
      this.rejectOpen = true
    },
    submitRowReject() {
      this.$refs["rejectForm"].validate(valid => {
        if (!valid) {
          return
        }
        auditGoods({
          goodsIds: this.rejectTargetIds,
          pass: false,
          rejectReason: this.rejectForm.rejectReason
        }).then(() => {
          this.$modal.msgSuccess("已驳回")
          this.rejectOpen = false
          this.handleSuccess()
        })
      })
    },
    handleBatchAudit(pass) {
      const ids = this.selection.map(item => item.goodsId)
      this.$modal.confirm("确认批量审核通过所选 " + ids.length + " 件商品？").then(() => {
        return auditGoods({ goodsIds: ids, pass: pass })
      }).then(() => {
        this.$modal.msgSuccess("批量审核通过")
        this.handleSuccess()
      }).catch(() => {})
    },
    submitBatchReject() {
      this.$refs["batchRejectForm"].validate(valid => {
        if (!valid) {
          return
        }
        const ids = this.selection.map(item => item.goodsId)
        auditGoods({
          goodsIds: ids,
          pass: false,
          rejectReason: this.batchRejectForm.rejectReason
        }).then(() => {
          this.$modal.msgSuccess("批量驳回成功")
          this.batchRejectOpen = false
          this.handleSuccess()
        })
      })
    },
    handleRowOffShelf(row) {
      this.$modal.confirm("确认下架该商品？").then(() => {
        return offShelfGoods({ goodsIds: [row.goodsId] })
      }).then(() => {
        this.$modal.msgSuccess("下架成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    handleBatchOffShelf() {
      const ids = this.selection.map(item => item.goodsId)
      this.$modal.confirm("确认批量下架所选 " + ids.length + " 件商品？").then(() => {
        return offShelfGoods({ goodsIds: ids })
      }).then(() => {
        this.$modal.msgSuccess("批量下架成功")
        this.handleSuccess()
      }).catch(() => {})
    },
    handleSuccess() {
      this.loadPendingCount()
      this.getList()
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 10px;
}
.tab-badge {
  margin-left: 4px;
}
</style>
