<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入出库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="系统编号" prop="systemNo">
        <el-input
          v-model="queryParams.systemNo"
          placeholder="请输入系统编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库类型" prop="orderTypeId">
        <el-input
          v-model="queryParams.orderTypeId"
          placeholder="请输入入库类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次ID" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.inbound_order_status"
            :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="['inventory:orders: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="['inventory:orders: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="['inventory:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inventory:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="出库单号" align="center" prop="orderId" width="150" />
      <el-table-column label="系统编号" align="center" prop="systemNo" width="150" />
      <el-table-column label="入库类型" align="center" prop="orderTypeId" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inbound_order_type" :value="scope.row.orderTypeId"/>
        </template>
      </el-table-column>
      <el-table-column label="批次ID" align="center" prop="batchCode" width="120" />
      <el-table-column label="仓库ID" align="center" prop="warehouseId" width="100" />
      <el-table-column label="货主ID" align="center" prop="ownerId" width="100" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inbound_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="出库日期" align="center" prop="inboundDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inboundDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="目的地" align="center" prop="destination" width="150" />
      <el-table-column label="计划量" align="center" prop="totalPlannedQuantity" width="100" />
      <el-table-column label="实际量" align="center" prop="totalActualQuantity" width="100" />
      <el-table-column label="总件数" align="center" prop="totalPackages" width="100" />
      <el-table-column label="备注" align="center" prop="remark" width="150" />
      <el-table-column label="是否使用" align="center" prop="isUsed" width="120" />
      <el-table-column label="排序" align="center" prop="sortNo" width="80" />
      <el-table-column label="创建人" align="center" prop="createUserCode" width="150" />
      <el-table-column label="更新人" align="center" prop="updateUserCode" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:orders:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:orders: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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库单号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入出库单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统编号" prop="systemNo">
              <el-input v-model="form.systemNo" placeholder="请输入系统编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" prop="orderTypeId">
              <el-input v-model="form.orderTypeId" placeholder="请输入入库类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次ID" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库ID" prop="warehouseId">
              <el-input v-model="form.warehouseId" placeholder="请输入仓库ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货主ID" prop="ownerId">
              <el-input v-model="form.ownerId" placeholder="请输入货主ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-radio-group v-model="form.orderStatus">
                <el-radio
                  v-for="dict in dict.type.inbound_order_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库日期" prop="inboundDate">
              <el-date-picker clearable
                v-model="form.inboundDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择出库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目的地" prop="destination">
              <el-input v-model="form.destination" placeholder="请输入目的地" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划量" prop="totalPlannedQuantity">
              <el-input v-model="form.totalPlannedQuantity" placeholder="请输入计划量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实际量" prop="totalActualQuantity">
              <el-input v-model="form.totalActualQuantity" placeholder="请输入实际量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总件数" prop="totalPackages">
              <el-input v-model="form.totalPackages" placeholder="请输入总件数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否使用" prop="isUsed">
              <el-input v-model="form.isUsed" placeholder="请输入是否使用" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortNo">
              <el-input v-model="form.sortNo" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建人" prop="createUserCode">
              <el-input v-model="form.createUserCode" placeholder="请输入创建人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新人" prop="updateUserCode">
              <el-input v-model="form.updateUserCode" placeholder="请输入更新人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">库存信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddInventoryItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteInventoryItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="inventoryList" :row-class-name="rowInventoryIndex" @selection-change="handleInventorySelectionChange" ref="inventory">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="货物ID" prop="materialId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.materialId" placeholder="请输入货物ID" />
            </template>
          </el-table-column>
          <el-table-column label="批次ID" prop="batchId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchId" placeholder="请输入批次ID" />
            </template>
          </el-table-column>
          <el-table-column label="仓库ID" prop="warehouseId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.warehouseId" placeholder="请输入仓库ID" />
            </template>
          </el-table-column>
          <el-table-column label="库位ID" prop="locationId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.locationId" placeholder="请输入库位ID" />
            </template>
          </el-table-column>
          <el-table-column label="货主ID" prop="ownerId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ownerId" placeholder="请输入货主ID" />
            </template>
          </el-table-column>
          <el-table-column label="库存数量" prop="quantity" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入库存数量" />
            </template>
          </el-table-column>
          <el-table-column label="锁定数量" prop="lockedQuantity" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lockedQuantity" placeholder="请输入锁定数量" />
            </template>
          </el-table-column>
          <el-table-column label="可用库存" width="150">
            <template slot-scope="scope">
              {{ (Number(scope.row.quantity) || 0) - (Number(scope.row.lockedQuantity) || 0) }}
            </template>
          </el-table-column>
          <el-table-column label="选择数量" prop="selectQty" width="150">
            <template slot-scope="scope">
              <el-input 
                v-model.number="scope.row.selectQty" 
                placeholder="请输入选择数量" 
                @blur="validateSelectQty(scope.row)"
                @input="validateSelectQty(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存状态" prop="inventoryStatus" width="150">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.inventory_status" :value="scope.row.inventoryStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="库存类别" prop="inventoryType" width="150">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.inventory_type" :value="scope.row.inventoryType"/>
            </template>
          </el-table-column>
          <el-table-column label="单位重量" prop="unitWeight" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unitWeight" placeholder="请输入单位重量" />
            </template>
          </el-table-column>
          <el-table-column label="最后入库时间" prop="lastInboundTime" width="150">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.lastInboundTime" type="datetime" placeholder="选择最后入库时间" value-format="yyyy-MM-dd HH:mm:ss" />
            </template>
          </el-table-column>
          <el-table-column label="最后出库时间" prop="lastOutboundTime" width="150">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.lastOutboundTime" type="datetime" placeholder="选择最后出库时间" value-format="yyyy-MM-dd HH:mm:ss" />
            </template>
          </el-table-column>
          <el-table-column label="是否使用" prop="isUsed" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.isUsed" placeholder="请输入是否使用" />
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sortNo" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sortNo" placeholder="请输入排序" />
            </template>
          </el-table-column>
        </el-table>
      </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 { listOrders, getOrders, delOrders, addOrders, updateOrders, listWarehouseInventory } from "@/api/inventory/orders"

export default {
  name: "Orders",
  dicts: ['inbound_order_status', 'outbound_item_status', 'label_color', 'inventory_status', 'inventory_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedInventory: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单主表格数据
      ordersList: [],
      // 库存表格数据
      inventoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        systemNo: null,
        orderTypeId: null,
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        inboundDate: null,
        destination: null,
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        isUsed: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  // 监听仓库ID变化
  watch: {
    'form.warehouseId'(newVal) {
      if (newVal) {
        this.queryWarehouseInventory(newVal)
      } else {
        this.inventoryList = []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询出库单主列表 */
    getList() {
      this.loading = true
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        systemNo: null,
        orderTypeId: null,
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        inboundDate: null,
        destination: null,
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        remark: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null
      }
      this.inventoryList = []
      this.resetForm("form")
    },
    // 查询仓库库存
    queryWarehouseInventory(warehouseId) {
      this.loading = true
      listWarehouseInventory(warehouseId).then(response => {
        this.inventoryList = response.rows || response.data || response
        // 按货物ID分类
        this.groupInventoryByMaterialId()
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.error('查询库存失败:', error)
      })
    },
    // 按货物ID分类库存数据
    groupInventoryByMaterialId() {
      // 这里可以根据需要实现按货物ID分类的逻辑
      // 例如：将同一货物ID的库存数据合并或排序
      this.inventoryList.sort((a, b) => {
        if (a.materialId < b.materialId) return -1
        if (a.materialId > b.materialId) return 1
        return 0
      })
    },
    /** 搜索按钮操作 */
    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) {
      this.reset()
      const id = row.id || this.ids
      getOrders(id).then(response => {
        this.form = response.data
        // 如果有inventoryList直接使用，否则根据仓库ID查询
        if (response.data.inventoryList && response.data.inventoryList.length > 0) {
          this.inventoryList = response.data.inventoryList
          // 按货物ID分类
          this.groupInventoryByMaterialId()
        } else if (response.data.warehouseId) {
          this.queryWarehouseInventory(response.data.warehouseId)
        }
        this.open = true
        this.title = "修改出库单主"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.inventoryList = this.inventoryList
          if (this.form.id != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除出库单主编号为"' + ids + '"的数据项？').then(function() {
        return delOrders(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 库存序号 */
    rowInventoryIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 库存添加按钮操作 */
    handleAddInventoryItem() {
      let obj = {}
      obj.materialId = ""
      obj.batchId = ""
      obj.warehouseId = ""
      obj.locationId = ""
      obj.ownerId = ""
      obj.quantity = ""
      obj.lockedQuantity = ""
      obj.selectQty = ""
      obj.inventoryStatus = ""
      obj.inventoryType = ""
      obj.unitWeight = ""
      obj.lastInboundTime = null
      obj.lastOutboundTime = null
      obj.isUsed = ""
      obj.sortNo = ""
      this.inventoryList.push(obj)
    },
    /** 验证选择数量 */
    validateSelectQty(row) {
      const selectQty = Number(row.selectQty) || 0
      const availableQty = (Number(row.quantity) || 0) - (Number(row.lockedQuantity) || 0)
      
      if (selectQty < 0) {
        this.$message.error('选择数量不能为负数')
        row.selectQty = ''
        return false
      }
      
      if (selectQty > availableQty) {
        this.$message.error('选择数量不能超过可用库存')
        row.selectQty = ''
        return false
      }
      
      return true
    },
    /** 库存删除按钮操作 */
    handleDeleteInventoryItem() {
      if (this.checkedInventory.length == 0) {
        this.$modal.msgError("请先选择要删除的库存数据")
      } else {
        const inventoryList = this.inventoryList
        const checkedInventory = this.checkedInventory
        this.inventoryList = inventoryList.filter(function(item) {
          return checkedInventory.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleInventorySelectionChange(selection) {
      this.checkedInventory = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
