<template>
  <el-dialog
    title="调查表填报"
    :visible.sync="dialogVisible"
    width="90%"
    :close-on-click-modal="false"
    :show-close="true"
    append-to-body
    :modal="false"
    @close="handleClose"
  >
    <!-- 操作按钮 -->
    <div class="action-buttons" style="margin-bottom: 20px">
      <el-button type="primary" :disabled="isViewMode" @click="handleAdd">
        <i class="el-icon-plus"></i>
        新增
      </el-button>
      <el-button
        type="danger"
        :disabled="isViewMode || selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        <i class="el-icon-delete"></i>
        删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="paginatedTableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <!-- 复选框列 -->
      <el-table-column type="selection" width="55" align="center" />

      <!-- 序号列 -->
      <el-table-column prop="seq" label="序号" width="80" align="center">
        <template slot-scope="scope">
          {{ getRowIndex(scope.$index) }}
        </template>
      </el-table-column>

      <!-- 监审期间列 -->
      <el-table-column
        prop="auditPeriod"
        label="监审期间"
        min-width="150"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.auditPeriod }}
        </template>
      </el-table-column>

      <!-- 填报时间列 -->
      <el-table-column
        prop="fillTime"
        label="填报时间"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.fillTime }}
        </template>
      </el-table-column>

      <!-- 最后修改时间列 -->
      <el-table-column
        prop="lastModifyTime"
        label="最后修改时间"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.lastModifyTime }}
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            :disabled="isViewMode"
            @click="handleViewDetail(scope.row)"
          >
            详情
          </el-button>
          <el-button
            type="text"
            size="small"
            :disabled="isViewMode"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            :disabled="isViewMode"
            style="color: #f56c6c"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="total, prev, pager, next, jumper"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />

    <!-- 详情/编辑弹窗 -->
    <el-dialog
      :title="detailDialogTitle"
      :visible.sync="detailDialogVisible"
      width="90%"
      :close-on-click-modal="false"
      append-to-body
      :modal="false"
    >
      <div>
        <!-- <div style="margin-bottom: 20px; padding: 10px; background: #f5f7fa">
          <p><strong>监审期间：</strong>{{ currentRow.auditPeriod }}</p>
          <p><strong>填报时间：</strong>{{ currentRow.fillTime }}</p>
          <p><strong>最后修改时间：</strong>{{ currentRow.lastModifyTime }}</p>
        </div> -->
        <!-- 固定资产表格 -->
        <fixed-assets-table
          ref="fixedAssetsTable"
          :table-items="localTableItems"
          :saved-data="currentRow ? currentRow.data || {} : {}"
          :is-view-mode="!isEditMode"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isEditMode" type="primary" @click="handleSaveDetail">
          保存
        </el-button>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
    </div> -->
  </el-dialog>
</template>

<script>
  import { Message, MessageBox } from 'element-ui'
  import FixedAssetsTable from './FixedAssetsTable.vue'

  export default {
    name: 'DynamicTableDialog',
    components: {
      FixedAssetsTable,
    },
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      surveyData: {
        type: Object,
        default: () => ({}),
      },
      // 表格数据
      tableData: {
        type: Array,
        default: () => [],
      },
      // 表格项配置（用于详情/编辑时显示表单）
      tableItems: {
        type: Array,
        default: () => [],
      },
      // 是否查看模式
      isViewMode: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        dialogVisible: false,
        // 表格数据
        localTableData: [],
        // 选中的行
        selectedRows: [],
        // 分页配置
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 详情/编辑弹窗
        detailDialogVisible: false,
        detailDialogTitle: '详情',
        currentRow: null,
        isEditMode: false,
        // 表格项配置（本地）
        localTableItems: [],
      }
    },
    computed: {
      // 分页后的表格数据
      paginatedTableData() {
        const start =
          (this.pagination.currentPage - 1) * this.pagination.pageSize
        const end = start + this.pagination.pageSize
        return this.localTableData.slice(start, end)
      },
    },
    watch: {
      visible: {
        handler(newVal) {
          this.dialogVisible = newVal
          if (newVal) {
            this.initTableData()
            this.initTableItems()
          }
        },
        immediate: true,
      },
      tableItems: {
        handler(newVal) {
          this.initTableItems()
        },
        deep: true,
      },
      dialogVisible(newVal) {
        if (!newVal) {
          this.$emit('update:visible', false)
        }
      },
      tableData: {
        handler(newVal) {
          this.initTableData()
        },
        deep: true,
      },
    },
    methods: {
      // 初始化表格项配置
      initTableItems() {
        // if (this.tableItems && this.tableItems.length > 0) {
        //   this.localTableItems = [...this.tableItems]
        // } else {
        //   // 使用假数据
        //   this.localTableItems = this.getMockTableItems()
        // }
        this.localTableItems = this.getMockTableItems()
      },
      // 获取假数据表格项配置（用于测试）
      getMockTableItems() {
        return [
          {
            id: 'I',
            itemName: '房屋建筑物',
            isCategory: true,
            categorySeq: 'I',
            children: [
              {
                id: 'I-1',
                itemName: '办公用房',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'I-2',
                itemName: '教保用房',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'I-3',
                itemName: '幼儿宿舍用房',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'I-4',
                itemName: '其它',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          {
            id: 'II',
            itemName: '交通运输工具',
            isCategory: true,
            categorySeq: 'II',
            children: [
              {
                id: 'II-1',
                itemName: '车辆',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          {
            id: 'III',
            itemName: '教保专用设备',
            isCategory: true,
            categorySeq: 'III',
            children: [
              {
                id: 'III-1',
                itemName: '电教',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'III-2',
                itemName: '文体',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          {
            id: 'IV',
            itemName: '办公设备',
            isCategory: true,
            categorySeq: 'IV',
            children: [
              {
                id: 'IV-1',
                itemName: '电脑',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          {
            id: 'V',
            itemName: '其它固定资产',
            isCategory: true,
            categorySeq: 'V',
            children: [
              {
                id: 'V-1',
                itemName: '空调',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-2',
                itemName: '家电',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-3',
                itemName: '供水系统',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-4',
                itemName: '洗涤用具',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-5',
                itemName: '家具',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-6',
                itemName: '炊事用具',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-7',
                itemName: '其它',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
        ]
      },
      // 初始化表格数据
      initTableData() {
        if (this.tableData && this.tableData.length > 0) {
          this.localTableData = [...this.tableData]
        } else {
          // 使用假数据
          this.localTableData = this.getMockTableData()
        }
        this.pagination.total = this.localTableData.length
        this.pagination.currentPage = 1
      },
      // 获取假数据（用于测试）
      getMockTableData() {
        const currentDate = new Date()
        const formatDateTime = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        }

        const data = []
        const currentYear = currentDate.getFullYear()

        // 生成25条假数据
        for (let i = 0; i < 25; i++) {
          const year = currentYear - i
          const fillDate = new Date(currentDate)
          fillDate.setDate(fillDate.getDate() - i)
          const modifyDate = new Date(fillDate)
          modifyDate.setHours(modifyDate.getHours() + 1)

          data.push({
            id: `row-${i + 1}`,
            seq: i + 1,
            auditPeriod: `${year}`,
            fillTime: formatDateTime(fillDate),
            lastModifyTime: formatDateTime(modifyDate),
            data: {}, // 存储具体的填报数据
          })
        }

        return data
      },
      // 获取行索引（考虑分页）
      getRowIndex(index) {
        return (
          (this.pagination.currentPage - 1) * this.pagination.pageSize +
          index +
          1
        )
      },
      // 选择变化
      handleSelectionChange(selection) {
        this.selectedRows = selection
      },
      // 新增
      handleAdd() {
        const currentYear = new Date().getFullYear()
        const currentDate = new Date()
        const formatDateTime = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        }

        const newRow = {
          id: `row-${Date.now()}`,
          seq: this.localTableData.length + 1,
          auditPeriod: String(currentYear),
          fillTime: formatDateTime(currentDate),
          lastModifyTime: formatDateTime(currentDate),
          data: {},
        }

        this.localTableData.unshift(newRow)
        this.pagination.total = this.localTableData.length
        this.pagination.currentPage = 1

        // 打开编辑弹窗
        this.currentRow = newRow
        this.isEditMode = true
        this.detailDialogTitle = '编辑'
        this.detailDialogVisible = true

        Message.success('新增成功，请填写数据')
      },
      // 批量删除
      handleBatchDelete() {
        if (this.selectedRows.length === 0) {
          Message.warning('请选择要删除的记录')
          return
        }

        MessageBox.confirm(
          `确定要删除选中的 ${this.selectedRows.length} 条记录吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            const selectedIds = this.selectedRows.map((row) => row.id)
            this.localTableData = this.localTableData.filter(
              (row) => !selectedIds.includes(row.id)
            )
            this.pagination.total = this.localTableData.length

            // 如果当前页没有数据了，跳转到上一页
            if (
              this.paginatedTableData.length === 0 &&
              this.pagination.currentPage > 1
            ) {
              this.pagination.currentPage--
            }

            this.selectedRows = []
            Message.success('删除成功')
          })
          .catch(() => {})
      },
      // 查看详情
      handleViewDetail(row) {
        this.currentRow = { ...row }
        this.isEditMode = false
        this.detailDialogTitle = '详情'
        this.detailDialogVisible = true
      },
      // 编辑
      handleEdit(row) {
        this.currentRow = { ...row }
        this.isEditMode = true
        this.detailDialogTitle = '编辑'
        this.detailDialogVisible = true
      },
      // 保存详情
      handleSaveDetail() {
        // 验证表格数据
        if (this.$refs.fixedAssetsTable) {
          const isValid = this.$refs.fixedAssetsTable.validate()
          if (!isValid) {
            const errors = this.$refs.fixedAssetsTable.validationErrors
            Message.error('数据验证失败：\n' + errors.join('\n'))
            return
          }

          // 获取表格数据
          const tableData = this.$refs.fixedAssetsTable.getTableData()
          if (this.currentRow) {
            // 更新当前行的数据
            this.currentRow.data = tableData
            this.currentRow.lastModifyTime = this.formatDateTime(new Date())

            // 更新本地表格数据
            const index = this.localTableData.findIndex(
              (item) => item.id === this.currentRow.id
            )
            if (index > -1) {
              this.$set(this.localTableData, index, { ...this.currentRow })
            }

            Message.success('保存成功')
            this.detailDialogVisible = false
          }
        }
      },
      // 删除单条记录
      handleDelete(row) {
        MessageBox.confirm('确定要删除这条记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            const index = this.localTableData.findIndex(
              (item) => item.id === row.id
            )
            if (index > -1) {
              this.localTableData.splice(index, 1)
              this.pagination.total = this.localTableData.length

              // 如果当前页没有数据了，跳转到上一页
              if (
                this.paginatedTableData.length === 0 &&
                this.pagination.currentPage > 1
              ) {
                this.pagination.currentPage--
              }

              Message.success('删除成功')
            }
          })
          .catch(() => {})
      },
      // 详情/编辑保存
      handleDetailSave(saveData) {
        if (this.currentRow) {
          // 更新当前行的数据
          this.currentRow.data = saveData
          this.currentRow.lastModifyTime = this.formatDateTime(new Date())

          // 更新本地表格数据
          const index = this.localTableData.findIndex(
            (item) => item.id === this.currentRow.id
          )
          if (index > -1) {
            this.$set(this.localTableData, index, { ...this.currentRow })
          }

          Message.success('保存成功')
          this.detailDialogVisible = false
        }
      },
      // 格式化日期时间
      formatDateTime(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      },
      // 分页变化
      handlePageChange(page) {
        this.pagination.currentPage = page
      },
      // 每页条数变化
      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.pagination.currentPage = 1
      },
      // 关闭弹窗
      handleClose() {
        this.dialogVisible = false
        this.$emit('update:visible', false)
      },
      // 取消
      handleCancel() {
        this.handleClose()
      },
    },
  }
</script>

<style scoped lang="scss">
  .action-buttons {
    margin-bottom: 20px;

    .el-button {
      margin-right: 10px;
    }
  }

  .dialog-footer {
    text-align: center;
    margin-top: 20px;
    .el-button {
      margin: 0 10px;
    }
  }

  ::v-deep .el-dialog__header {
    padding: 20px 20px 10px;
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  // 操作按钮样式
  ::v-deep .el-table {
    .el-button--text {
      padding: 0 5px;
    }
  }
</style>
