<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="库区" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择库区" clearable filterable>
          <el-option v-for="item in areaOptions" :key="item.id" :label="areaLabel(item)" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-select v-model="queryParams.brand" placeholder="请选择品牌" clearable filterable>
          <el-option v-for="item in brandOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择类别" clearable filterable>
          <el-option v-for="item in categoryOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="规格" prop="spec">
        <el-input v-model="queryParams.spec" placeholder="请输入规格" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.wms_check_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </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-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['warehouse:check:add']">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['warehouse:check:edit']">修改</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['warehouse:check:remove']">删除</el-button></el-col>
      <el-col :span="1.5"><el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['warehouse:check:export']">导出</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="盘点单号" align="center" prop="checkNo" min-width="150" />
      <el-table-column label="库区" align="center" prop="areaName" min-width="110" />
      <el-table-column label="产品信息" min-width="300">
        <template slot-scope="scope">
          <div class="product-name">{{ scope.row.productName || '-' }}</div>
          <div class="product-meta">
            <span v-if="scope.row.brand">品牌：{{ scope.row.brand }}</span>
            <span v-if="scope.row.category">类别：{{ scope.row.category }}</span>
            <span v-if="scope.row.spec">规格：{{ scope.row.spec }}</span>
            <span v-if="scope.row.unit">单位：{{ scope.row.unit }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="账面库存" align="right" prop="bookNum" />
      <el-table-column label="实际数量" align="right" prop="realNum" />
      <el-table-column label="差异" align="right" prop="diffNum" />
      <el-table-column label="状态" align="center" prop="checkStatus">
        <template slot-scope="scope"><dict-tag :options="dict.type.wms_check_status" :value="scope.row.checkStatus" /></template>
      </el-table-column>
      <el-table-column label="盘点人" align="center" prop="checkUser" />
      <el-table-column label="审核人" align="center" prop="confirmUser" />
      <el-table-column label="生效时间" align="center" prop="confirmTime" width="180">
        <template slot-scope="scope">{{ parseTime(scope.row.confirmTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="scope.row.checkStatus === 0" size="mini" type="text" icon="el-icon-check" @click="handleConfirm(scope.row)" v-hasPermi="['warehouse:check:confirm']">确认</el-button>
          <el-button v-if="scope.row.checkStatus === 0" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['warehouse:check:edit']">修改</el-button>
          <el-button v-if="scope.row.checkStatus === 0" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['warehouse:check:remove']">删除</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-dialog :title="title" :visible.sync="open" width="620px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="盘点单号" prop="checkNo"><el-input v-model="form.checkNo" placeholder="不填则自动生成" :disabled="!!form.id" /></el-form-item>
        <el-form-item label="库区" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择库区" filterable :disabled="!!form.id">
            <el-option v-for="item in areaOptions" :key="item.id" :label="areaLabel(item)" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择产品" filterable :disabled="!!form.id">
            <el-option v-for="item in productOptions" :key="item.id" :label="productLabel(item)" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.id" label="账面库存"><el-input :value="form.bookNum" disabled /></el-form-item>
        <el-form-item label="实际盘点数量" prop="realNum"><el-input-number v-model="form.realNum" :min="0" :precision="3" :step="1" controls-position="right" /></el-form-item>
        <el-form-item label="差异原因" prop="reason"><el-input v-model="form.reason" type="textarea" placeholder="请输入差异原因" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStockCheck, getStockCheck, delStockCheck, addStockCheck, updateStockCheck, confirmStockCheck } from '@/api/warehouse/stockCheck'
import { optionselectArea } from '@/api/warehouse/area'
import { optionselectProduct } from '@/api/warehouse/product'

export default {
  name: 'StockCheck',
  dicts: ['wms_check_status'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      recordList: [],
      areaOptions: [],
      productOptions: [],
      title: '',
      open: false,
      queryParams: { pageNum: 1, pageSize: 10, areaId: undefined, productName: undefined, brand: undefined, category: undefined, spec: undefined, checkStatus: undefined },
      form: {},
      rules: {
        areaId: [{ required: true, message: '库区不能为空', trigger: 'change' }],
        productId: [{ required: true, message: '产品不能为空', trigger: 'change' }],
        realNum: [{ required: true, message: '实际盘点数量不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    brandOptions() {
      return this.getDistinctOptions('brand')
    },
    categoryOptions() {
      return this.getDistinctOptions('category')
    }
  },
  created() {
    this.getOptions()
    this.getList()
  },
  methods: {
    areaLabel(area) {
      return area.areaName || area.areaCode
    },
    productLabel(product) {
      const name = product.productName || product.productCode || '-'
      const details = [product.brand, product.category, product.spec, product.unit].filter(item => item)
      return details.length ? name + '（' + details.join(' / ') + '）' : name
    },
    getDistinctOptions(field) {
      const values = this.productOptions.map(item => item[field]).filter(item => item !== undefined && item !== null && item !== '')
      return Array.from(new Set(values))
    },
    getOptions() {
      optionselectArea().then(res => { this.areaOptions = res.data })
      optionselectProduct().then(res => { this.productOptions = res.data })
    },
    getList() {
      this.loading = true
      listStockCheck(this.queryParams).then(response => {
        this.recordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cancel() { this.open = false; this.reset() },
    reset() {
      this.form = { id: undefined, checkNo: undefined, areaId: undefined, productId: undefined, bookNum: undefined, realNum: undefined, reason: undefined }
      this.resetForm('form')
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.resetForm('queryForm'); this.handleQuery() },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() { this.reset(); this.open = true; this.title = '新增盘库记录' },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getStockCheck(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改盘库记录'
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        const request = this.form.id ? updateStockCheck(this.form) : addStockCheck(this.form)
        request.then(() => {
          this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    handleConfirm(row) {
      this.$modal.confirm('是否确认盘点单号为"' + row.checkNo + '"的记录生效？').then(() => confirmStockCheck(row.id)).then(() => {
        this.getList()
        this.$modal.msgSuccess('盘点已生效')
      }).catch(() => {})
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除盘库编号为"' + ids + '"的数据项？').then(() => delStockCheck(ids)).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleExport() {
      this.download('warehouse/check/export', { ...this.queryParams }, `stock_check_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.product-name {
  line-height: 20px;
  font-weight: 600;
}
.product-meta {
  color: #909399;
  line-height: 18px;
}
.product-meta span {
  margin-right: 12px;
  white-space: nowrap;
}
</style>
