<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="adjustDate">
        <el-date-picker v-model="queryParams.adjustDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择" style="width: 200px" />
      </el-form-item>
      <el-form-item label="调整员" prop="adjustUser">
        <el-input v-model="queryParams.adjustUser" 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:adjust: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:adjust: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="adjustDate" min-width="110" align="center" />
      <el-table-column label="调整单号" prop="sheetNo" min-width="130" align="center" />
      <el-table-column label="调整员" prop="adjustUser" min-width="100" align="center" />
      <el-table-column label="成本变动合计" prop="totalAmount" min-width="120" 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:adjust:query']">查看</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['erp:stock:adjust: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="adjustDate">
              <el-date-picker v-model="form.adjustDate" 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="adjustUser">
              <el-input v-model="form.adjustUser" 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="260">
            <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="100" />
          <el-table-column label="物料名称" prop="goodsName" min-width="110" />
          <el-table-column label="入库批次" prop="batchNo" min-width="90" />
          <el-table-column label="仓库" min-width="130">
            <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="88" />
          <el-table-column label="调整基本数量" width="180">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.adjBaseQty"
                :precision="4"
                :disabled="readonly"
                controls-position="right"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="辅助单位" prop="assistantUnit" width="88" />
          <el-table-column label="调整辅助数量" width="180">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.adjAssistQty"
                :precision="4"
                :disabled="readonly"
                controls-position="right"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="单位成本" width="180">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.unitCost"
                :precision="4"
                :min="0"
                :disabled="readonly"
                controls-position="right"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="行成本变动" min-width="110" align="right">
            <template slot-scope="scope">
              <span>{{ lineAmountDisplay(scope.row) }}</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 {
  addStockAdjust,
  delStockAdjust,
  getStockAdjust,
  listStockAdjust,
  listStockAdjustInventoryOptions
} from "@/api/erp/stock";

export default {
  name: "StockWarehouseAdjust",
  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,
        adjustDate: undefined,
        adjustUser: undefined
      },
      form: {},
      rules: {
        adjustDate: [{ required: true, message: "调整日期不能为空", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
    this.loadInventoryOptions();
  },
  methods: {
    getList() {
      this.loading = true;
      listStockAdjust(this.queryParams).then((res) => {
        this.list = res.rows || [];
        this.total = res.total || 0;
        this.loading = false;
      });
    },
    loadInventoryOptions() {
      listStockAdjustInventoryOptions().then((res) => {
        this.inventoryOptions = res.data || [];
      });
    },
    defaultAdjustUser() {
      const u = this.$store.state.user;
      return (u && (u.nickName || u.name)) || "";
    },
    reset() {
      this.form = {
        id: undefined,
        adjustDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
        sheetNo: "",
        adjustUser: this.defaultAdjustUser(),
        remark: "",
        goodsList: [this.buildEmptyGoodsRow()]
      };
      this.resetForm("form");
    },
    buildEmptyGoodsRow() {
      return {
        inventoryId: undefined,
        goodsNum: "",
        goodsName: "",
        batchNo: "",
        warehouseNo: "",
        warehouseName: "",
        baseUnit: "",
        assistantUnit: "",
        adjBaseQty: 1,
        adjAssistQty: 1,
        unitCost: 0,
        remark: ""
      };
    },
    inventoryOptionLabel(item) {
      const wh = item.warehouseNo || "";
      const g = item.goodsNum || "";
      const b = item.batchNo || "";
      return `${wh} | ${g} | 批次:${b}`;
    },
    lineAmountText(row) {
      const a = Number(row.adjBaseQty || 0) * Number(row.unitCost || 0);
      return a.toFixed(4);
    },
    lineAmountDisplay(row) {
      if (row.lineAmount !== undefined && row.lineAmount !== null && row.lineAmount !== "") {
        return Number(row.lineAmount).toFixed(4);
      }
      return this.lineAmountText(row);
    },
    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;
      getStockAdjust(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 || "";
      if (row.adjBaseQty === undefined || row.adjBaseQty === null) {
        row.adjBaseQty = 1;
      }
      if (row.adjAssistQty === undefined || row.adjAssistQty === null) {
        row.adjAssistQty = 1;
      }
    },
    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;
        }
        const b = Number(row.adjBaseQty || 0);
        const a = Number(row.adjAssistQty || 0);
        if (b === 0 && a === 0) {
          this.$modal.msgError(`第${i + 1}行调整基本数量与调整辅助数量不能同时为0`);
          return false;
        }
      }
      return true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid || !this.validateGoodsList()) {
          return;
        }
        const payload = {
          adjustDate: this.form.adjustDate,
          adjustUser: this.form.adjustUser,
          remark: this.form.remark,
          goodsList: (this.form.goodsList || []).map((r) => ({
            inventoryId: r.inventoryId,
            adjBaseQty: Number(r.adjBaseQty || 0),
            adjAssistQty: Number(r.adjAssistQty || 0),
            unitCost: Number(r.unitCost || 0),
            remark: r.remark
          }))
        };
        addStockAdjust(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(() => delStockAdjust(ids)).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    }
  }
};
</script>
