<template>
  <Dialog v-model="dialogVisible" title="预览" width="60%" scroll>
    <div class="materialsOut-print" id="printArea" v-loading="loading">
      <div class="title">物资出库单</div>

      <div class="meta-row">
        <div class="meta-item"><span class="label">申领科室:</span><span class="value">{{ detail.outDeptName || '' }}</span></div>
        <div class="meta-item"><span class="label">出库时间:</span><span class="value">{{ detail.orderDate || '' }}</span></div>
        <div class="meta-item"><span class="label">出库单号:</span><span class="value">{{ detail.orderNo || '' }}</span></div>
      </div>

      <div class="meta-row">
        <div class="meta-item"><span class="label">出库部门:</span><span class="value"></span></div>
        <div class="meta-item"><span class="label">摘要:</span><span class="value"></span></div>
      </div>

      <table class="items-table">
        <thead>
          <tr>
            <th class="col-idx">序号</th>
            <th class="col-no">编号</th>
            <th class="col-name">品名</th>
            <th class="col-spec">规格</th>
            <th class="col-unit">单位</th>
            <th class="col-qty">数量</th>
            <th class="col-price">进货价</th>
            <th class="col-amount">进货金额</th>
            <th class="col-remark">备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(it, idx) in (detail.items || [])" :key="it.id ?? idx">
            <td class="text-center">{{ idx + 1 }}</td>
            <td>{{ it.materialNumber || '' }}</td>
            <td>{{ it.materialName || '' }}</td>
            <td>{{ it.specification || '' }}</td>
            <td class="text-center">{{ it.materialUnit || '' }}</td>
            <td class="text-center">{{ it.quantity ?? '' }}</td>
            <td class="text-right">{{ (it.inUnitPrice ?? '') }}</td>
            <td class="text-right">{{ (Number(it.amount ?? 0)).toFixed(2) }}</td>
            <td></td>
          </tr>
          <tr v-if="!(detail.items && detail.items.length)">
            <td colspan="9" class="empty">暂无明细</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="7" class="text-right">合计</td>
            <td class="text-right">{{ totalAmount().toFixed(2) }}</td>
            <td></td>
          </tr>
        </tfoot>
      </table>

      <div class="sign-row">
        <div class="sign-item"><span class="label">会计:</span><span class="line"></span></div>
        <div class="sign-item"><span class="label">保管:</span><span class="line"></span></div>
        <div class="sign-item"><span class="label">领用人:</span><span class="line">{{ detail.outUser || '' }}</span></div>
        <div class="sign-item"><span class="label">审核:</span><span class="line"></span></div>
        <div class="sign-item"><span class="label">制表:</span><span class="value">{{ detail.creator || '' }}</span></div>
      </div>
    </div>
    <template #footer>
      <el-button @click="handleClosed">取消</el-button>
      <el-button type="primary" v-print="print">打印</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import { getMaterialOutboundDetail } from '@/api/material/stockInAndOut'

const dialogVisible = ref(false)
const loading = ref(false)

type OutboundItem = {
  id?: number
  orderId?: number
  materialId?: number
  materialNumber?: string
  materialName?: string
  materialUnit?: string
  refInboundItemId?: number
  refInOrderNo?: string
  quantity?: number
  inUnitPrice?: number
  saleUnitPrice?: number
  amount?: number
  produceDate?: string
  latestAvailableQty?: number
  refInStoreId?: number
  refInStoreName?: string
  specification?: string
}

type OutboundDetail = {
  id?: number
  orderNo?: string
  status?: number
  orderDate?: string
  outDeptId?: number
  outDeptName?: string
  outUser?: string
  outReason?: string
  remark?: string
  tenantId?: number
  createTime?: string
  updateTime?: string
  creator?: string
  updater?: string
  auditor?: string
  auditResult?: string
  auditTime?: string
  auditRemark?: string
  items?: OutboundItem[]
}

const detail = reactive<OutboundDetail>({
  items: []
})

const totalAmount = () => {
  const list = detail.items || []
  return list.reduce((sum, it) => sum + Number(it?.amount ?? 0), 0)
}

const handleClosed = () => {
  dialogVisible.value = false
}

const open = async (id: number | string) => {
  dialogVisible.value = true
  loading.value = true
  try {
    const res: any = await getMaterialOutboundDetail(id)
    const data: OutboundDetail = res?.data ?? res ?? {}

    Object.assign(detail, {
      ...data,
      items: Array.isArray(data?.items) ? data.items : []
    })

    await nextTick()
  } finally {
    loading.value = false
  }
}

// 打印
const print = {
  id: 'printArea',
  extraCss: '',
  popTitle: '',
  extraHead: '',
  preview: false,
  previewTitle: '出库单预览',
  previewPrintBtnLabel: '预览结束，开始打印',
  zIndex: 20002,
  previewBeforeOpenCallback() {
    console.log('正在加载预览窗口！')
  },
  previewOpenCallback() {
    console.log('已经加载完预览窗口，预览打开了！')
  },
  beforeOpenCallback() {
    console.log('开始打印之前！')
  },
  openCallback() {
    console.log('执行打印了！')
  },
  closeCallback() {
    console.log('关闭了打印工具！')
  },
  clickMounted() {
    console.log('点击v-print绑定的按钮了！')
  },
  standard: ''
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

</script>
<style media="print" lang="scss">
@page {
  margin: 3mm;
  margin-top: 2cm;
  margin-bottom: 2cm;
}
@media print {
  html {
    background-color: #ffffff;
    height: auto;
    margin: 0;
  }
  .synthetic-ability-print {
    padding: 10px 15px;
  }
}
</style>
<style lang="scss" scoped>
.materialsOut-print {
  padding: 10px 15px;
  color: #000;
}

.title {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
}

.meta-row {
  display: flex;
  gap: 10px;
  margin-bottom: 6px;
}

.meta-item {
  flex: 1;
  display: flex;
  align-items: center;
  min-height: 22px;
}

.label {
  width: 90px;
  flex: 0 0 90px;
}

.value {
  flex: 1;
  border-bottom: 1px solid #000;
  padding: 0 6px;
  min-height: 18px;
}

.items-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.items-table th,
.items-table td {
  border: 1px solid #000;
  padding: 6px 6px;
  font-size: 12px;
}

.text-center {
  text-align: center;
}

.text-right {
  text-align: right;
}

.empty {
  text-align: center;
  height: 60px;
}

.sign-row {
  display: flex;
  margin-top: 18px;
  gap: 20px;
}

.sign-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.line {
  flex: 1;
  border-bottom: 1px solid #000;
  margin-left: 6px;
  height: 18px;
}
</style>