<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="货主ID" prop="ownerId">
        <el-input
          v-model="queryParams.ownerId"
          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 label="出库日期" prop="inboundDate">
        <el-date-picker clearable
          v-model="queryParams.inboundDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="目的地" prop="destination">
        <el-input
          v-model="queryParams.destination"
          placeholder="请输入目的地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="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" 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="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.number="form.totalPlannedQuantity" placeholder="请输入计划量" type="number" />
            </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.number="form.totalActualQuantity" placeholder="请输入实际量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总件数" prop="totalPackages">
              <el-input v-model.number="form.totalPackages" placeholder="请输入总件数" type="number" />
            </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-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="openDetailDialog">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTableItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table 
          :data="inboundOrderItemsList" 
          :row-class-name="rowInboundOrderItemsIndex" 
          @selection-change="handleInboundOrderItemsSelectionChange" 
          ref="inboundOrderItems"
          border
          style="width: 100%;"
        >
          <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" />
          <el-table-column label="批次ID" prop="batchId" width="150" />
          <el-table-column label="仓库ID" prop="warehouseId" width="150" />
          <el-table-column label="库位ID" prop="locationId" width="150" />
          <el-table-column label="计划数量" prop="plannedQuantity" width="150" />
          <el-table-column label="实际数量" prop="actualQuantity" width="150" />
          <el-table-column label="计划件数" prop="plannedPackages" width="150" />
          <el-table-column label="实际件数" prop="actualPackages" width="150" />
          <el-table-column label="约数" prop="divisor" width="150" />
          <el-table-column label="标签颜色" prop="labelColor" width="150" />
          <el-table-column label="单价" prop="unitPrice" width="150" />
          <el-table-column label="状态" prop="itemStatus" width="150">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.inbound_order_item_status" :value="scope.row.itemStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="收货时间" prop="receivedAt" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.receivedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收货人" prop="receivedBy" width="150" />
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="editDetailItem(scope.row)"
              >编辑</el-button>
            </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>

    <!-- 明细项添加/编辑子组件弹窗（OutboundOrderFormWithItems） -->
    <OutboundOrderFormWithItems
      :title="detailDialogTitle"
      :open="detailDialogOpen"
      :init-form="currentDetailItem"
      @submit="handleDetailSubmit"
      @update:open="detailDialogOpen = $event" 
    />
    
  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/inventory/orders"
// 导入明细子组件
import OutboundOrderFormWithItems from './OutboundOrderFormWithItems.vue'

export default {
  name: "Orders",
  dicts: ['inbound_order_status', 'inbound_order_type', 'inbound_order_item_status'],
  components: {
    OutboundOrderFormWithItems // 注册子组件
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单主表格数据
      ordersList: [],
      // 主弹窗标题
      title: "",
      // 主弹窗是否显示
      open: false,
      // 明细表格数据
      inboundOrderItemsList: [],
      // 选中的明细行
      selectedInboundOrderItems: [],
      // 明细子弹窗相关
      detailDialogOpen: false, // 子弹窗是否显示
      detailDialogTitle: "新增明细项", // 子弹窗标题
      currentDetailItem: {
        materialUuids: '', // 存储物料选择器返回的materialCodes
        materialId: '',
        batchId: '',
        warehouseId: '',
        locationId: '',
        plannedQuantity: '',
        actualQuantity: '',
        plannedPackages: '',
        actualPackages: '',
        divisor: '',
        labelColor: '',
        unitPrice: '',
        itemStatus: 'pending',
        receivedAt: '',
        receivedBy: ''
      }, // 当前编辑的明细项
      isEditDetail: 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: {
        orderId: [{ required: true, message: '请输入出库单号', trigger: 'blur' }],
        warehouseId: [{ required: true, message: '请输入仓库ID', trigger: 'blur' }],
        inboundDate: [{ required: true, message: '请选择出库日期', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // ========== 明细子弹窗相关方法 ==========
    // 打开明细子弹窗（新增）
    openDetailDialog() {
      this.isEditDetail = false
      this.detailDialogTitle = "新增明细项"
      this.currentDetailItem = {
        materialUuids: '', // 初始化materialUuids（接收materialCodes）
        materialId: '',
        batchId: '',
        warehouseId: '',
        locationId: '',
        plannedQuantity: '',
        actualQuantity: '',
        plannedPackages: '',
        actualPackages: '',
        divisor: '',
        labelColor: '',
        unitPrice: '',
        itemStatus: 'pending', // 默认状态
        receivedAt: '',
        receivedBy: ''
      }
      this.detailDialogOpen = true
    },
    // 编辑明细项
    editDetailItem(row) {
      this.isEditDetail = true
      this.detailDialogTitle = "编辑明细项"
      // 兼容materialUuids：优先取row.materialUuids，无则用materialId（适配返回的materialCodes）
      this.currentDetailItem = { 
        ...row,
        materialUuids: row.materialUuids || row.materialId || '' 
      } 
      this.detailDialogOpen = true
    },
    // 接收子组件提交的明细数据（核心修改：适配materialCodes返回格式）
    handleDetailSubmit(details) {
      // 兼容子组件返回格式：如果是materialCodes结构，提取第一个值赋值给materialId
      const formatDetail = (item) => {
        // 处理物料选择器返回的materialCodes数组
        if (item.materialUuids && Array.isArray(item.materialUuids)) {
          item.materialId = item.materialUuids[0] || '' // 单选取第一个值
          item.materialUuids = item.materialUuids[0] || '' // 同步更新materialUuids
        }
        // 兼容子组件返回的原始格式
        return item
      }

      // 统一转为数组处理
      const detailList = Array.isArray(details) ? details : [details]
      // 格式化每条明细的物料字段
      const formattedList = detailList.map(item => formatDetail(item))
      
      if (this.isEditDetail) {
        // 编辑模式：替换原有单条数据
        const editIndex = this.inboundOrderItemsList.findIndex(item => item.index === this.currentDetailItem.index)
        if (editIndex > -1) {
          this.inboundOrderItemsList.splice(editIndex, 1, {
            ...formattedList[0],
            index: this.currentDetailItem.index
          })
        }
        this.$message.success("编辑明细成功")
      } else {
        // 新增模式：批量添加多条明细
        const newDetails = formattedList.map((item, idx) => {
          const newIndex = this.inboundOrderItemsList.length + idx + 1
          return { ...item, index: newIndex }
        })
        this.inboundOrderItemsList = [...this.inboundOrderItemsList, ...newDetails]
        
        // 自动计算主表总数量
        this.calcTotalQuantity()
        
        this.$message.success(`成功新增${newDetails.length}条明细`)
      }
      
      this.detailDialogOpen = false
    },

    // 自动计算主表的计划总量/实际总量/总件数
    calcTotalQuantity() {
      const totalPlanned = this.inboundOrderItemsList.reduce((sum, item) => sum + (Number(item.plannedQuantity) || 0), 0)
      const totalActual = this.inboundOrderItemsList.reduce((sum, item) => sum + (Number(item.actualQuantity) || 0), 0)
      const totalPackages = this.inboundOrderItemsList.reduce((sum, item) => sum + (Number(item.actualPackages) || 0), 0)
      
      this.form.totalPlannedQuantity = totalPlanned
      this.form.totalActualQuantity = totalActual
      this.form.totalPackages = totalPackages
    },

    // ========== 明细表格相关方法 ==========
    // 生成明细表格行序号
    rowInboundOrderItemsIndex({ row, rowIndex }) {
      if (!row.index) row.index = rowIndex + 1
    },
    // 明细表格选择事件
    handleInboundOrderItemsSelectionChange(val) {
      this.selectedInboundOrderItems = val
    },
    // 删除选中的明细行
    deleteTableItem() {
      if (this.selectedInboundOrderItems.length === 0) {
        this.$message.warning('请选择要删除的明细行')
        return
      }
      // 获取选中行索引并倒序删除
      const selectedIndexes = this.selectedInboundOrderItems.map(item => 
        this.inboundOrderItemsList.findIndex(row => row.index === item.index)
      )
      selectedIndexes.sort((a, b) => b - a).forEach(index => {
        this.inboundOrderItemsList.splice(index, 1)
      })
      // 重新更新序号
      this.inboundOrderItemsList.forEach((row, index) => {
        row.index = index + 1
      })
      // 重新计算总数量
      this.calcTotalQuantity()
      this.$message.success('明细行删除成功')
    },

    // ========== 主表格/表单相关方法 ==========
    /** 查询出库单主列表 */
    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.inboundOrderItemsList = []
      this.selectedInboundOrderItems = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    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
        // 如果有明细数据，初始化明细表格
        if (response.data.items) {
          this.inboundOrderItemsList = response.data.items.map((item, index) => ({
            ...item,
            // 兼容materialUuids：适配物料选择器返回的materialCodes格式
            materialUuids: item.materialUuids || item.materialId || '',
            index: index + 1
          }))
          // 计算总数量
          this.calcTotalQuantity()
        }
        this.open = true
        this.title = "修改出库单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          // 组装完整数据（主表+明细）
          const submitData = {
            ...this.form,
            items: this.inboundOrderItemsList.map(item => {
              const { index, ...rest } = item // 剔除序号
              // 提交时确保materialId是单选的物料编码（从materialUuids/原materialId取值）
              rest.materialId = rest.materialUuids || rest.materialId || ''
              return rest
            })
          }
          try {
            if (this.form.id != null) {
              await updateOrders(submitData)
              this.$modal.msgSuccess("修改成功")
            } else {
              await addOrders(submitData)
              this.$modal.msgSuccess("新增成功")
            }
            this.open = false
            this.getList()
          } catch (error) {
            this.$modal.msgError(error.msg || "操作失败")
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除出库单编号为"' + ids + '"的数据项？').then(async () => {
        await delOrders(ids)
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})  
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 弹窗内表单滚动优化 */
.el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}
/* 自定义滚动条 */
.el-dialog__body::-webkit-scrollbar {
  width: 6px;
}
.el-dialog__body::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}
/* 明细表格样式优化 */
.el-table {
  --el-table-row-hover-bg-color: #f8f9fa;
}
</style>