<template>
  <el-dialog
    v-model="dialogVisible"
    title="出库单详情"
    width="1200px"
    append-to-body
  >
    <div class="detail-header flex !justify-end">
      <el-button type="success" icon="Document" @click="handlePrint">打印出库单</el-button>
    </div>

      <!-- 出库单基本信息 -->
        <el-descriptions :column="3" border size="small" class="order-info-descriptions">
          <el-descriptions-item label="出库单号">
            {{ orderDetail.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="出库类型">
            <dict-tag :options="outbound_type" :value="orderDetail.orderType" />
          </el-descriptions-item>
          <el-descriptions-item label="仓库">
            {{ orderDetail.warehouseName }}
          </el-descriptions-item>
          <el-descriptions-item label="客户">
            {{ orderDetail.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="总数量">
            {{ orderDetail.totalQuantity }}
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            {{ orderDetail.totalAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="出库人">
            {{ orderDetail.nickName || orderDetail.applicantName }}
          </el-descriptions-item>
          <el-descriptions-item label="出库时间">
            {{ orderDetail.applyTime }}
          </el-descriptions-item>
          <el-descriptions-item label="预计发货日期">
            {{ orderDetail.expectedDeliveryDate }}
          </el-descriptions-item>
          <el-descriptions-item label="出库原因" :span="3">
            {{ orderDetail.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>

      <!-- 明细列表 -->
      <el-divider>出库单明细</el-divider>
      <el-table :data="orderDetail.items" border style="width: 100%" height="400px">
        <el-table-column prop="material.materialCode" label="物资编码" width="150" fixed="left" />
        <el-table-column prop="material.materialName" label="物资名称" width="150" fixed="left" />
        <el-table-column prop="material.specification" label="规格型号" width="150" fixed="left" />
        <el-table-column prop="planQuantity" label="计划数量" width="120" />
        <el-table-column prop="actualQuantity" label="实际数量" width="120" />
        <el-table-column prop="unit" label="计量单位" width="80" />
        <el-table-column prop="unitPrice" label="单价"  />
        <el-table-column prop="amount" label="金额" />
         <el-table-column prop="pickingStatus" label="拣货状态">
              <template #default="scope">
                <dict-tag :options="out_order_status" :value="scope.row.pickingStatus" />
              </template>
            </el-table-column>
        <el-table-column prop="productionDate" label="生产日期" width="120" />
        <el-table-column prop="expirationDate" label="失效日期" width="120" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="handleInventoryFlow(scope.row)" >出库流水</el-button>
        </template>
      </el-table-column>
      </el-table>

          <!-- 出库流水详情对话框 -->
    <BatchDetailDialog v-model="showBatchDialog" ref="batchDetailDialogRef" />
  </el-dialog>
</template>

<script setup name="WmsOutboundOrderDetail">
import { ref, onMounted, getCurrentInstance, watch, computed } from 'vue'
import { getWmsOutboundOrder } from "@/api/ware/wmsOutboundOrder"
import BatchDetailDialog from './BatchDetailDialog.vue'

const { proxy } = getCurrentInstance()

// 字典
const { out_order_status, outbound_type } = proxy.useDict('out_order_status', 'outbound_type')

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  order: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['update:visible'])

// 响应式数据
const orderDetail = ref({
  orderNo: '',
  orderType: '',
  warehouseId: '',
  warehouseName: '',
  areaId: '',
  areaName: '',
  locationId: '',
  locationName: '',
  customerId: '',
  customerName: '',
  totalQuantity: '',
  totalAmount: '',
  applicantName: '',
  applyTime: '',
  expectedDeliveryDate: '',
  actualDeliveryDate: '',
  remark: '',
  items: [],
})

// 出库流水详情对话框状态
const showBatchDialog = ref(false)
// 出库流水详情对话框实例引用
const batchDetailDialogRef = ref(null)

// 计算属性：控制弹框显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})


// 获取出库单详情
function getOrderDetail() {
  if (props.order?.orderId) {
    getWmsOutboundOrder(props.order.orderId).then(response => {
      const data = props.order || {}
      orderDetail.value = { 
        ...props.order, 
        warehouseName: data.warehouse?.warehouseName || '',
        areaName: data.area?.areaName || '',
        locationName: data.location?.locationName || '',
        customerName: data.customerUser?.customerName || '',
        nickName: data.applicantUser?.nickName || '',
        items: response.data?.items || [] 
      }
    })
  }
}

// 打印功能
function handlePrint() {
  const orderData = orderDetail.value
  // 创建打印窗口
  const printWindow = window.open('', '_blank')
  
  // 构建打印内容
  let printContent = `
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>出库单打印</title>
      <style>
        @media print {
          @page {
            margin: 0;
            padding: 0;
           size: landscape; /* 设置为横向 */
          }
        }
        body {
          font-family: Arial, sans-serif;
          margin: 20px;
          padding: 20px;
        }
        h1 {
          text-align: center;
          color: #333;
          margin-bottom: 10px;
        }
        .order-info {
          margin-bottom: 20px;
          padding: 10px;
          border: 1px solid #eee;
          display: grid;
          grid-template-columns: 1fr 1fr 1fr;
          gap: 10px;
        }
        .info-row {
          display: flex;
          margin-bottom: 10px;
          align-items: center;
        }
        .info-label {
          width: 120px;
          font-weight: bold;
          margin-right: 10px;
        }
        .table-container {
          margin-top: 20px;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          margin-top: 10px;
        }
        th, td {
          border: 1px solid #ddd;
          padding: 8px;
          text-align: left;
        }
        th {
          background-color: #f2f2f2;
        }
        .footer {
          margin-top: 30px;
          text-align: right;
        }
      </style>
    </head>
    <body>
      <h1>出库单</h1>
      <div class="order-info">
        <div class="info-row">
          <span class="info-label">出库单号：</span>
          <span>${orderData.orderNo}</span>
        </div>
        <div class="info-row">
          <span class="info-label">出库类型：</span>
          <span>${proxy.selectDictLabel(outbound_type.value, orderData.orderType)}</span>
        </div>
        <div class="info-row">
          <span class="info-label">状态：</span>
          <span>${proxy.selectDictLabel(out_order_status.value, orderData.orderStatus)}</span>
        </div>
        <div class="info-row">
          <span class="info-label">仓库：</span>
          <span>${orderData.warehouse?.warehouseName || orderData.warehouseName || ''}</span>
        </div>
        <div class="info-row">
          <span class="info-label">客户名称：</span>
          <span>${orderData.customerUser?.customerName || orderData.customerName || ''}</span>
        </div>
        <div class="info-row">
          <span class="info-label">联系人：</span>
          <span>${orderData.customerUser?.contactPerson || ''}</span>
        </div>
        <div class="info-row">
          <span class="info-label">联系电话：</span>
          <span>${orderData.customerUser?.contactPhone || ''}</span>
        </div>
        <div class="info-row">
          <span class="info-label">总数量：</span>
          <span>${orderData.totalQuantity}</span>
        </div>
        <div class="info-row">
          <span class="info-label">总金额：</span>
          <span>${orderData.totalAmount}</span>
        </div>
        <div class="info-row">
          <span class="info-label">出库人：</span>
          <span>${orderData.applicantUser?.nickName || orderData.nickName || orderData.applicantName || ''}</span>
        </div>
        <div class="info-row">
          <span class="info-label">出库时间：</span>
          <span>${orderData.applyTime ? new Date(orderData.applyTime).toLocaleDateString() : ''}</span>
        </div>
        <div class="info-row">
          <span class="info-label">预计发货日期：</span>
          <span>${orderData.expectedDeliveryDate ? new Date(orderData.expectedDeliveryDate).toLocaleDateString() : ''}</span>
        </div>
        <div class="info-row">
          <span class="info-label">备注：</span>
          <span>${orderData.remark || ''}</span>
        </div>
      </div>
      
      <div class="table-container">
        <h3>出库单明细</h3>
        <table>
          <thead>
            <tr>
              <th>物资编码</th>
              <th>物资名称</th>
              <th>规格型号</th>
              <th>计划数量</th>
              <th>单位</th>
              <th>单价</th>
              <th>金额</th>
              <th>生产日期</th>
              <th>失效日期</th>
              <th>备注</th>
            </tr>
          </thead>
          <tbody>
  `
  
  // 添加明细数据
  if (orderData.items && orderData.items.length > 0) {
    orderData.items.forEach(detail => {
      printContent += `
        <tr>
          <td>${detail.material?.materialCode || detail.materialCode || ''}</td>
          <td>${detail.material?.materialName || detail.materialName || ''}</td>
          <td>${detail.material?.specification || detail.specification || ''}</td>
          <td>${detail.planQuantity}</td>
          <td>${detail.unit}</td>
          <td>${detail.unitPrice}</td>
          <td>${detail.amount}</td>
          <td>${detail.productionDate ? new Date(detail.productionDate).toLocaleDateString() : ''}</td>
          <td>${detail.expirationDate ? new Date(detail.expirationDate).toLocaleDateString() : ''}</td>
          <td>${detail.remark || ''}</td>
        </tr>
      `
    })
  } else {
    printContent += `
      <tr>
        <td colspan="10">无明细数据</td>
      </tr>
    `
  }
  
  // 完成打印内容
  printContent += `
          </tbody>
        </table>
      </div>
      
      <div class="footer">
        <p>打印时间：${new Date().toLocaleString()}</p>
      </div>
    </body>
    </html>
  `
  
  // 写入打印窗口
  printWindow.document.write(printContent)
  printWindow.document.close()
  
  // 执行打印
  printWindow.print()
  
  // 关闭打印窗口
  printWindow.close()
}

function handleInventoryFlow(row) {
  showBatchDialog.value = true
  batchDetailDialogRef.value.openDialog(row)
}


// 监听弹框显示状态变化
watch(() => props.order, (newVal) => {
  if (newVal) {
    getOrderDetail()
  }
}, { immediate: true, deep: true })
</script>

<style scoped>
.detail-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-card {
  padding: 20px;
}

.order-info-form {
  margin-bottom: 20px;
}
</style>