<template>
    <div class="h-full">
      <div class="modal-header">
        <h2 class="modal-title">编辑合同产品信息</h2>
        <div class="modal-actions">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleClose">关闭</el-button>
        </div>
      </div>
      
      <div class="grid grid-cols-2 gap-2 h-full">
        <!-- 左侧PDF显示区域 -->
        <div class="col-span-1 h-full overflow-auto">
          <embed :src="pdfUrl" type="application/pdf" width="100%" height="100%" class="pdf-embed" />
        </div>
        
        <!-- 右侧编辑表单区域 -->
        <div class="h-full overflow-auto">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            class="edit-form"
          >
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="formData.brand" placeholder="请输入品牌" />
            </el-form-item>
            <el-form-item label="型号(版本号)" prop="versionStr">
              <el-input v-model="formData.versionStr" placeholder="请输入型号" />
            </el-form-item>
            <el-form-item label="CPU型号" prop="cpuModel">
              <el-input v-model="formData.cpuModel" placeholder="请输入CPU型号" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-input v-model="formData.type" placeholder="请输入类型" />
            </el-form-item>
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number 
                v-model="formData.unitPrice" 
                :precision="0" 
                :step="1" 
                :min="0"
                placeholder="请输入单价"
              />
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input-number 
                v-model="formData.quantity" 
                :min="0"
                placeholder="请输入数量"
              />
            </el-form-item>
            <el-form-item label="总价" prop="totalPrice">
              <el-input-number 
                v-model="formData.totalPrice" 
                :precision="0" 
                :step="1" 
                :min="0"
                placeholder="总价"
                disabled
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted, nextTick, watch } from 'vue';
  import { ElMessage } from 'element-plus';
  import { updateContractualProductInfo } from '@/api/contractReview/ContractualProductInfo';
  import { getPdfFile } from '@/api/contractReview/JyjcontractualTaskBatch';
  
  defineOptions({ name: 'ContractualProductInfoEdit' });
  
  // 定义Props
  const props = defineProps({
    record: {
      type: Object,
      required: true,
      default: () => ({})
    }
  });
  
  // 定义Emits
  const emit = defineEmits(['close', 'success']);
  
  // 表单数据和校验规则
  const formRef = ref();
  const formData = reactive({
    id: '',
    taskId: '',
    fileName: '',
    unitName: '',
    brand: '',
    versionStr: '',
    cpuModel: '',
    type: '',
    unitPrice: 0,
    quantity: 0,
    totalPrice: 0
  });
  
  // 校验规则
  const rules = {
    brand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],
  };
  
  // PDF文件URL
  const pdfUrl = ref<string>('');
  const loading = ref(false);
  
  // 监听单价和数量的变化，计算总价
  watch(
    () => [formData.unitPrice, formData.quantity],
    ([newUnitPrice, newQuantity]) => {
      formData.totalPrice = newUnitPrice * newQuantity;
    },
    { immediate: true }
  );
  
  // 初始化数据
  onMounted(async () => {
    if (props.record) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        if (props.record[key] !== undefined) {
          formData[key] = props.record[key];
        }
      });
  
      // 尝试加载PDF文件
      try {
        if (props.record.id) {
          const response = await getPdfFile(props.record.taskId);
          if (response instanceof Blob) {
            pdfUrl.value = URL.createObjectURL(response);
            
            // 文件加载完成后自动适应宽度
            nextTick(() => {
              setTimeout(() => {
                // 如果需要特殊处理PDF显示可以在这里添加
              }, 500);
            });
          } else {
            console.error('获取PDF文件失败：返回的不是Blob对象');
          }
        }
      } catch (error) {
        console.error('加载PDF文件失败:', error);
      }
    }
  });
  
  // 提交表单
  const handleSubmit = async () => {
    try {
      await formRef.value.validate();
      
      loading.value = true;
      
      // 调用API保存数据
      const res = await updateContractualProductInfo(formData);
      
      if (res.code === 200) {
        ElMessage.success('保存成功');
        emit('success', formData);
        handleClose();
      } else {
        ElMessage.error(res.msg || '保存失败');
      }
    } catch (error) {
      console.error('提交失败', error);
      ElMessage.error('表单验证失败，请检查输入');
    } finally {
      loading.value = false;
    }
  };
  
  // 关闭页面
  const handleClose = () => {
    emit('close');
  };
  </script>
  
  <style scoped>
  /* 头部样式 */
  .modal-header {
    overflow: hidden;
    padding: 16px 24px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .modal-title {
    float: left;
    margin: 0;
    font-size: 18px;
    color: #303133;
  }
  
  .modal-actions {
    float: right;
  }
  
  .modal-actions .el-button {
    margin-left: 12px;
  }
  
  /* 确保embed标签占满整个容器 */
  .pdf-embed {
    display: block;
    height: calc(100vh - 70px) !important; /* 减去头部的高度 */
    border: none;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  /* 使网格容器填充整个可用空间 */
  .grid {
    height: calc(100vh - 70px); /* 减去头部的高度 */
    overflow: hidden;
  }
  
  /* 确保两列都有适当的滚动行为 */
  .col-span-1 {
    height: 100%;
    overflow-y: auto;
  }
  
  /* 表单样式 */
  .edit-form {
    padding: 20px;
  }
  
  /* 全局高度 */
  .h-full {
    height: 100%;
  }
  </style>