<template>
  <el-dialog
    title="在线填报"
    :visible.sync="dialogVisible"
    width="90%"
    :close-on-click-modal="false"
    top="5vh"
    @close="handleClose"
  >
    <div class="online-fill-container">
      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 单记录类型 -->
        <div v-if="tableType === '单记录'" class="form-section">
          <el-card>
            <!-- <div slot="header" class="card-header">
            <span>{{ surveyData.name }}</span>
          </div> -->
            <el-form
              ref="singleRecordForm"
              :model="singleRecordForm"
              :rules="singleRecordRules"
              label-width="120px"
            >
              <el-form-item label="机构名称" prop="institutionName">
                <el-input
                  v-model="singleRecordForm.institutionName"
                  placeholder="请输入机构名称"
                  style="width: 400px"
                ></el-input>
              </el-form-item>
              <el-form-item label="机构性质" prop="institutionNature">
                <el-select
                  v-model="singleRecordForm.institutionNature"
                  placeholder="请选择机构性质"
                  style="width: 400px"
                >
                  <el-option label="公办" value="公办"></el-option>
                  <el-option label="民办" value="民办"></el-option>
                  <el-option label="混合所有制" value="混合所有制"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="机构评定等级" prop="institutionLevel">
                <el-select
                  v-model="singleRecordForm.institutionLevel"
                  placeholder="请选择机构评定等级"
                  style="width: 400px"
                >
                  <el-option label="一级" value="一级"></el-option>
                  <el-option label="二级" value="二级"></el-option>
                  <el-option label="三级" value="三级"></el-option>
                  <el-option label="未评定" value="未评定"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="机构办学方式" prop="educationMode">
                <el-select
                  v-model="singleRecordForm.educationMode"
                  placeholder="请选择机构办学方式"
                  style="width: 400px"
                >
                  <el-option label="全日制" value="全日制"></el-option>
                  <el-option label="非全日制" value="非全日制"></el-option>
                  <el-option label="混合制" value="混合制"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="机构地址" prop="institutionAddress">
                <el-input
                  v-model="singleRecordForm.institutionAddress"
                  placeholder="请输入机构地址"
                  style="width: 400px"
                ></el-input>
              </el-form-item>
              <el-form-item label="机构财务负责人" prop="financialManager">
                <el-input
                  v-model="singleRecordForm.financialManager"
                  placeholder="请输入机构财务负责人"
                  style="width: 400px"
                ></el-input>
              </el-form-item>
              <el-form-item label="机构填表人" prop="formFiller">
                <el-input
                  v-model="singleRecordForm.formFiller"
                  placeholder="请输入机构填表人"
                  style="width: 400px"
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="form-actions">
              <el-button @click="handleCancel">取消</el-button>
              <el-button type="primary" @click="handleSave">保存</el-button>
              <el-button type="success" @click="handleSubmit">提交</el-button>
            </div>
          </el-card>
        </div>

        <!-- 固定表类型 -->
        <div v-if="tableType === '固定表'" class="table-section">
          <el-card>
            <div slot="header" class="card-header">
              <span>{{ surveyData.name }}</span>
              <el-button type="primary" size="small" @click="handleAddFixedRow">
                新增行
              </el-button>
            </div>
            <el-table :data="fixedTableData" border style="width: 100%">
              <el-table-column
                prop="seq"
                label="序号"
                width="80"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="project" label="项目" min-width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.project"
                    placeholder="请输入项目名称"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="unit"
                label="单位"
                width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.unit"
                    placeholder="单位"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="dynamicYear"
                label="动态年份"
                width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.dynamicYear"
                    type="year"
                    placeholder="选择年份"
                    size="mini"
                  ></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入备注"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDeleteFixedRow(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="form-actions">
              <el-button @click="handleCancel">取消</el-button>
              <el-button type="primary" @click="handleSave">保存</el-button>
              <el-button type="success" @click="handleSubmit">提交</el-button>
            </div>
          </el-card>
        </div>

        <!-- 动态表类型 -->
        <div v-if="tableType === '动态表'" class="table-section">
          <el-card>
            <div slot="header" class="card-header">
              <!-- <span>{{ surveyData.name }}</span> -->
              <div>
                <el-button
                  type="primary"
                  size="small"
                  @click="handleAddDynamicRow"
                >
                  新增
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  :disabled="selectedRows.length === 0"
                  @click="handleBatchDelete"
                >
                  批量删除
                </el-button>
              </div>
            </div>
            <el-table
              :data="dynamicTableData"
              border
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="seq"
                label="序号"
                width="80"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="auditPeriod"
                label="监审期间"
                min-width="200"
              >
                <template slot-scope="scope">
                  {{ scope.row.auditPeriod }}
                </template>
              </el-table-column>
              <el-table-column
                prop="fillTime"
                label="填报时间"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.fillTime }}
                </template>
              </el-table-column>
              <el-table-column
                prop="lastModifyTime"
                label="最后修改时间"
                width="150"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.lastModifyTime }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleViewDetail(scope.row)"
                  >
                    详情
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleEdit(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="form-actions">
              <el-button @click="handleCancel">取消</el-button>
              <el-button type="primary" @click="handleSave">保存</el-button>
              <el-button type="success" @click="handleSubmit">提交</el-button>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      title="详情"
      :visible.sync="detailDialogVisible"
      width="90%"
      :append-to-body="true"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <div v-if="currentDetail" class="detail-content">
        <!-- 固定资产表格 - 只读模式 -->
        <div class="fixed-assets-table">
          <el-table
            :data="flattenedTableData"
            border
            style="width: 100%"
            size="small"
          >
            <el-table-column prop="seq" label="序号" width="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.seq }}
              </template>
            </el-table-column>

            <el-table-column prop="name" label="项目" min-width="150">
              <template slot-scope="scope">
                <span v-if="scope.row.isCategory" class="category-name">
                  {{ scope.row.name }}
                </span>
                <span v-else>{{ scope.row.name }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="unit"
              label="计量单位"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategory">{{ scope.row.unit }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="originalValue"
              label="固定资产原值"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategory">
                  {{ scope.row.originalValue }}
                </span>
              </template>
            </el-table-column>

            <el-table-column
              prop="entryDate"
              label="入帐或竣工验收日期"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategory">
                  {{ scope.row.entryDate }}
                </span>
              </template>
            </el-table-column>

            <el-table-column
              prop="depreciationPeriod"
              label="折旧年限"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategory">
                  {{ scope.row.depreciationPeriod }}
                </span>
              </template>
            </el-table-column>

            <el-table-column
              prop="depreciationExpense"
              label="折旧费"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategory">
                  {{ scope.row.depreciationExpense }}
                </span>
              </template>
            </el-table-column>

            <el-table-column
              prop="fundSource"
              label="资金来源"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategory">
                  {{ scope.row.fundSource }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="remark" label="备注" min-width="150">
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategory">{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑"
      :visible.sync="editDialogVisible"
      width="90%"
      :append-to-body="true"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <!-- 固定资产表格 -->
      <div class="fixed-assets-table">
        <el-table
          :data="flattenedTableData"
          border
          style="width: 100%"
          size="small"
        >
          <el-table-column prop="seq" label="序号" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.seq }}
            </template>
          </el-table-column>

          <el-table-column prop="name" label="项目" min-width="150">
            <template slot-scope="scope">
              <el-input
                v-if="!scope.row.isCategory"
                v-model="scope.row.name"
                placeholder="请输入项目名称"
                size="mini"
              ></el-input>
              <span v-else class="category-name">{{ scope.row.name }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="unit"
            label="计量单位"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-if="!scope.row.isCategory"
                v-model="scope.row.unit"
                placeholder="单位"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="originalValue"
            label="固定资产原值"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-if="!scope.row.isCategory"
                v-model="scope.row.originalValue"
                placeholder="原值"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="entryDate"
            label="入帐或竣工验收日期"
            width="180"
            align="center"
          >
            <template slot-scope="scope">
              <el-date-picker
                v-if="!scope.row.isCategory"
                v-model="scope.row.entryDate"
                type="date"
                placeholder="选择日期"
                size="mini"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </template>
          </el-table-column>

          <el-table-column
            prop="depreciationPeriod"
            label="折旧年限"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-if="!scope.row.isCategory"
                v-model="scope.row.depreciationPeriod"
                placeholder="年限"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="depreciationExpense"
            label="折旧费"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-if="!scope.row.isCategory"
                v-model="scope.row.depreciationExpense"
                placeholder="费用"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="fundSource"
            label="资金来源"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-if="!scope.row.isCategory"
                v-model="scope.row.fundSource"
                placeholder="来源"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注" min-width="150">
            <template slot-scope="scope">
              <el-input
                v-if="!scope.row.isCategory"
                v-model="scope.row.remark"
                placeholder="备注"
                size="mini"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <div v-if="!scope.row.isCategory" class="operation-buttons">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-plus"
                  @click="handleAddRow(scope.row)"
                ></el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-minus"
                  @click="handleDeleteRow(scope.row)"
                ></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="form-actions">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSave">确定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import { Message } from 'element-ui'

  export default {
    name: 'OnlineFillDialog',
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      tableType: {
        type: String,
        default: '单记录',
      },
      surveyData: {
        type: Object,
        default: () => ({}),
      },
    },
    data() {
      return {
        dialogVisible: false,

        // 单记录表单数据
        singleRecordForm: {
          institutionName: '',
          institutionNature: '',
          institutionLevel: '',
          educationMode: '',
          institutionAddress: '',
          financialManager: '',
          formFiller: '',
        },
        singleRecordRules: {
          institutionName: [
            { required: true, message: '请输入机构名称', trigger: 'blur' },
          ],
          institutionNature: [
            { required: true, message: '请选择机构性质', trigger: 'change' },
          ],
          institutionLevel: [
            {
              required: true,
              message: '请选择机构评定等级',
              trigger: 'change',
            },
          ],
          educationMode: [
            {
              required: true,
              message: '请选择机构办学方式',
              trigger: 'change',
            },
          ],
          institutionAddress: [
            { required: true, message: '请输入机构地址', trigger: 'blur' },
          ],
          financialManager: [
            {
              required: true,
              message: '请输入机构财务负责人',
              trigger: 'blur',
            },
          ],
          formFiller: [
            { required: true, message: '请输入机构填表人', trigger: 'blur' },
          ],
        },

        // 固定表数据
        fixedTableData: [
          {
            project: '',
            unit: '',
            dynamicYear: null,
            remark: '',
          },
        ],

        // 动态表数据
        dynamicTableData: [
          {
            auditPeriod: '2023年1月-2023年12月',
            fillTime: '2023-12-01 10:00:00',
            lastModifyTime: '2023-12-01 10:00:00',
            detail: '固定资产表格数据',
          },
        ],

        // 选中的行
        selectedRows: [],

        // 弹窗控制
        detailDialogVisible: false,
        editDialogVisible: false,
        currentDetail: null,

        // 编辑表单
        editForm: {
          auditPeriod: '',
          detail: '',
        },
        editRules: {
          auditPeriod: [
            { required: true, message: '请输入监审期间', trigger: 'blur' },
          ],
          detail: [
            { required: true, message: '请输入详细信息', trigger: 'blur' },
          ],
        },

        // 固定资产表格数据 - 用于弹窗显示
        fixedAssetsData: [
          // 房屋建筑物
          {
            id: 'I',
            category: '房屋建筑物',
            items: [
              {
                id: 'I-1',
                name: '办公用房',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'I-2',
                name: '教保用房',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'I-3',
                name: '幼儿宿舍用房',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'I-4',
                name: '其它',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          // 交通运输工具
          {
            id: 'II',
            category: '交通运输工具',
            items: [
              {
                id: 'II-1',
                name: '车辆',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          // 教保专用设备
          {
            id: 'III',
            category: '教保专用设备',
            items: [
              {
                id: 'III-1',
                name: '电教',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'III-2',
                name: '文体',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          // 办公设备
          {
            id: 'IV',
            category: '办公设备',
            items: [
              {
                id: 'IV-1',
                name: '电脑',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
          // 其它固定资产
          {
            id: 'V',
            category: '其它固定资产',
            items: [
              {
                id: 'V-1',
                name: '空调',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-2',
                name: '家电',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-3',
                name: '供水系统',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-4',
                name: '洗涤用具',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-5',
                name: '家具',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-6',
                name: '炊事用具',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
              {
                id: 'V-7',
                name: '其它',
                unit: '',
                originalValue: '',
                entryDate: '',
                depreciationPeriod: '',
                depreciationExpense: '',
                fundSource: '',
                remark: '',
              },
            ],
          },
        ],
      }
    },
    computed: {
      // 将嵌套的表格数据扁平化，用于表格显示
      flattenedTableData() {
        const result = []
        let seq = 1

        this.fixedAssetsData.forEach((category) => {
          // 添加分类行
          result.push({
            seq: category.id,
            name: category.category,
            isCategory: true,
            categoryId: category.id,
          })

          // 添加分类下的项目行
          category.items.forEach((item) => {
            result.push({
              ...item,
              seq: seq++,
              isCategory: false,
              categoryId: category.id,
            })
          })
        })

        return result
      },
    },
    watch: {
      visible: {
        handler(newVal) {
          this.dialogVisible = newVal
        },
        immediate: true,
      },
    },
    methods: {
      // 关闭弹窗
      handleClose() {
        this.$emit('update:visible', false)
      },

      // 取消
      handleCancel() {
        this.handleClose()
      },

      // 保存
      handleSave() {
        if (this.tableType === '单记录') {
          this.$refs.singleRecordForm.validate((valid) => {
            if (valid) {
              console.log('保存单记录数据:', this.singleRecordForm)
              Message.success('保存成功')
            } else {
              Message.error('请完善表单信息')
              return false
            }
          })
        } else if (this.tableType === '固定表') {
          console.log('保存固定表数据:', this.fixedTableData)
          Message.success('保存成功')
        } else if (this.tableType === '动态表') {
          // 动态表保存时不进行严格验证
          console.log('保存动态表数据:', this.dynamicTableData)
          Message.success('保存成功')
        }
      },

      // 提交
      handleSubmit() {
        if (this.tableType === '单记录') {
          this.$refs.singleRecordForm.validate((valid) => {
            if (valid) {
              console.log('提交单记录数据:', this.singleRecordForm)
              Message.success('提交成功')
              this.handleClose()
            } else {
              Message.error('请完善表单信息')
              return false
            }
          })
        } else if (this.tableType === '固定表') {
          console.log('提交固定表数据:', this.fixedTableData)
          Message.success('提交成功')
          this.handleClose()
        } else if (this.tableType === '动态表') {
          // 动态表提交时不进行验证
          console.log('提交动态表数据:', this.dynamicTableData)
          Message.success('提交成功')
          this.handleClose()
        }
      },

      // 固定表相关方法
      handleAddFixedRow() {
        this.fixedTableData.push({
          project: '',
          unit: '',
          dynamicYear: null,
          remark: '',
        })
      },

      handleDeleteFixedRow(index) {
        this.$confirm('确定删除该行吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.fixedTableData.splice(index, 1)
          Message.success('删除成功')
        })
      },

      // 固定资产表格相关方法
      handleAddRow(row) {
        // 找到对应的分类
        const category = this.fixedAssetsData.find(
          (cat) => cat.id === row.categoryId
        )
        if (category) {
          // 生成新的项目ID
          const newId = `${row.categoryId}-${Date.now()}`
          const newItem = {
            id: newId,
            name: '',
            unit: '',
            originalValue: '',
            entryDate: '',
            depreciationPeriod: '',
            depreciationExpense: '',
            fundSource: '',
            remark: '',
          }

          // 在指定行后插入新行
          const itemIndex = category.items.findIndex(
            (item) => item.id === row.id
          )
          if (itemIndex !== -1) {
            category.items.splice(itemIndex + 1, 0, newItem)
          } else {
            category.items.push(newItem)
          }

          Message.success('添加行成功')
        }
      },

      handleDeleteRow(row) {
        this.$confirm('确定删除该行吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          // 找到对应的分类
          const category = this.fixedAssetsData.find(
            (cat) => cat.id === row.categoryId
          )
          if (category) {
            const itemIndex = category.items.findIndex(
              (item) => item.id === row.id
            )
            if (itemIndex !== -1) {
              category.items.splice(itemIndex, 1)
              Message.success('删除成功')
            }
          }
        })
      },

      // 动态表相关方法
      handleAddDynamicRow() {
        const newRow = {
          auditPeriod: '',
          fillTime: new Date().toLocaleString(),
          lastModifyTime: new Date().toLocaleString(),
          detail: '',
        }
        this.dynamicTableData.unshift(newRow)
        // 打开编辑弹窗
        this.handleEdit(newRow)
      },

      handleBatchDelete() {
        if (this.selectedRows.length === 0) {
          Message.warning('请选择要删除的行')
          return
        }
        this.$confirm(
          `确定删除选中的 ${this.selectedRows.length} 行吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          this.selectedRows.forEach((row) => {
            const index = this.dynamicTableData.indexOf(row)
            if (index > -1) {
              this.dynamicTableData.splice(index, 1)
            }
          })
          this.selectedRows = []
          Message.success('删除成功')
        })
      },

      handleSelectionChange(selection) {
        this.selectedRows = selection
      },

      handleViewDetail(row) {
        // 详情弹窗显示整个表格数据
        this.currentDetail = this.dynamicTableData
        this.detailDialogVisible = true
      },

      handleEdit(row) {
        // 编辑弹窗显示整个表格数据
        this.currentDetail = this.dynamicTableData
        this.editDialogVisible = true
      },

      handleDelete(row) {
        this.$confirm('确定删除该行吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const index = this.dynamicTableData.indexOf(row)
          if (index > -1) {
            this.dynamicTableData.splice(index, 1)
          }
          Message.success('删除成功')
        })
      },

      handleEditSave() {
        // 编辑保存逻辑 - 验证固定资产表格
        const validationErrors = this.validateFixedAssetsTable()
        if (validationErrors.length > 0) {
          Message.error('表单验证失败，请检查以下问题：')
          validationErrors.forEach((error) => {
            console.error(error)
          })
          return false
        }

        console.log('编辑保存数据:', this.fixedAssetsData)
        Message.success('编辑保存成功')
        this.editDialogVisible = false
      },

      // 表单验证
      validateFixedAssetsTable() {
        const errors = []

        this.fixedAssetsData.forEach((category) => {
          category.items.forEach((item, index) => {
            const rowNum = index + 1

            // 必填字段验证
            if (!item.name) {
              errors.push(
                `${category.category} 第${rowNum}行：项目名称不能为空`
              )
            }
            if (!item.unit) {
              errors.push(
                `${category.category} 第${rowNum}行：计量单位不能为空`
              )
            }
            if (!item.originalValue) {
              errors.push(
                `${category.category} 第${rowNum}行：固定资产原值不能为空`
              )
            }
            if (!item.entryDate) {
              errors.push(
                `${category.category} 第${rowNum}行：入帐或竣工验收日期不能为空`
              )
            }
            if (!item.depreciationPeriod) {
              errors.push(
                `${category.category} 第${rowNum}行：折旧年限不能为空`
              )
            }
            if (!item.depreciationExpense) {
              errors.push(`${category.category} 第${rowNum}行：折旧费不能为空`)
            }
            if (!item.fundSource) {
              errors.push(
                `${category.category} 第${rowNum}行：资金来源不能为空`
              )
            }

            // 格式验证
            if (
              item.originalValue &&
              !/^\d+(\.\d+)?$/.test(item.originalValue)
            ) {
              errors.push(
                `${category.category} 第${rowNum}行：固定资产原值格式不正确`
              )
            }
            if (
              item.depreciationPeriod &&
              !/^\d+$/.test(item.depreciationPeriod)
            ) {
              errors.push(
                `${category.category} 第${rowNum}行：折旧年限必须为正整数`
              )
            }
            if (
              item.depreciationExpense &&
              !/^\d+(\.\d+)?$/.test(item.depreciationExpense)
            ) {
              errors.push(
                `${category.category} 第${rowNum}行：折旧费格式不正确`
              )
            }
          })
        })

        return errors
      },
    },
  }
</script>

<style scoped lang="scss">
  .online-fill-container {
    padding: 20px;
  }

  .page-header {
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 20px;
      font-weight: bold;
    }
  }

  .action-buttons {
    margin-bottom: 20px;
  }

  .main-content {
    .form-section,
    .table-section {
      margin-bottom: 20px;
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-weight: bold;
      font-size: 16px;
    }
  }

  .form-actions {
    margin-top: 20px;
    text-align: right;

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

  .dialog-footer {
    text-align: right;

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

  // 固定资产表格样式
  .fixed-assets-table {
    .category-name {
      font-weight: bold;
      color: #409eff;
      background-color: #f5f7fa;
      padding: 8px;
      display: block;
    }

    .operation-buttons {
      display: flex;
      justify-content: center;
      gap: 5px;

      .el-button {
        padding: 5px;
        min-width: 24px;
        height: 24px;
      }
    }

    // 分类行样式
    ::v-deep .el-table__row {
      &.category-row {
        background-color: #f5f7fa;

        td {
          background-color: #f5f7fa !important;
          font-weight: bold;
          color: #409eff;
        }
      }
    }

    // 输入框样式
    ::v-deep .el-input__inner {
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      &:focus {
        border-color: #409eff;
      }
    }

    // 日期选择器样式
    ::v-deep .el-date-editor {
      width: 100%;
    }
  }

  // 详情弹窗样式
  .detail-content {
    .fixed-assets-table {
      .category-name {
        font-weight: bold;
        color: #409eff;
        background-color: #f5f7fa;
        padding: 8px;
        display: block;
      }

      // 只读模式下的样式
      ::v-deep .el-table__row {
        &.category-row {
          background-color: #f5f7fa;

          td {
            background-color: #f5f7fa !important;
            font-weight: bold;
            color: #409eff;
          }
        }
      }

      // 只读文本样式
      span {
        display: inline-block;
        padding: 4px 8px;
        min-height: 20px;
        line-height: 20px;
      }
    }
  }
</style>
