<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="outOperator">
        <el-select v-model="queryParams.outOperator" placeholder="请选择出库人" clearable filterable>
          <el-option v-for="item in userOptions" :key="item.userId" :label="userLabel(item)" :value="userValue(item)" />
        </el-select>
      </el-form-item>
      <el-form-item label="出库类型" prop="outType">
        <el-select v-model="queryParams.outType" placeholder="请选择类型" clearable>
          <el-option v-for="dict in dict.type.wms_out_type" :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:out:add']">新增</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:out:export']">导出</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="recordList">
      <el-table-column label="出库单号" align="center" prop="outNo" min-width="150" />
      <el-table-column label="库区" align="center" prop="areaName" min-width="110" />
      <el-table-column label="产品信息" min-width="280">
        <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="center" prop="outType">
        <template slot-scope="scope"><dict-tag :options="dict.type.wms_out_type" :value="scope.row.outType" /></template>
      </el-table-column>
      <el-table-column label="数量" align="right" prop="outNum" />
      <el-table-column label="关联单据号" align="center" prop="sourceNo" />
      <el-table-column label="系统操作人" align="center" prop="operator" />
      <el-table-column label="出库人" align="center" prop="outOperator" />
      <el-table-column label="出库时间" align="center" prop="outTime" width="180">
        <template slot-scope="scope">{{ parseTime(scope.row.outTime) }}</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="新增出库记录" :visible.sync="open" width="620px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="出库单号" prop="outNo"><el-input v-model="form.outNo" placeholder="不填则自动生成" /></el-form-item>
        <el-form-item label="库区" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择库区" 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="productId">
          <el-select v-model="form.productId" placeholder="请选择产品" filterable>
            <el-option v-for="item in productOptions" :key="item.id" :label="productLabel(item)" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库人" prop="outOperator">
          <el-select v-model="form.outOperator" placeholder="请选择出库人" filterable>
            <el-option v-for="item in userOptions" :key="item.userId" :label="userLabel(item)" :value="userValue(item)" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库类型" prop="outType">
          <el-select v-model="form.outType" placeholder="请选择出库类型">
            <el-option v-for="dict in dict.type.wms_out_type" :key="dict.value" :label="dict.label" :value="Number(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库数量" prop="outNum"><el-input-number v-model="form.outNum" :min="0.001" :precision="3" :step="1" controls-position="right" /></el-form-item>
        <el-form-item label="关联单据号" prop="sourceNo"><el-input v-model="form.sourceNo" placeholder="请输入关联单据号" /></el-form-item>
        <el-form-item label="备注" prop="remark"><el-input v-model="form.remark" 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 { listOutRecord, addOutRecord } from '@/api/warehouse/outRecord'
import { optionselectArea } from '@/api/warehouse/area'
import { optionselectProduct } from '@/api/warehouse/product'
import { optionselectUser } from '@/api/warehouse/user'

export default {
  name: 'OutRecord',
  dicts: ['wms_out_type'],
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      recordList: [],
      areaOptions: [],
      productOptions: [],
      userOptions: [],
      open: false,
      queryParams: { pageNum: 1, pageSize: 10, areaId: undefined, productName: undefined, brand: undefined, category: undefined, spec: undefined, outOperator: undefined, outType: undefined },
      form: {},
      rules: {
        areaId: [{ required: true, message: '库区不能为空', trigger: 'change' }],
        productId: [{ required: true, message: '产品不能为空', trigger: 'change' }],
        outOperator: [{ required: true, message: '出库人不能为空', trigger: 'change' }],
        outType: [{ required: true, message: '出库类型不能为空', trigger: 'change' }],
        outNum: [{ required: true, message: '出库数量不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    brandOptions() {
      return this.getDistinctOptions('brand')
    },
    categoryOptions() {
      return this.getDistinctOptions('category')
    }
  },
  created() {
    this.getOptions()
    this.getList()
  },
  methods: {
    userLabel(user) {
      return user.nickName || user.userName
    },
    userValue(user) {
      return user.nickName || user.userName
    },
    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 })
      optionselectUser().then(res => { this.userOptions = res.data })
    },
    getList() {
      this.loading = true
      listOutRecord(this.queryParams).then(response => {
        this.recordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cancel() { this.open = false; this.reset() },
    reset() {
      this.form = { outNo: undefined, areaId: undefined, productId: undefined, outOperator: undefined, outType: 1, outNum: undefined, sourceNo: undefined, remark: undefined }
      this.resetForm('form')
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.resetForm('queryForm'); this.handleQuery() },
    handleAdd() { this.reset(); this.open = true },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        addOutRecord(this.form).then(() => {
          this.$modal.msgSuccess('出库成功')
          this.open = false
          this.getList()
        })
      })
    },
    handleExport() {
      this.download('warehouse/out/export', { ...this.queryParams }, `out_record_${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>
