<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" size="small" label-width="90px">
      <el-form-item label="仓库编号" prop="warehouseNo">
        <el-input v-model="queryParams.warehouseNo" placeholder="请输入仓库编号" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="物料编号" prop="goodsNum">
        <el-input v-model="queryParams.goodsNum" placeholder="请输入物料编号" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" clearable style="width: 200px" />
      </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="['erp:stock:inventory: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="['erp:stock:inventory: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="['erp:stock:inventory:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="仓库编号" prop="warehouseNo" min-width="120" align="center" />
      <el-table-column label="仓库名称" prop="warehouseName" min-width="140" align="center" />
      <el-table-column label="物料编号" prop="goodsNum" min-width="120" align="center" />
      <el-table-column label="物料名称" prop="goodsName" min-width="140" align="center" />
      <el-table-column label="批次号" prop="batchNo" min-width="120" align="center" />
      <el-table-column label="库存量" prop="stockQty" min-width="120" align="center" />
      <el-table-column label="辅助库存量" prop="assistStockQty" min-width="120" align="center" />
      <el-table-column label="成本" prop="costAmount" min-width="100" align="center" />
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleUpdate(scope.row)" v-hasPermi="['erp:stock:inventory:edit']">修改</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['erp:stock:inventory: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="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="仓库" prop="warehouseNo">
          <el-select
            filterable
            style="width: 100%;"
            v-model="form.warehouseNo"
            @change="changeWare"
            placeholder="请选择仓库"
            @keydown.enter.native="goNext($event, 'remark1')"
          >
            <el-option v-for="item in warehouseOptions" :key="item.warehouseNo" :value="item.warehouseNo" :label="item.warehouseName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料编号" prop="goodsNum">
          <el-input v-model="form.goodsNum" disabled placeholder="请搜索物料">
            <template #append>
              <el-tooltip class="item" effect="dark" content="货品速查" placement="top">
                <el-button type="success" icon="el-icon-search" circle size="mini" @click="openQueryMaterial"></el-button>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="物料名称" prop="goodsName">
          <el-input v-model="form.goodsName" disabled placeholder="搜索完自动填充"></el-input>
        </el-form-item>
        <el-form-item label="基本单位" prop="unit">
          <el-input v-model="form.unit" disabled placeholder="搜索完自动填充"></el-input>
        </el-form-item>
        <el-form-item label="辅助单位" prop="assistantUnit">
          <el-input v-model="form.assistantUnit" disabled placeholder="搜索完自动填充"></el-input>
        </el-form-item>
        <el-form-item label="批次号" prop="batchNo">
          <el-input v-model="form.batchNo"  placeholder="请输入批次号"></el-input>
        </el-form-item>
        <el-form-item label="基本库存量" prop="stockQty">
          <decimal-input v-model="form.stockQty" :min="0" :max="999999" :precision="2" placeholder="请输入基本库存量" />
        </el-form-item>
        <el-form-item label="辅助库存量" prop="assistStockQty">
          <decimal-input v-model="form.assistStockQty" :min="0" :max="999999" :precision="2" placeholder="请输入辅助库存量" />
        </el-form-item>
        <el-form-item label="成本" prop="costAmount">
          <decimal-input v-model="form.costAmount" :min="0" :max="999999" :precision="2" placeholder="请输入成本" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
        <!-- <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseNo">
              <el-select v-model="form.warehouseNo" filterable placeholder="请选择仓库" style="width: 100%" @change="onWarehouseChange">
                <el-option v-for="item in warehouseOptions" :key="item.code" :label="`${item.code} - ${item.name}`" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="物料" prop="goodsNum">
              <el-select v-model="form.goodsNum" filterable placeholder="请选择物料" style="width: 100%" @change="onMaterialChange">
                <el-option v-for="item in materialOptions" :key="item.code" :label="`${item.code} - ${item.name}`" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="goodsName">
              <el-input v-model="form.goodsName" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="form.batchNo" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存量" prop="stockQty">
              <el-input-number v-model="form.stockQty" :precision="4" :min="0" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="辅助库存量" prop="assistStockQty">
              <el-input-number v-model="form.assistStockQty" :precision="4" :min="0" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本" prop="costAmount">
              <el-input-number v-model="form.costAmount" :precision="4" :min="0" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </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>
      <query-material ref="query-material" :is-multiple="false" @selectList="getSelectList"></query-material>
    </el-dialog>
  </div>
</template>

<script>
import {
  addInventory,
  delInventory,
  getInventory,
  listInventory,
  listMaterialOptions,
  listWarehouseOptions,
  updateInventory
} from "@/api/erp/stock";
import { getWareHouseList } from "@/api/erp/stock";
import queryMaterial from "../../../components/queryMaterial.vue";
import { getFindByKey } from "@/utils";
export default {
  name: "StockInventory",
  components: {
    queryMaterial
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      title: "",
      open: false,
      ids: [],
      single: true,
      multiple: true,
      warehouseOptions: [],
      materialOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseNo: undefined,
        goodsNum: undefined,
        batchNo: undefined
      },
      form: {},
      rules: {
        warehouseNo: [{ required: true, message: "仓库不能为空", trigger: "change" }],
        goodsNum: [{ required: true, message: "物料不能为空", trigger: "change" }],
        batchNo: [{ required: true, message: "批次号不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
    this.loadOptions();
  },
  methods: {
    initWarehouse() {
      getWareHouseList({}).then(res => {
        this.wareList = res.data
      })
    },
    changeWare(val) {
      let item = getFindByKey(this.wareList, val, 'warehouseNo')
      if(item) {
        this.form.warehouseName = item.warehouseName
      }
    },
    goNext(event, nextRef) {
      event.preventDefault();
      this.$refs[nextRef].focus();
    },
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then((res) => {
        this.list = res.rows || [];
        this.total = res.total || 0;
        this.loading = false;
      });
    },
    loadOptions() {
      listWarehouseOptions().then((res) => {
        this.warehouseOptions = res.data || [];
      });
      listMaterialOptions().then((res) => {
        this.materialOptions = res.data || [];
      });
    },
    reset() {
      this.form = {
        id: undefined,
        warehouseNo: "",
        warehouseName: "",
        goodsNum: "",
        goodsName: "",
        batchNo: "",
        stockQty: 0,
        assistStockQty: 0,
        costAmount: 0,
        remark: ""
      };
      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) {
      const id = row.id || this.ids[0];
      this.reset();
      getInventory(id).then((res) => {
        this.form = Object.assign({}, this.form, res.data || {});
        this.open = true;
        this.title = "修改库存";
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
     // 打开物料速查表
     openQueryMaterial() {
      this.$refs['query-material'].open()
    },
    getSelectList(list) {
      this.form.goodsName = list[0].goodsName;
      this.form.goodsNum = list[0].goodsNum;
      this.form.unit = list[0].unit;
      this.form.assistantUnit = list[0].assistantUnit;
    },
    onWarehouseChange(warehouseNo) {
      const hit = this.warehouseOptions.find((item) => item.code === warehouseNo);
      this.form.warehouseName = hit ? hit.name : "";
    },
    onMaterialChange(goodsNum) {
      const hit = this.materialOptions.find((item) => item.code === goodsNum);
      this.form.goodsName = hit ? hit.name : "";
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        const req = this.form.id ? updateInventory(this.form) : addInventory(this.form);
        req.then(() => {
          this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids.join(",");
      this.$modal.confirm("确认删除选中的库存数据吗？").then(() => delInventory(ids)).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    }
  }
};
</script>
