<template>
  <el-dialog
    v-model="dialogVisible"
    :title="issettlement?'领取设备结算单':'续借'"
    width="75%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
  <!--  <div class="title">
        <img src="../../../../../assets/u2855.svg" alt="">
        <span>已领取</span>
    </div> -->
    <div ref="printContent" class="print-container">
      <el-form :model="formData" label-width="110px" label-position="top" class="print-form">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="借用单编号">
              <div class="form-content">{{ formData.application_no }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="借用人">
              <div class="form-content">{{ name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学号/工号">
              <div class="form-content">{{ userCode }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="借用性质">
              <div class="form-content">{{ borrowType }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="借出时间">
              <div class="form-content">{{ formData.expected_start_time }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计归还时间">
              <div class="form-content">{{ formData.expected_end_time }}</div>
            </el-form-item>
          </el-col>

        </el-row>

        <div class="detail-title">借用明细表</div>
        <div class="table-container">
          <table class="detail-table">
            <thead>
              <tr>
                <th width="60">序号</th>
                <th>设备编号</th>
                <th>设备分类</th>
                <th>设备名称</th>
                <th>借用数量</th>
                <th>规格型号</th>
                <th>存放位置</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in filteredItems" :key="index">
                <td>{{ index + 1 }}</td>
                <td>{{ item.device_code }}</td>
                <td>{{ item.device_category_name }}</td>
                <td>{{ item.device_name }}</td>
                <td>{{ item.quantity }}</td>
                <td>{{ item.device_specification }}</td>
                <td>{{ item.device_storage_location || '-' }}</td>
                <td>{{ item.remark || '-' }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="accessories-info">
          <div class="detail-title">配件信息</div>
          <div class="form-content">{{ formData.pre_borrow_accessories || '-' }}</div>
        </div>

        <div class="remark-info">
          <div class="detail-title">备注</div>
          <div class="form-content">{{ formData.remark || '-' }}</div>
        </div>

        <div v-if="isrenew">
          <div style="margin-bottom: 8px; font-weight: bold;">续借时间（天）</div>
          <input
            v-model.number="renewal_days"
            type="number"
            min="1"
            placeholder="请输入续借天数"
            style="width: 100%; border: 1px solid #dcdfe6; padding: 8px; box-sizing: border-box;"
          />

          <div style="margin-bottom: 8px; font-weight: bold;">续借理由</div>
          <textarea
            v-model="return_remark"
            placeholder="请输入续借理由"
            rows="3"
            style="width: 100%;  border: 1px solid #dcdfe6;padding: 8px; resize: vertical; box-sizing: border-box;"
          ></textarea>



        </div>
        <!-- <div v-else>
          <div style="margin-bottom: 8px; font-weight: bold;">续借时间（天）</div>
          <div class="form-content">{{ formData.renewal_days || '-' }}</div>
          <div style="margin-bottom: 8px; font-weight: bold;">续借理由</div>
          <div class="form-content">{{ formData.return_remark || '-' }}</div>
        </div> -->
      </el-form>
    </div>

   

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handlePrint" v-if="issettlement">打印</el-button>
      <el-button type="primary" @click="handlerenew" v-if="isrenew">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import * as api from '../../api';

const props = defineProps<{
  visible: boolean;
  settlementData: any;
  modelValue: any;
}>();

const emit = defineEmits(['update:visible', 'update:modelValue']);

const issettlement = computed(() => props.modelValue?.mode === 'settlement');
const isrenew = computed(() => props.modelValue?.mode === 'renew');

const dialogVisible = ref(false);
const formData = ref<any>({});

const return_remark = ref('')
const renewal_days = ref(1)


watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      // 优先使用 modelValue，如果没有则使用 settlementData
      formData.value = props.modelValue || props.settlementData || {};
    }
  }
);

watch(
  () => props.modelValue,
  (val) => {
    console.log("val:::",val);
    if (val) {
    /* formData.value.app_user_borrower = val.borrower_info.user_code; */
      formData.value = val;
      console.log("formData.value:::",formData.value);
    }
  },
  { immediate: true }
);
const name = computed(() => {
  return formData.value?.app_user_borrower?.name || formData.value?.borrower_info?.name || '';
});
const userCode = computed(() => {
  return formData.value?.app_user_borrower?.user_code || formData.value?.borrower_info?.user_code || '';
});

const borrowType=computed(() => {
  return formData.value?.borrow_type_label || formData.value?.borrow_type || '';
});

interface DeviceItem {
  device:number;
  device_code: string;
  device_category_name: string;
  device_name: string;
  quantity: number;
  device_specification: string;
  device_storage_location?: string;
  remark?: string;
}

const filteredItems = computed(() => {
  return formData.value?.items?.filter((item: DeviceItem | null) => item?.device !== null) || [];
});

const handleClose = () => {
  emit('update:visible', false);
  emit('update:modelValue', formData.value);
};

//续借
async function handlerenew(){
  console.log("filteredItems::",filteredItems.value.length)
  console.log("formData.value::",formData.value)
  for (let i = 0; i < filteredItems.value.length; i++) {
    const item = filteredItems.value[i]

    const payload = {
      // device: item.device, 
      // quantity: item.quantity, 
      renewal_days:renewal_days.value,
      return_remark: return_remark.value, 
      id: formData.value.id 
    }

    try {
      const res = await api.RenewDevice(payload)
      if(res.code===2000){
      console.log(`设备 ${payload.device} 续借申请提交成功`, res)
      emit('update:visible', false);
      emit('update:modelValue', formData.value);
      ElMessage.success("续借申请提交成功");

      }
    } catch (err) {
      console.error(`设备 ${payload.device} 续借申请提交失败`, err)
      ElMessage.success("续借申请提交失败");
    }
  }
}

/* const handlePrint = () => {
  window.print();
}; */
// 定义打印区域的ref
const printContent = ref<HTMLElement | null>(null);

const handlePrint = () => {
  try {
    if (!printContent.value) {
      ElMessage.error('打印区域未找到');
      return;
    }

    // 1. 克隆打印区域内容
    const printElement = printContent.value.cloneNode(true);
    
    // 2. 创建打印专用iframe
    const iframe = document.createElement('iframe');
    iframe.style.position = 'absolute';
    iframe.style.width = '0px';
    iframe.style.height = '0px';
    iframe.style.left = '-9999px';
    document.body.appendChild(iframe);

    // 确保iframe和其document已经准备好
    if (!iframe.contentWindow || !iframe.contentWindow.document) {
      throw new Error('iframe初始化失败');
    }

    const printDocument = iframe.contentWindow.document;
    
    // 3. 添加打印样式
    printDocument.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="utf-8">
          <title>设备借用单打印</title>
          <style>
                          /* 打印样式 */
              @media print {
                body {
                  font-family: Arial, sans-serif;
                  padding: 20px;
                  margin: 0;
                }
                .no-print {
                  display: none !important;
                }
                /* 表单布局优化 */
                .el-form {
                  width: 100%;
                }
                .el-row {
                  display: flex !important;
                  flex-wrap: nowrap !important;
                  margin: 0 -8px;
                }
                .el-col {
                  padding: 0 8px;
                  flex: 1;
                }
                /* 表单项样式 */
                .el-form-item {
                  margin-bottom: 12px;
                  page-break-inside: avoid;
                }
                .el-form-item__label {
                  font-weight: bold;
                  margin-bottom: 4px;
                  display: block;
                }
                .el-form-item__content {
                  line-height: 1.5;
                }
                /* 表格样式优化 */
                table {
                  page-break-inside: auto;
                  width: 100% !important;
                  border-collapse: collapse;
                  margin: 20px 0;
                  table-layout: fixed;
                }
                tr {
                  page-break-inside: avoid;
                  page-break-after: auto;
                }
                th, td {
                  border: 1px solid #000;
                  padding: 8px;
                  text-align: center;
                  word-break: break-all;
                }
                /* 隐藏Element Plus的默认样式 */
                .el-input__inner {
                  border: none !important;
                  padding: 0 !important;
                }
                .el-form--label-top .el-form-item__label {
                  padding: 0;
                }
                /* 标题样式 */
                h2 {
                  text-align: center;
                  margin-bottom: 30px;
                  font-size: 24px;
                }
                /* 明细表标题 */
                .detail-title {
                  font-weight: bold;
                  margin: 20px 0 10px;
                  font-size: 16px;
                }
                /* 配件信息和备注 */
                .accessories-info,
                .remark-info {
                  margin-top: 20px;
                }
                .accessories-info .el-input,
                .remark-info .el-input {
                  width: 100%;
                }
            }
            /* 屏幕预览样式 */
            @media screen {
              body {
                background-color: #fff;
                padding: 20px;
              }
            }
          </style>
        </head>
        <body>
          <h2 style="text-align: center; margin-bottom: 30px;">设备借用单</h2>
        </body>
      </html>
    `);
    
    // 4. 插入内容并添加打印类
    const body = printDocument.body;
    body.appendChild(printElement);
    
    // 5. 添加打印按钮（仅屏幕显示）
    const printBtn = printDocument.createElement('button');
    printBtn.className = 'no-print';
    printBtn.textContent = '打印';
    printBtn.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 10px 20px;
      background: #409EFF;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      z-index: 9999;
    `;
    printBtn.onclick = () => {
      try {
        if (iframe.contentWindow) {
          iframe.contentWindow.print();
        } else {
          throw new Error('打印窗口未准备好');
        }
      } catch (error) {
        console.error('打印过程出错:', error);
        ElMessage.error('打印失败，请重试');
      }
    };
    body.appendChild(printBtn);
    
    // 6. 自动触发打印
    if (iframe.contentWindow) {
      iframe.contentWindow.focus();
      setTimeout(() => {
        try {
          if (iframe.contentWindow) {
            iframe.contentWindow.print();
          } else {
            throw new Error('打印窗口未准备好');
          }
        } catch (error) {
          console.error('打印过程出错:', error);
          ElMessage.error('打印失败，请重试');
        } finally {
          // 确保iframe被移除
          document.body.removeChild(iframe);
        }
      }, 500);
    } else {
      throw new Error('打印窗口未准备好');
    }
  } catch (error) {
    console.error('打印准备过程出错:', error);
    ElMessage.error('打印准备失败，请重试');
  }
};
</script>

<style scoped>
@media print {
  .el-dialog__footer {
    display: none;
  }
}

.print-container {
  padding: 20px;
}

.print-form {
  width: 100%;
}

.form-content {
  min-height: 20px;
  line-height: 20px;
  padding: 4px 0;
}

.detail-title {
  font-weight: bold;
  margin: 20px 0 10px;
  font-size: 16px;
}

.table-container {
  margin: 20px 0;
  width: 100%;
  overflow-x: auto;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.detail-table th,
.detail-table td {
  border: 1px solid #000;
  padding: 8px;
  text-align: center;
  word-break: break-all;
}

.detail-table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

.accessories-info,
.remark-info {
  margin-top: 20px;
}

.form-content {
  /* border: 1px solid #dcdfe6; */
  padding: 8px;
  min-height: 32px;
  line-height: 1.5;
  border-radius: 4px;
}

@media print {
  .print-container {
    padding: 0;
  }

  .form-content {
    border: none;
    padding: 4px 0;
  }

  .el-form-item {
    margin-bottom: 16px !important;
  }

  .el-form-item__label {
    color: #000 !important;
    line-height: 1.5 !important;
  }

  .detail-table th {
    background-color: #fff !important;
  }

  /* 确保分页时表头重复 */
  thead {
    display: table-header-group;
  }

  /* 避免元素被分页截断 */
  tr, .el-form-item, .accessories-info, .remark-info {
    page-break-inside: avoid;
  }
}

.title {
  display: flex;
  justify-content: flex-end;
  position: relative;
}

.title span {
  position: absolute;
  right: 10px;
  bottom: 30%;
  align-self: flex-start;
  padding: 0;
  box-sizing: border-box;
  transform: rotate(315deg);
  font-family: "Impact Bold", "Impact Normal", "Impact", sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 17px;
  color: #F77105;
}
</style> 