<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="transferDate">
        <el-date-picker v-model="queryParams.transferDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择" style="width: 200px" />
      </el-form-item>
      <el-form-item label="调拨员" prop="transferUser">
        <el-input v-model="queryParams.transferUser" 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:transfer: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:transfer: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="transferDate" min-width="110" align="center" />
      <el-table-column label="调拨单号" prop="sheetNo" min-width="130" align="center" />
      <el-table-column label="调拨员" prop="transferUser" 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:transfer:query']">查看</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['erp:stock:transfer: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="1480px" 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="transferDate">
              <el-date-picker v-model="form.transferDate" 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="transferUser">
              <el-input v-model="form.transferUser" 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="250">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.sourceInventoryId"
                filterable
                placeholder="出库仓+物料+批次"
                style="width: 100%"
                :disabled="readonly"
                @change="onSourceInventoryChange(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="goodsSpec" min-width="90" show-overflow-tooltip />
          <el-table-column label="入库批次" prop="batchNo" min-width="90" />
          <el-table-column label="出库仓库" min-width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.outWarehouseNo }}{{ scope.row.outWarehouseName ? ' / ' + scope.row.outWarehouseName : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="入库仓库" min-width="150">
            <template slot-scope="scope">
              <el-select
                v-if="!readonly"
                v-model="scope.row.inWarehouseNo"
                filterable
                placeholder="请选择"
                style="width: 100%"
                @change="onInWarehouseChange(scope.row)"
              >
                <el-option
                  v-for="w in warehouseOptionsFiltered(scope.row)"
                  :key="w.code"
                  :label="`${w.code} - ${w.name}`"
                  :value="w.code"
                />
              </el-select>
              <span v-else>{{ scope.row.inWarehouseNo }} / {{ scope.row.inWarehouseName }}</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.baseQty"
                :precision="4"
                :min="0"
                :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.assistQty"
                :precision="4"
                :min="0"
                :disabled="readonly"
                controls-position="right"
                style="width: 100%"
              />
            </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 {
  addStockTransfer,
  delStockTransfer,
  getStockTransfer,
  listStockTransfer,
  listStockTransferInventoryOptions,
  listWarehouseOptions
} from "@/api/erp/stock";

export default {
  name: "StockWarehouseTransfer",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      ids: [],
      multiple: true,
      open: false,
      title: "",
      readonly: false,
      inventoryOptions: [],
      warehouseOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sheetNo: undefined,
        transferDate: undefined,
        transferUser: undefined
      },
      form: {},
      rules: {
        transferDate: [{ required: true, message: "调拨日期不能为空", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
    this.loadInventoryOptions();
    this.loadWarehouseOptions();
  },
  methods: {
    getList() {
      this.loading = true;
      listStockTransfer(this.queryParams).then((res) => {
        this.list = res.rows || [];
        this.total = res.total || 0;
        this.loading = false;
      });
    },
    loadInventoryOptions() {
      listStockTransferInventoryOptions().then((res) => {
        this.inventoryOptions = res.data || [];
      });
    },
    loadWarehouseOptions() {
      listWarehouseOptions().then((res) => {
        this.warehouseOptions = res.data || [];
      });
    },
    defaultTransferUser() {
      const u = this.$store.state.user;
      return (u && (u.nickName || u.name)) || "";
    },
    reset() {
      this.form = {
        id: undefined,
        transferDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
        sheetNo: "",
        transferUser: this.defaultTransferUser(),
        remark: "",
        goodsList: [this.buildEmptyGoodsRow()]
      };
      this.resetForm("form");
    },
    buildEmptyGoodsRow() {
      return {
        sourceInventoryId: undefined,
        goodsNum: "",
        goodsName: "",
        goodsSpec: "",
        batchNo: "",
        outWarehouseNo: "",
        outWarehouseName: "",
        inWarehouseNo: "",
        inWarehouseName: "",
        baseUnit: "",
        assistantUnit: "",
        baseQty: 1,
        assistQty: 1,
        remark: ""
      };
    },
    inventoryOptionLabel(item) {
      const wh = item.warehouseNo || "";
      const g = item.goodsNum || "";
      const b = item.batchNo || "";
      return `${wh} | ${g} | 批次:${b}`;
    },
    warehouseOptionsFiltered(row) {
      const outNo = row.outWarehouseNo;
      if (!outNo) {
        return this.warehouseOptions;
      }
      return (this.warehouseOptions || []).filter((w) => w.code !== outNo);
    },
    onSourceInventoryChange(row) {
      const hit = this.inventoryOptions.find((o) => o.inventoryId === row.sourceInventoryId);
      if (!hit) {
        return;
      }
      row.goodsNum = hit.goodsNum || "";
      row.goodsName = hit.goodsName || "";
      row.goodsSpec = hit.goodsSpec || "";
      row.batchNo = hit.batchNo || "";
      row.outWarehouseNo = hit.warehouseNo || "";
      row.outWarehouseName = hit.warehouseName || "";
      row.baseUnit = hit.baseUnit || "";
      row.assistantUnit = hit.assistantUnit || "";
      if (row.baseQty === undefined || row.baseQty === null) {
        row.baseQty = 1;
      }
      if (row.assistQty === undefined || row.assistQty === null) {
        row.assistQty = 1;
      }
      row.inWarehouseNo = "";
      row.inWarehouseName = "";
    },
    onInWarehouseChange(row) {
      const hit = this.warehouseOptions.find((w) => w.code === row.inWarehouseNo);
      row.inWarehouseName = hit ? hit.name : "";
    },
    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();
      this.loadWarehouseOptions();
    },
    handleView(row) {
      this.readonly = true;
      getStockTransfer(row.id).then((res) => {
        this.form = Object.assign({ goodsList: [] }, res.data || {});
        this.open = true;
        this.title = "查看仓库调拨";
      });
    },
    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.sourceInventoryId) {
          this.$modal.msgError(`第${i + 1}行未选择源库存行`);
          return false;
        }
        if (!row.inWarehouseNo) {
          this.$modal.msgError(`第${i + 1}行未选择入库仓库`);
          return false;
        }
        const b = Number(row.baseQty || 0);
        const a = Number(row.assistQty || 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 = {
          transferDate: this.form.transferDate,
          transferUser: this.form.transferUser,
          remark: this.form.remark,
          goodsList: (this.form.goodsList || []).map((r) => ({
            sourceInventoryId: r.sourceInventoryId,
            inWarehouseNo: r.inWarehouseNo,
            baseQty: Number(r.baseQty || 0),
            assistQty: Number(r.assistQty || 0),
            remark: r.remark
          }))
        };
        addStockTransfer(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(() => delStockTransfer(ids)).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    }
  }
};
</script>
