<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" size="small" label-width="90px">
      <el-form-item label="盘点单号" prop="sheetNo">
        <el-input v-model="queryParams.sheetNo" placeholder="请输入盘点单号" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="盘点日期" prop="checkDate">
        <el-date-picker v-model="queryParams.checkDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择" style="width: 200px" />
      </el-form-item>
      <el-form-item label="盘点员" prop="checkUser">
        <el-input v-model="queryParams.checkUser" 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:check:add']">新增盘点</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:check: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="checkDate" min-width="110" align="center" />
      <el-table-column label="盘点单号" prop="sheetNo" min-width="130" align="center" />
      <el-table-column label="盘点员" prop="checkUser" min-width="100" align="center" />
      <el-table-column label="备注" prop="remark" min-width="160" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleView(scope.row)" v-hasPermi="['erp:stock:check:query']">查看</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['erp:stock: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="1400px" append-to-body :close-on-click-modal="false">
      <el-alert
        title="提交后将以实盘数量更新当前库存（基本量、辅助量），成本金额不变；账面数量以提交瞬间系统库存为准。"
        type="info"
        :closable="false"
        class="mb8"
      />
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="盘点日期" prop="checkDate">
              <el-date-picker v-model="form.checkDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择" style="width: 100%" :disabled="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点单号">
              <el-input v-model="form.sheetNo" placeholder="提交后自动生成" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点员" prop="checkUser">
              <el-input v-model="form.checkUser" placeholder="默认当前用户" :disabled="readonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="货单备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" :disabled="readonly" />
        </el-form-item>

        <div class="mb8" v-if="!readonly">
          <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="addGoodsRow">新增明细</el-button>
        </div>
        <el-table :data="form.goodsList" border>
          <el-table-column type="index" label="#" width="50" />
          <el-table-column label="库存行" min-width="280">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.inventoryId"
                filterable
                placeholder="选择仓库+物料+批次"
                style="width: 100%"
                :disabled="readonly"
                @change="onInventoryLineChange(scope.row)"
              >
                <el-option
                  v-for="item in inventoryOptions"
                  :key="item.inventoryId"
                  :label="inventoryOptionLabel(item)"
                  :value="item.inventoryId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" prop="goodsNum" min-width="110" />
          <el-table-column label="物料名称" prop="goodsName" min-width="120" />
          <el-table-column label="入库批次" prop="batchNo" min-width="100" />
          <el-table-column label="仓库" min-width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.warehouseNo }} {{ scope.row.warehouseName ? ' / ' + scope.row.warehouseName : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="基本单位" prop="baseUnit" width="90" />
          <el-table-column label="辅助单位" prop="assistantUnit" width="90" />
          <el-table-column label="账面基本" prop="bookBaseQty" min-width="100" align="right" />
          <el-table-column label="账面辅助" prop="bookAssistQty" min-width="100" align="right" />
          <el-table-column label="盘点基本" width="180">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.countBaseQty"
                :precision="4"
                :min="0"
                :disabled="readonly"
                controls-position="right"
                style="width: 100%"
                @change="recalcDiff(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="盘点辅助" width="180">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.countAssistQty"
                :precision="4"
                :min="0"
                :disabled="readonly"
                controls-position="right"
                style="width: 100%"
                @change="recalcDiff(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="差异基本" min-width="100" align="right">
            <template slot-scope="scope">
              <span>{{ formatQty(scope.row.diffBaseQty) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="差异辅助" min-width="100" align="right">
            <template slot-scope="scope">
              <span>{{ formatQty(scope.row.diffAssistQty) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="货品备注" min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" :disabled="readonly" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" v-if="!readonly">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="removeGoodsRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!readonly" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addStockCheck,
  delStockCheck,
  getStockCheck,
  listStockCheck,
  listStockCheckInventoryOptions
} from "@/api/erp/stock";

export default {
  name: "StockWarehouseCheck",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      ids: [],
      multiple: true,
      open: false,
      title: "",
      readonly: false,
      inventoryOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sheetNo: undefined,
        checkDate: undefined,
        checkUser: undefined
      },
      form: {},
      rules: {
        checkDate: [{ required: true, message: "盘点日期不能为空", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
    this.loadInventoryOptions();
  },
  methods: {
    getList() {
      this.loading = true;
      listStockCheck(this.queryParams).then((res) => {
        this.list = res.rows || [];
        this.total = res.total || 0;
        this.loading = false;
      });
    },
    loadInventoryOptions() {
      listStockCheckInventoryOptions().then((res) => {
        this.inventoryOptions = res.data || [];
      });
    },
    defaultCheckUser() {
      const u = this.$store.state.user;
      return (u && (u.nickName || u.name)) || "";
    },
    reset() {
      this.form = {
        id: undefined,
        checkDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
        sheetNo: "",
        checkUser: this.defaultCheckUser(),
        remark: "",
        goodsList: [this.buildEmptyGoodsRow()]
      };
      this.resetForm("form");
    },
    buildEmptyGoodsRow() {
      return {
        inventoryId: undefined,
        goodsNum: "",
        goodsName: "",
        batchNo: "",
        warehouseNo: "",
        warehouseName: "",
        baseUnit: "",
        assistantUnit: "",
        bookBaseQty: 0,
        bookAssistQty: 0,
        countBaseQty: 0,
        countAssistQty: 0,
        diffBaseQty: 0,
        diffAssistQty: 0,
        remark: ""
      };
    },
    inventoryOptionLabel(item) {
      const wh = item.warehouseNo || "";
      const g = item.goodsNum || "";
      const b = item.batchNo || "";
      return `${wh} | ${g} | 批次:${b}`;
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.readonly = false;
      this.reset();
      this.open = true;
      this.title = "新增仓库盘点";
      this.loadInventoryOptions();
    },
    handleView(row) {
      this.readonly = true;
      getStockCheck(row.id).then((res) => {
        this.form = Object.assign({ goodsList: [] }, res.data || {});
        this.open = true;
        this.title = "查看仓库盘点";
      });
    },
    onInventoryLineChange(row) {
      const hit = this.inventoryOptions.find((o) => o.inventoryId === row.inventoryId);
      if (!hit) {
        return;
      }
      row.goodsNum = hit.goodsNum || "";
      row.goodsName = hit.goodsName || "";
      row.batchNo = hit.batchNo || "";
      row.warehouseNo = hit.warehouseNo || "";
      row.warehouseName = hit.warehouseName || "";
      row.baseUnit = hit.baseUnit || "";
      row.assistantUnit = hit.assistantUnit || "";
      row.bookBaseQty = Number(hit.bookBaseQty != null ? hit.bookBaseQty : 0);
      row.bookAssistQty = Number(hit.bookAssistQty != null ? hit.bookAssistQty : 0);
      row.countBaseQty = row.bookBaseQty;
      row.countAssistQty = row.bookAssistQty;
      this.recalcDiff(row);
    },
    recalcDiff(row) {
      const cb = Number(row.countBaseQty || 0);
      const ca = Number(row.countAssistQty || 0);
      const bb = Number(row.bookBaseQty || 0);
      const ba = Number(row.bookAssistQty || 0);
      row.diffBaseQty = cb - bb;
      row.diffAssistQty = ca - ba;
      this.$forceUpdate();
    },
    formatQty(v) {
      if (v === null || v === undefined || v === "") {
        return "0.0000";
      }
      return Number(v).toFixed(4);
    },
    addGoodsRow() {
      this.form.goodsList.push(this.buildEmptyGoodsRow());
    },
    removeGoodsRow(index) {
      this.form.goodsList.splice(index, 1);
      if (this.form.goodsList.length === 0) {
        this.form.goodsList.push(this.buildEmptyGoodsRow());
      }
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    validateGoodsList() {
      const goodsList = this.form.goodsList || [];
      if (!goodsList.length) {
        this.$modal.msgError("至少需要一条盘点明细");
        return false;
      }
      for (let i = 0; i < goodsList.length; i++) {
        const row = goodsList[i];
        if (!row.inventoryId) {
          this.$modal.msgError(`第${i + 1}行未选择库存行`);
          return false;
        }
      }
      return true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid || !this.validateGoodsList()) {
          return;
        }
        const payload = {
          checkDate: this.form.checkDate,
          checkUser: this.form.checkUser,
          remark: this.form.remark,
          goodsList: (this.form.goodsList || []).map((r) => ({
            inventoryId: r.inventoryId,
            countBaseQty: Number(r.countBaseQty || 0),
            countAssistQty: Number(r.countAssistQty || 0),
            remark: r.remark
          }))
        };
        addStockCheck(payload).then(() => {
          this.$modal.msgSuccess("提交成功");
          this.open = false;
          this.getList();
          this.loadInventoryOptions();
        });
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids.join(",");
      this.$modal.confirm("确认删除选中的盘点单吗？（不会回滚已更新的库存）").then(() => delStockCheck(ids)).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    }
  }
};
</script>
