<template>
  <el-dialog
    title="纸张管理"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="900px"
    top="5vh"
    custom-class="paper-management-dialog"
    :append-to-body="true"
    @close="handleDialogClose"
  >
    <div class="paper-management-content">
      <!-- 纸张表单区域 -->
      <div class="form-section">
        <PaperForm
          :paper-data="currentPaper"
          :is-edit-mode="isEditMode"
          :existing-papers="paperList"
          @save="handleSave"
          @cancel="handleCancel"
        />
      </div>

      <!-- 纸张列表区域 -->
      <div class="list-section">
        <PaperList
          :papers="paperList"
          :loading="listLoading"
          :table-height="300"
          @edit="handleEdit"
          @delete="handleDelete"
          @refresh="loadPaperList"
          @toggle-status="handleToggleStatus"
        />
      </div>
    </div>

    <!-- 对话框底部 -->
    <div slot="footer" class="dialog-footer">
      <div class="footer-info">
        <span class="paper-count">
          共 {{ paperList.length }} 个纸张规格
          ({{ activePaperCount }} 个启用)
        </span>
      </div>
      <div class="footer-actions">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import PaperForm from './PaperForm.vue'
import PaperList from './PaperList.vue'
import { getPaperList } from '@/api/labelSetting/paperManagement.js'
import dynamicPaperConfig from '@/utils/paperConfigDynamic.js'

export default {
  name: 'PaperManagementDialog',
  components: {
    PaperForm,
    PaperList
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:visible', 'paper-updated'],
  data() {
    return {
      paperList: [],
      currentPaper: null,
      isEditMode: false,
      listLoading: false,
      dialogVisible: false
    }
  },
  computed: {
    // 启用的纸张数量
    activePaperCount() {
      return this.paperList.filter(paper => paper.isActive).length
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal
        if (newVal) {
          this.initDialog()
        }
      },
      immediate: true
    },
    dialogVisible(newVal) {
      // 当对话框关闭时，通知父组件
      this.$emit('update:visible', newVal)
    }
  },
  beforeDestroy() {
    // 确保组件销毁前清理状态
    this.paperList = []
    this.currentPaper = null
    this.isEditMode = false
    this.listLoading = false
  },
  methods: {
    // 初始化对话框
    async initDialog() {
      await this.loadPaperList()
      this.resetForm()
    },

    // 重置对话框状态
    resetDialog() {
      this.resetForm()
      this.paperList = []
    },

    // 加载纸张列表
    async loadPaperList() {
      try {
        this.listLoading = true

        const { data } = await getPaperList({
          site: this.$store.state.user.site
        })

        if (data.code === 200) {
          this.paperList = data.data || []

          // 更新动态纸张配置缓存
          this.paperList.forEach(paper => {
            dynamicPaperConfig.addPaperToCache(paper)
          })

          console.log('纸张列表加载成功:', this.paperList.length)
        } else {
          this.$message.error(data.msg || '加载纸张列表失败')
          this.paperList = []
        }
      } catch (error) {
        console.error('加载纸张列表失败:', error)
        this.$message.error('加载纸张列表失败，请重试')
        this.paperList = []
      } finally {
        this.listLoading = false
      }
    },

    // 保存纸张
    handleSave(savedPaper) {
      if (this.isEditMode) {
        // 更新模式：更新列表中的纸张
        const index = this.paperList.findIndex(p => p.id === savedPaper.id)
        if (index >= 0) {
          this.$set(this.paperList, index, savedPaper)
        }

        // 更新缓存
        dynamicPaperConfig.addPaperToCache(savedPaper)

        // 重置为新增模式
        this.resetForm()
      } else {
        // 新增模式：添加到列表
        this.paperList.unshift(savedPaper)

        // 更新缓存
        dynamicPaperConfig.addPaperToCache(savedPaper)
      }

      // 通知父组件纸张数据已更新
      this.$emit('paper-updated', {
        action: this.isEditMode ? 'update' : 'create',
        paper: savedPaper
      })
    },

    // 取消操作
    handleCancel() {
      this.resetForm()
    },

    // 编辑纸张
    handleEdit(paper) {
      this.currentPaper = { ...paper }
      this.isEditMode = true

      // 滚动到表单区域
      this.$nextTick(() => {
        const formSection = this.$el.querySelector('.form-section')
        if (formSection) {
          formSection.scrollIntoView({ behavior: 'smooth', block: 'start' })
        }
      })
    },

    // 删除纸张
    handleDelete(deletedPaper) {
      // 从列表中移除
      this.paperList = this.paperList.filter(p => p.id !== deletedPaper.id)

      // 从缓存中移除
      dynamicPaperConfig.removePaperFromCache(deletedPaper.id)

      // 如果删除的是当前编辑的纸张，重置表单
      if (this.isEditMode && this.currentPaper && this.currentPaper.id === deletedPaper.id) {
        this.resetForm()
      }

      // 通知父组件
      this.$emit('paper-updated', {
        action: 'delete',
        paper: deletedPaper
      })
    },

    // 切换纸张状态
    handleToggleStatus(updatedPaper) {
      // 更新列表中的纸张状态
      const index = this.paperList.findIndex(p => p.id === updatedPaper.id)
      if (index >= 0) {
        this.$set(this.paperList, index, updatedPaper)
      }

      // 更新缓存
      dynamicPaperConfig.addPaperToCache(updatedPaper)

      // 通知父组件
      this.$emit('paper-updated', {
        action: 'toggle-status',
        paper: updatedPaper
      })
    },

    // 重置表单
    resetForm() {
      this.currentPaper = null
      this.isEditMode = false
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
    },

    // 对话框关闭事件处理
    handleDialogClose() {
      // 延迟清理状态，避免销毁时机冲突
      this.$nextTick(() => {
        this.resetDialog()
      })
    }
  }
}
</script>

<style scoped>
.paper-management-dialog {
  border-radius: 8px !important;
}

.paper-management-content {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 0;
}

.list-section {
  margin-top: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0 0 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 16px;
}

.footer-info {
  flex: 1;
}

.paper-count {
  font-size: 13px;
  color: #606266;
}

.footer-actions {
  display: flex;
  gap: 8px;
}

/* Element UI 分隔线样式 */
.paper-management-content .el-divider {
  margin: 16px 0;
}

.paper-management-content .el-divider__text {
  background-color: #fff;
  color: #909399;
  font-size: 12px;
}

.paper-management-content .el-divider__text i {
  font-size: 14px;
}

/* 滚动条样式 */
.paper-management-content::-webkit-scrollbar {
  width: 6px;
}

.paper-management-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.paper-management-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.paper-management-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .paper-management-dialog {
    width: 95% !important;
    margin: 0 auto !important;
  }
}

@media (max-width: 768px) {
  .paper-management-dialog {
    width: 98% !important;
    top: 2vh !important;
  }

  .paper-management-content {
    max-height: 80vh;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

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

  .footer-actions {
    justify-content: center;
  }
}
</style>

<!-- 全局样式 -->
<style>
.paper-management-dialog {
  border-radius: 8px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12) !important;
}

.paper-management-dialog .el-dialog__header {
  padding: 16px 20px 12px !important;
  border-bottom: 1px solid #e4e7ed !important;
  background: #fafafa !important;
}

.paper-management-dialog .el-dialog__title {
  font-size: 16px !important;
  font-weight: 600 !important;
  color: #303133 !important;
}

.paper-management-dialog .el-dialog__body {
  padding: 20px !important;
  background: #fff !important;
}

.paper-management-dialog .el-dialog__footer {
  padding: 12px 20px 16px !important;
  border-top: 1px solid #e4e7ed !important;
  background: #fafafa !important;
}
</style>
