<template>
  <div>
    <!-- 调查表填报弹窗（单记录类型） -->
    <survey-form-dialog
      :visible.sync="surveyFormDialogVisible"
      :survey-data="currentSurveyRow"
      :form-fields="formFields"
      :is-view-mode="isViewMode"
      @save="handleSurveyFormSave"
    />

    <!-- 固定表填报弹窗 -->
    <fixed-table-dialog
      :visible.sync="fixedTableDialogVisible"
      :survey-data="currentSurveyRow"
      :table-items="tableItems"
      :audit-periods="auditPeriods"
      :is-view-mode="isViewMode"
      @save="handleFixedTableSave"
    />

    <!-- 动态表填报弹窗 -->
    <dynamic-table-dialog
      :visible.sync="dynamicTableDialogVisible"
      :survey-data="currentSurveyRow"
      :table-data="dynamicTableData"
      :table-items="tableItems"
      :is-view-mode="isViewMode"
      @save="handleDynamicTableSave"
    />

    <el-table
      style="width: 100%; margin-top: 20px"
      :data="paginatedData"
      border
      size="medium"
    >
      <!-- 序号列 -->
      <el-table-column prop="index" label="序号" width="60" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="成本调查表" min-width="220">
        <template slot-scope="scope">
          <span
            :style="{
              color: scope.row.isDisabled ? '#909399' : '#409EFF',
              cursor: scope.row.isDisabled ? 'default' : 'pointer',
            }"
            @click="
              !scope.row.isDisabled && $emit('handle-survey-click', scope.row)
            "
          >
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>

      <!-- 资料类型列 -->
      <el-table-column
        prop="dataType"
        label="资料类型"
        width="120"
        align="center"
      ></el-table-column>

      <!-- 表格类型列 -->
      <el-table-column
        prop="tableType"
        label="表格类型"
        width="120"
        align="center"
      ></el-table-column>

      <!-- 是否必填列 -->
      <el-table-column
        prop="isRequired"
        label="是否必填"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <span>
            {{ scope.row.isRequired === '1' ? '是' : '否' }}
          </span>
        </template>
      </el-table-column>

      <!-- 是否上传列（红色“未上传”、绿色“已上传”） -->
      <el-table-column label="是否上传" width="100" align="center">
        <template slot-scope="scope">
          <span
            :style="{
              color: scope.row.isUploaded === true ? '#67c23a' : '#f56c6c',
            }"
          >
            {{ scope.row.isUploaded === true ? '已上传' : '未上传' }}
          </span>
        </template>
      </el-table-column>

      <!-- 操作列（根据“是否上传”“表格类型”显示不同按钮） -->
      <el-table-column label="操作" width="280" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.isUploaded">
            <el-button
              type="text"
              size="small"
              :disabled="isViewMode"
              @click="handleOnlineFillClick(scope.row)"
            >
              在线填报
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="isViewMode"
              @click="$emit('handle-modify', scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="isViewMode"
              @click="$emit('handle-data-download', scope.row)"
            >
              数据下载
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="isViewMode"
              @click="$emit('handle-data-upload', scope.row)"
            >
              数据上传
            </el-button>
          </template>
          <template v-else>
            <el-button
              type="text"
              size="small"
              :disabled="isViewMode"
              @click="handleOnlineFillClick(scope.row)"
            >
              在线填报
            </el-button>
            <el-button
              v-if="scope.row.tableType === '动态表'"
              type="text"
              size="small"
              :disabled="isViewMode"
              @click="$emit('handle-template-download', scope.row)"
            >
              模版下载
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="isViewMode"
              @click="$emit('handle-data-upload', scope.row)"
            >
              数据上传
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right"
      @current-change="$emit('handle-page-change', $event)"
      @size-change="$emit('handle-size-change', $event)"
    />
  </div>
</template>

<script>
  import SurveyFormDialog from './SurveyFormDialog.vue'
  import FixedTableDialog from './FixedTableDialog.vue'
  import DynamicTableDialog from './DynamicTableDialog.vue'

  export default {
    name: 'CostSurveyTab',
    components: {
      SurveyFormDialog,
      FixedTableDialog,
      DynamicTableDialog,
    },
    props: {
      paginatedData: {
        type: Array,
        default: () => [],
      },
      pagination: {
        type: Object,
        default: () => ({ currentPage: 1, pageSize: 10, total: 0 }),
      },
      isViewMode: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        surveyFormDialogVisible: false,
        fixedTableDialogVisible: false,
        dynamicTableDialogVisible: false,
        currentSurveyRow: null,
        // 表单字段配置（可以从后台获取，或通过 props 传入）
        formFields: [],
        // 固定表数据配置
        tableItems: [],
        // 监审期间（年份数组）
        auditPeriods: [],
        // 动态表数据
        dynamicTableData: [],
      }
    },
    mounted() {
      // 如果当前行有表单配置，则使用，否则使用默认配置
      // 这里可以根据实际需求从后台获取表单配置
      this.initFormFields()
    },
    methods: {
      // 处理在线填报点击
      handleOnlineFillClick(row) {
        this.currentSurveyRow = row

        // 如果表格类型是"单记录"，弹出调查表填报弹窗
        if (row.tableType === '单记录') {
          // 初始化表单字段配置
          this.initFormFields()
          this.surveyFormDialogVisible = true
        } else if (row.tableType === '固定表') {
          // 如果表格类型是"固定表"，弹出固定表填报弹窗
          this.initFixedTableData()
          this.fixedTableDialogVisible = true
        } else if (row.tableType === '动态表') {
          // 如果表格类型是"动态表"，弹出动态表填报弹窗
          this.initDynamicTableData()
          this.dynamicTableDialogVisible = true
        } else {
          // 其他类型，触发原有事件
          this.$emit('handle-online-fill', row)
        }
      },
      // 处理调查表保存
      handleSurveyFormSave(formData) {
        // 可以将保存的数据传递给父组件
        this.$emit('handle-survey-form-save', {
          row: this.currentSurveyRow,
          formData: formData,
        })
      },
      // 处理固定表保存
      handleFixedTableSave(tableData) {
        // 可以将保存的数据传递给父组件
        this.$emit('handle-fixed-table-save', {
          row: this.currentSurveyRow,
          tableData: tableData,
        })
      },
      // 处理动态表保存
      handleDynamicTableSave(tableData) {
        // 可以将保存的数据传递给父组件
        this.$emit('handle-dynamic-table-save', {
          row: this.currentSurveyRow,
          tableData: tableData,
        })
      },
      // 初始化动态表数据
      initDynamicTableData() {
        // 如果当前行有动态表数据，则使用
        if (this.currentSurveyRow && this.currentSurveyRow.dynamicTableData) {
          this.dynamicTableData = this.currentSurveyRow.dynamicTableData
        } else {
          // 使用空数组，组件内部会使用假数据
          this.dynamicTableData = []
        }

        // 初始化表格项配置（用于详情/编辑时显示表单）
        if (this.currentSurveyRow && this.currentSurveyRow.tableItems) {
          this.tableItems = this.currentSurveyRow.tableItems
        } else {
          // 使用固定表的假数据配置
          this.tableItems = this.getMockTableItems()
        }
      },
      // 初始化表单字段配置
      initFormFields() {
        // 如果当前行有表单配置，则使用
        // 这里可以根据实际需求从后台获取表单配置
        // 例如：从 currentSurveyRow 中获取表单配置，或调用 API 获取
        if (this.currentSurveyRow && this.currentSurveyRow.formFields) {
          this.formFields = this.currentSurveyRow.formFields
        } else {
          // 使用假数据作为测试（实际开发中应该从后台获取）
          this.formFields = this.getMockFormFields()
        }
      },
      // 获取假数据表单字段配置（用于测试）
      getMockFormFields() {
        return [
          {
            prop: 'institutionName',
            label: '机构名称',
            type: 'input',
            colSpan: 12,
            defaultValue: '幼儿园基本情况',
            placeholder: '请输入机构名称',
            required: true,
          },
          {
            prop: 'institutionNature',
            label: '机构性质',
            type: 'select',
            colSpan: 12,
            dictType: 'institutionNature', // 字典类型
            defaultValue: '公办',
            placeholder: '请选择机构性质',
            required: true,
            clearable: true,
          },
          {
            prop: 'institutionLevel',
            label: '机构评定等级',
            type: 'select',
            colSpan: 12,
            dictType: 'institutionLevel', // 字典类型
            defaultValue: '省一级',
            placeholder: '请选择机构评定等级',
            required: true,
            clearable: true,
          },
          {
            prop: 'educationMode',
            label: '机构办学方式',
            type: 'select',
            colSpan: 12,
            dictType: 'educationMode', // 字典类型
            defaultValue: '全日制',
            placeholder: '请选择机构办学方式',
            required: true,
            clearable: true,
          },
          {
            prop: 'institutionAddress',
            label: '机构地址',
            type: 'input',
            colSpan: 12,
            placeholder: '请输入机构地址',
            required: true,
          },
          {
            prop: 'formFiller',
            label: '机构填表人',
            type: 'input',
            colSpan: 12,
            placeholder: '请输入机构填表人',
            required: true,
          },
          {
            prop: 'financialManager',
            label: '机构财务负责人',
            type: 'input',
            colSpan: 12,
            placeholder: '请输入机构财务负责人',
            required: true,
          },
          {
            prop: 'contactPhone',
            label: '机构联系电话',
            type: 'input',
            colSpan: 12,
            placeholder: '请输入机构联系电话',
            required: true,
            rules: [
              {
                required: true,
                message: '请输入机构联系电话',
                trigger: 'blur',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的手机号码',
                trigger: 'blur',
              },
            ],
          },
        ]
      },
      // 初始化固定表数据
      initFixedTableData() {
        // 如果当前行有表格配置，则使用
        if (this.currentSurveyRow && this.currentSurveyRow.tableItems) {
          this.tableItems = this.currentSurveyRow.tableItems
        } else {
          // 使用假数据作为测试（实际开发中应该从后台获取）
          this.tableItems = this.getMockTableItems()
        }

        // 初始化监审期间
        if (this.currentSurveyRow && this.currentSurveyRow.auditPeriod) {
          this.auditPeriods = this.parseAuditPeriod(
            this.currentSurveyRow.auditPeriod
          )
        } else {
          // 默认使用最近3年
          const currentYear = new Date().getFullYear()
          this.auditPeriods = [
            String(currentYear - 2),
            String(currentYear - 1),
            String(currentYear),
          ]
        }
      },
      // 解析监审期间字符串（如 "2022,2023,2024" 或 "2022-2024"）
      parseAuditPeriod(periodStr) {
        if (!periodStr) return []
        if (periodStr.includes(',')) {
          return periodStr.split(',').map((p) => p.trim())
        }
        if (periodStr.includes('-')) {
          const parts = periodStr.split('-')
          if (parts.length === 2) {
            const start = parseInt(parts[0].trim())
            const end = parseInt(parts[1].trim())
            const years = []
            for (let year = start; year <= end; year++) {
              years.push(String(year))
            }
            return years
          }
        }
        return [String(periodStr)]
      },
      // 获取假数据表格配置（用于测试）
      getMockTableItems() {
        return [
          {
            id: '1',
            itemName: '班级数',
            unit: '个',
            isCategory: false,
            seq: 1,
            validateRules: {
              required: true,
              type: 'number',
              min: 0,
            },
          },
          {
            id: '2',
            itemName: '幼儿学生人数',
            unit: '人',
            isCategory: false,
            seq: 2,
            validateRules: {
              required: true,
              type: 'number',
              min: 0,
            },
          },
          {
            id: 'III',
            itemName: '在取做保职工总人数',
            unit: '人',
            isCategory: true,
            categorySeq: 'III',
            children: [
              {
                id: '3-1',
                itemName: '行政管理人员数',
                unit: '人',
                isCategory: false,
                categoryId: 'III',
                seq: 3,
                validateRules: {
                  required: true,
                  type: 'number',
                  min: 0,
                },
                linkageRules: {
                  parent: 'III',
                  relation: 'sum',
                },
              },
              {
                id: '3-2',
                itemName: '教师人数',
                unit: '人',
                isCategory: false,
                categoryId: 'III',
                seq: 4,
                validateRules: {
                  required: true,
                  type: 'number',
                  min: 0,
                },
                linkageRules: {
                  parent: 'III',
                  relation: 'sum',
                },
              },
              {
                id: '3-3',
                itemName: '保育员人数',
                unit: '人',
                isCategory: false,
                categoryId: 'III',
                seq: 5,
                validateRules: {
                  required: true,
                  type: 'number',
                  min: 0,
                },
                linkageRules: {
                  parent: 'III',
                  relation: 'sum',
                },
              },
              {
                id: '3-4',
                itemName: '医务人员',
                unit: '人',
                isCategory: false,
                categoryId: 'III',
                seq: 6,
                validateRules: {
                  required: true,
                  type: 'number',
                  min: 0,
                },
                linkageRules: {
                  parent: 'III',
                  relation: 'sum',
                },
              },
              {
                id: '3-5',
                itemName: '工勤人员',
                unit: '人',
                isCategory: false,
                categoryId: 'III',
                seq: 7,
                validateRules: {
                  required: true,
                  type: 'number',
                  min: 0,
                },
                linkageRules: {
                  parent: 'III',
                  relation: 'sum',
                },
                children: [
                  {
                    id: '3-5-1',
                    itemName: '炊事员',
                    unit: '人',
                    isCategory: false,
                    categoryId: '3-5',
                    seq: 8,
                    validateRules: {
                      required: true,
                      type: 'number',
                      min: 0,
                    },
                    linkageRules: {
                      parent: '3-5',
                      relation: 'sum',
                    },
                  },
                  {
                    id: '3-5-2',
                    itemName: '司机',
                    unit: '人',
                    isCategory: false,
                    categoryId: '3-5',
                    seq: 9,
                    validateRules: {
                      required: true,
                      type: 'number',
                      min: 0,
                    },
                    linkageRules: {
                      parent: '3-5',
                      relation: 'sum',
                    },
                  },
                  {
                    id: '3-5-3',
                    itemName: '清洁工',
                    unit: '人',
                    isCategory: false,
                    categoryId: '3-5',
                    seq: 10,
                    validateRules: {
                      required: true,
                      type: 'number',
                      min: 0,
                    },
                    linkageRules: {
                      parent: '3-5',
                      relation: 'sum',
                    },
                  },
                ],
              },
              {
                id: '3-6',
                itemName: '其他人员',
                unit: '人',
                isCategory: false,
                categoryId: 'III',
                seq: 11,
                validateRules: {
                  required: true,
                  type: 'number',
                  min: 0,
                },
                linkageRules: {
                  parent: 'III',
                  relation: 'sum',
                },
              },
            ],
          },
        ]
      },
    },
  }
</script>
