<template>
  <div class="app-container">
    <!-- 修改查询表单，将 form 改为 queryParams -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <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="批次ID" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库类型" prop="orderTypeId">
        <el-select v-model="queryParams.orderTypeId" placeholder="请选择入库类型" clearable>
          <el-option 
            v-for="item in inBoundTypeOptions" 
            :key="item.orderTypeId" 
            :label="item.orderTypeName" 
            :value="item.orderTypeId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="入库单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择入库单状态" clearable>
          <el-option 
            v-for="item in inBoundStatusOptions" 
            :key="item.orderStatus" 
            :label="item.orderStatusName" 
            :value="item.orderStatus"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable>
          <el-option 
            v-for="item in orderTypeOptions" 
            :key="item.orderType" 
            :label="item.orderTypeName" 
            :value="item.orderType"
          >
          </el-option>
        </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:inbound: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:inbound: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:inbound: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:inbound:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格保持不变 -->
    <el-table v-loading="loading" :data="inboundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单号" align="center" prop="orderId" />
      <el-table-column label="系统编号" align="center" prop="systemNo" />
      <el-table-column label="入库类型" align="center" prop="orderTypeId" />
      <el-table-column label="批次ID" align="center" prop="batchCode" />
      <el-table-column label="入库单状态" align="center" prop="orderStatus"/>
      <el-table-column label="排序" align="center" prop="sortNo" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['inventory:inbound:confirm']"
          >确认入库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more"
            @click="handleDetail(scope.row)"
            v-hasPermi="['inventory:inbound:view']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:inbound:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:inbound: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="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 表单内容保持不变 -->
        <el-divider content-position="center">入库单基础信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入入库单号" />
            </el-form-item>
            <el-form-item label="入库类型" prop="orderTypeId">
              <el-input v-model="form.orderTypeId" placeholder="请输入入库类型" />
            </el-form-item>
            <el-form-item label="货主ID" prop="ownerId">
              <el-input v-model="form.ownerId" placeholder="请输入货主ID" />
            </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-form-item label="批次ID" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次ID" />
            </el-form-item>
            <el-form-item label="入库日期" prop="inboundDate" lebel-width="100">
              <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-divider content-position="center">入库其他信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="计划量" prop="totalPlannedQuantity">
              <el-input v-model="form.totalPlannedQuantity" placeholder="请输入计划量" />
            </el-form-item>
            <el-form-item label="总件数" prop="totalPackages">
              <el-input v-model="form.totalPackages" placeholder="请输入总件数" />
            </el-form-item>
            <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="实际量" prop="totalActualQuantity">
              <el-input v-model="form.totalActualQuantity" placeholder="请输入实际量" />
            </el-form-item>
            <el-form-item label="负责人" prop="opUserName">
              <el-input v-model="form.opUserName" placeholder="请输入负责人" />
            </el-form-item>
            <el-form-item label="排序" prop="sortNo">
              <el-input v-model="form.sortNo" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </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="handleAddInboundItem"
            >添加明细</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              size="mini" 
              @click="handleDeleteSelectedItems"
            >删除选中</el-button>
          </el-col>
        </el-row> -->
        
        <!-- 入库明细组件 -->
        <InboundItems
          ref="inboundItemsRef"
          v-model="form.inboundOrderItemsList"
          :embedded="true"
          :order-id="form.orderId"
          :show-search-form="false"
          :show-pagination="false"
          :show-toolbar="true"
          :show-action-column="true"
          :show-selection="true"
          :show-add-button="true"
          :show-edit-button="true"
          :show-delete-button="true"
          @selection-change="handleItemsSelectionChange"
          @data-change="handleItemsDataChange"
          @totals-change="handleTotalsChange"
          @item-added="handleItemAdded"
          @row-saved="handleRowSaved"
          @row-deleted="handleRowDeleted"
          @batch-delete="handleBatchDelete"
          @cell-change="handleCellChange"
        />
      </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 { listInbound, getInbound, delInbound, addInbound, updateInbound } from "@/api/inventory/inbound"
import InboundItems from "@/views/inventory/inbound_items/index.vue"

export default {
  name: "Inbound",
  components: {
    InboundItems
  },
  data() {
    return {
      inBoundTypeOptions:[
        { orderTypeId: '1', orderTypeName: '入库类型1' },
        { orderTypeId: '2', orderTypeName: '入库类型2' }
      ],
      inBoundStatusOptions: [
        { orderStatus: '1', orderStatusName: '草稿' },
        { orderStatus: '2', orderStatusName: '已完成' },
        { orderStatus: '3', orderStatusName: '已取消' }
      ],
      orderTypeOptions:[
        { orderType: '1', orderTypeName: '订单类型1' },
        { orderType: '2', orderTypeName: '订单类型2' }
      ],
      // 选中的明细项
      selectedItems: [],
      // 遮罩层 
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库表格数据
      inboundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        orderTypeId: null,
        systemNo: null,
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        orderType: null
      },
      // 表单参数
      form: {
        id: null,
        orderId: null,
        orderTypeId: null,
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        referenceNo: null,
        plannedArrivalDate: undefined,
        actualArrivalDate: undefined,
        totalPlannedQuantity: null,
        totalActualQuantity: null,
        totalPackages: null,
        remark: null,
        opUserName: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null,
        // 明细列表
        inboundOrderItemsList: []
      },
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "入库单号不能为空", trigger: "blur" }
        ],
        orderTypeId: [
          { required: true, message: "入库类型不能为空", trigger: "blur" }
        ],
        systemNo: [
          { required: true, message: "系统编号不能为空", trigger: "blur" }
        ],
        batchCode: [
          { required: true, message: "批次ID不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询入库列表 */
    getList() {
      this.loading = true
      listInbound(this.queryParams).then(response => {
        this.inboundList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    
    /** 搜索按钮操作 */
    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
      getInbound(id).then(response => {
        this.form = response.data
        console.log(this.form)
        // 加载明细数据
        if (response.data.inboundOrderItemsList) {
          this.form.inboundOrderItemsList = response.data.inboundOrderItemsList
        }
        this.open = true
        this.title = "修改入库"
      })
    },
    
    /** 确认入库操作 */
    handleConfirm(row) {
      this.$confirm('确认要入库吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用确认入库API
        // confirmInbound(row.id).then(() => {
        //   this.$modal.msgSuccess("确认成功")
        //   this.getList()
        // })
      })
    },
    
    /** 查看详情 */
    handleDetail(row) {
      // 可以打开一个新的详情页面或者弹窗
      console.log('查看详情:', row)
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除入库编号为"' + ids + '"的数据项？').then(function() {
        return delInbound(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return
        
        // 验证明细表
        const errors = this.$refs.inboundItemsRef ? this.$refs.inboundItemsRef.validate() : []
        if (errors.length > 0) {
          this.$message.error(errors.join('；'))
          return
        }
        
        // 确保明细项数量大于0
        if (!this.form.inboundOrderItemsList || this.form.inboundOrderItemsList.length === 0) {
          this.$message.warning('请至少添加一条入库明细')
          return
        }
        
        // 自动计算总数
        this.calculateTotals()
        
        // 提交数据
        const submitData = {
          ...this.form,
          inboundOrderItemsList: this.form.inboundOrderItemsList.map(item => ({
            ...item,
            orderId: this.form.orderId // 确保明细项有主表ID
          }))
        }
        
        if (this.form.id != null) {
          updateInbound(submitData).then(response => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.getList()
          })
        } else {
          addInbound(submitData).then(response => {
            this.$modal.msgSuccess("新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        orderId: null,
        orderTypeId: null,
        batchCode: null,
        warehouseId: null,
        ownerId: null,
        orderStatus: null,
        referenceNo: null,
        plannedArrivalDate: null,
        actualArrivalDate: null,
        totalPlannedQuantity: 0,
        totalActualQuantity: 0,
        totalPackages: 0,
        remark: null,
        opUserName: null,
        isUsed: null,
        sortNo: null,
        createTime: null,
        createUserCode: null,
        updateTime: null,
        updateUserCode: null,
        inboundOrderItemsList: []
      }
      if (this.$refs.inboundItemsRef) {
        this.$refs.inboundItemsRef.resetEmbeddedData()
      }
      this.resetForm("form")
    },

    
    /** 处理明细项选择变化 */
    handleItemsSelectionChange(selection) {
      this.selectedItems = selection
    },
    
    /** 处理明细数据变化 */
    handleItemsDataChange(items) {
      this.form.inboundOrderItemsList = items
      this.calculateTotals()
    },
    
    /** 处理总数变化 */
    handleTotalsChange(totals) {
      this.form.totalPlannedQuantity = totals.plannedQuantity
      this.form.totalActualQuantity = totals.actualQuantity
      this.form.totalPackages = totals.packages
    },
    
    /** 添加明细项回调 */
    handleItemAdded(item) {
      // 为新项设置orderId
      item.orderId = this.form.orderId
    },
    
    /** 行保存回调 */
    handleRowSaved(row) {
      // 可以在这里添加保存后的逻辑
    },
    
    /** 行删除回调 */
    handleRowDeleted(row) {
      this.$message.success('删除成功')
    },
    
    /** 批量删除回调 */
    handleBatchDelete(ids) {
      this.$message.success(`成功删除 ${ids.length} 项`)
    },
    
    /** 单元格变化回调 */
    handleCellChange({ row, prop, value }) {
      // 可以在这里处理特定字段的变化
      if (prop === 'plannedQuantity' || prop === 'actualQuantity') {
        this.calculateTotals()
      }
    },
    
    /** 计算总数 */
    calculateTotals() {
      if (!this.form.inboundOrderItemsList || this.form.inboundOrderItemsList.length === 0) {
        this.form.totalPlannedQuantity = 0
        this.form.totalActualQuantity = 0
        this.form.totalPackages = 0
        return
      }
      
      const totals = this.form.inboundOrderItemsList.reduce(
        (acc, item) => {
          acc.plannedQuantity += parseFloat(item.plannedQuantity) || 0
          acc.actualQuantity += parseFloat(item.actualQuantity) || 0
          acc.packages += parseFloat(item.plannedPackages) || 0
          return acc
        },
        { plannedQuantity: 0, actualQuantity: 0, packages: 0 }
      )
      
      this.form.totalPlannedQuantity = totals.plannedQuantity
      this.form.totalActualQuantity = totals.actualQuantity
      this.form.totalPackages = totals.packages
    },
    

    
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/inbound/export', {
        ...this.queryParams
      }, `inbound_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
/* 强制允许点击输入框 */
.el-form-item .el-input__inner {
  pointer-events: all !important;
  cursor: auto !important;
}
/* 确保没有遮罩层 */
.el-dialog__wrapper {
  overflow: visible !important;
}

.el-dialog__body {
  overflow: visible !important;
}
</style>