<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:items:add']"
        >新增</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['inventory:items:edit']"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:items:remove']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:items:export']"
        >导出</el-button>
      </template>
    </PageTitle>

    <!-- 页面容器 -->
    <div class="page-container">
      <!-- 查询表单 -->
      <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="货物ID" prop="materialId">
          <el-input
            v-model="queryParams.materialId"
            placeholder="请输入货物ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="批次号" prop="batchCode">
          <el-input
            v-model="queryParams.batchCode"
            placeholder="请输入批次号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库ID" prop="warehouseId">
          <el-input
            v-model="queryParams.warehouseId"
            placeholder="请输入仓库ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="库位ID" prop="locationId">
          <el-input
            v-model="queryParams.locationId"
            placeholder="请输入库位ID"
            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>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table v-loading="loading" :data="itemsList" height="100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="编号" align="center" prop="id" width="100" /> -->
          <el-table-column label="出库单号" align="center" prop="orderId" width="150" />
          <el-table-column label="货物ID" align="center" prop="materialId" width="120" />
          <el-table-column label="批次号" align="center" prop="batchCode" width="150" />
          <el-table-column label="仓库ID" align="center" prop="warehouseId" width="120" />
          <el-table-column label="库位ID" align="center" prop="locationId" width="120" />
          <!-- <el-table-column label="库存ID" align="center" prop="inventoryId" width="120" /> -->
          <el-table-column label="计划数量" align="center" prop="plannedQuantity" width="100" />
          <el-table-column label="实际数量" align="center" prop="actualQuantity" width="100" />
          <el-table-column label="单价" align="center" prop="unitPrice" width="100">
            <template slot-scope="scope">
              {{ formatAmount(scope.row.unitPrice || 0) }}
            </template>
          </el-table-column>
           <el-table-column label="金额" align="center" prop="amount" width="100">
            <template slot-scope="scope">
              {{ formatAmount(scope.row.amount || 0) }}
            </template>
          </el-table-column>
         
          <el-table-column label="约数" align="center" prop="divisor" width="80" />
          <el-table-column label="标签颜色" align="center" prop="labelColor" width="100">
          <template slot-scope="scope">
              <dict-tag v-if="dict.type.label_color" :options="dict.type.label_color" :value="scope.row.labelColor"/>
             </template>
          </el-table-column>
          <el-table-column label="凭证号" align="center" prop="voucherNumber" width="150" />
          <el-table-column label="明细状态" align="center" prop="itemStatus" width="100">
            <template slot-scope="scope">
              <dict-tag v-if="dict.type.outbound_item_status" :options="dict.type.outbound_item_status" :value="scope.row.itemStatus"/>
              </template>
          </el-table-column>
          <el-table-column label="发货时间" align="center" prop="shippedAt" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.shippedAt, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发货方" align="center" prop="shippedBy" width="120" />
          <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDetail(scope.row)"
                v-hasPermi="['inventory:items:view']"
              >详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改出库单明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body class="scrollable-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="出库单号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入出库单号" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货物ID" prop="materialId">
              <el-input v-model="form.materialId" placeholder="请输入货物ID" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次号" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库ID" prop="warehouseId">
              <el-input v-model="form.warehouseId" placeholder="请输入仓库ID" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="库位ID" prop="locationId">
              <el-input v-model="form.locationId" placeholder="请输入库位ID" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存ID" prop="inventoryId">
              <el-input v-model="form.inventoryId" placeholder="请输入库存ID" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="出库单ID" prop="outboundOrderId">
              <el-input v-model="form.outboundOrderId" placeholder="请输入出库单ID" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                v-model="form.unitPrice"
                :min="0"
                size="small"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="计划数量" prop="plannedQuantity">
              <el-input-number
                v-model="form.plannedQuantity"
                :min="0"
                size="small"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际数量" prop="actualQuantity">
              <el-input-number
                v-model="form.actualQuantity"
                :min="0"
                size="small"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="约数" prop="divisor">
              <el-input-number
                v-model="form.divisor"
                :min="0"
                size="small"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签颜色" prop="labelColor">
              <el-input-number
                v-model="form.labelColor"
                :min="0"
                size="small"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="凭证号" prop="voucherNumber">
              <el-input v-model="form.voucherNumber" placeholder="请输入凭证号" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="明细状态" prop="itemStatus">
              <el-select v-model="form.itemStatus" placeholder="请选择明细状态" style="width: 100%" :disabled="isDetailMode">
               
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="发货时间" prop="shippedAt">
              <el-date-picker
                v-model="form.shippedAt"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择发货时间"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货方" prop="shippedBy">
              <el-input v-model="form.shippedBy" placeholder="请输入发货方" :readonly="isDetailMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="数据状态" prop="isUsed">
              <el-select v-model="form.isUsed" placeholder="请选择数据状态" style="width: 100%" :disabled="isDetailMode">
                <el-option label="使用中" value="1" />
                <el-option label="已删除" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortNo">
              <el-input-number
                v-model="form.sortNo"
                :min="0"
                size="small"
                style="width: 100%"
                :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" :readonly="isDetailMode" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isDetailMode" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItems, getItems, delItems, addItems, updateItems,getStatistics } from "@/api/inventory/items"
import PageTitle from "@/components/PageTitle"

export default {
  name: "OutboundOrderItems",
  dicts: ['outbound_item_status', 'inbound_order_type', 'inbound_order_item_status', 'label_color'],
  components: {
    PageTitle
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库单明细表格数据
      itemsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为详情模式
      isDetailMode: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        materialId: null,
        batchCode: null,
        warehouseId: null,
        locationId: null,
        voucherNumber: null,
        itemStatus: null,
        labelColor: null
      },
      // 表单参数
      form: {
        id: null,
        orderId: null,
        materialId: null,
        batchCode: null,
        warehouseId: null,
        locationId: null,
        inventoryId: null,
        outboundOrderId: null,
        unitPrice: 0,
        plannedQuantity: 0,
        actualQuantity: 0,
        divisor: 0,
        labelColor: 0,
        voucherNumber: null,
        itemStatus: 1,
        shippedAt: null,
        shippedBy: null,
        isUsed: 1,
        sortNo: 0,
        remark: null,
        createUserCode: null,
        updateUserCode: null
      },
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "出库单号不能为空", trigger: "blur" }
        ],
        materialId: [
          { required: true, message: "货物ID不能为空", trigger: "blur" }
        ],
        itemStatus: [
          { required: true, message: "明细状态不能为空", trigger: "change" }
        ],
        isUsed: [
          { required: true, message: "数据状态不能为空", trigger: "change" }
        ]
      },
      // 选中行
      selectedRows: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询出库单明细列表 */
    getList() {
      this.loading = true
      getStatistics(this.queryParams).then(response => {
        this.itemsList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 获取明细状态样式类型 */
    getItemStatusType(status) {
      switch (status) {
        case 1: return 'info' // 待发货
        case 2: return 'warning' // 部分发货
        case 3: return 'success' // 已完成
        default: return 'info'
      }
    },
    /** 获取明细状态名称 */
    getItemStatusName(status) {
      switch (status) {
        case 1: return '待发货'
        case 2: return '部分发货'
        case 3: return '已完成'
        default: return '未知'
      }
    },
    /** 格式化金额，保留2位小数 */
    formatAmount(amount) {
      if (amount === null || amount === undefined || isNaN(amount)) {
        return '0.00'
      }
      return parseFloat(amount).toFixed(2)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectedRows = selection
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isDetailMode = false
      this.open = true
      this.title = "新增出库单明细"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row) {
        if (this.selectedRows.length === 1) {
          row = this.selectedRows[0]
        } else {
          this.$message.warning("请选择一个出库单明细进行修改！")
          return
        }
      }
      this.reset()
      const id = row.id || this.ids[0]
      getItems(id).then(response => {
        this.form = response.data
        this.isDetailMode = false
        this.open = true
        this.title = "修改出库单明细"
      })
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      if (!row) {
        this.$message.warning("请选择一个出库单明细！")
        return
      }
      this.reset()
      this.isDetailMode = true
      const id = row.id
      getItems(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "出库单明细详情"
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm(`是否确认删除编号为"${ids}"的出库单明细？`, '提示', {
        type: 'warning'
      }).then(() => {
        return delItems(ids)
      }).then(() => {
        this.getList()
        this.$message.success("删除成功")
      }).catch(() => {})
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return

        // 提交数据
        if (this.form.id != null) {
          updateItems(this.form).then(response => {
            this.$message.success("修改成功")
            this.open = false
            this.getList()
          })
        } else {
          addItems(this.form).then(response => {
            this.$message.success("新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        orderId: null,
        materialId: null,
        batchCode: null,
        warehouseId: null,
        locationId: null,
        inventoryId: null,
        outboundOrderId: null,
        unitPrice: 0,
        plannedQuantity: 0,
        actualQuantity: 0,
        divisor: 0,
        labelColor: 0,
        voucherNumber: null,
        itemStatus: 1,
        shippedAt: null,
        shippedBy: null,
        isUsed: 1,
        sortNo: 0,
        remark: null,
        createUserCode: null,
        updateUserCode: null
      }
      this.isDetailMode = false
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    /** 导出出库单明细数据 */
    handleExport() {
      const params = { ...this.queryParams }
      delete params.pageNum
      delete params.pageSize

      this.download('inventory/items/export', {
        ...params
      }, `出库单明细数据_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 页面容器样式 */
.page-container {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 140px);
  min-height: 600px;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  min-height: 0;
  margin-top: 16px;
  display: flex;
  flex-direction: column;
}

.scrollable-dialog .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
  padding: 20px;
}

.w20 {
  width: 120px;
}
</style>