<template>
  <div>
    <!-- 表格组件 -->
    <CostAuditTable
      v-loading="loading"
      :table-data="surveyData.list"
      :columns="getSurveyColumns()"
      :show-action-column="true"
      :show-pagination="true"
      :pagination="costSurveyPagination"
      style="width: 100%"
      @pagination-change="handlePaginationChange"
    ></CostAuditTable>
    <!-- 成本调查表查看弹窗 -->
    <SurveyDialog
      :dialog-visible="contentEditDialogVisible"
      :dialog-title="contentEditDialogTitle"
      :form-data="contentEditForm"
      :audit-period-from-parent="auditPeriodFromProject"
      :disabled="contentEditDisabled"
      @cancel="handleContentEditCancel"
    />
  </div>
</template>
<script>
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import SurveyDialog from '@/views/costAudit/baseInfo/catalogManage/surveyDialog.vue'
  import { getCostSurveyForms } from '@/api/catalogManage.js'
  export default {
    components: {
      CostAuditTable,
      SurveyDialog,
    },
    props: {
      // 父组件传递的参数
      project: {
        type: Object,
        default: () => {},
      },
      isView: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        loading: false,
        // 内容编辑弹窗相关
        contentEditDialogVisible: false,
        contentEditDialogTitle: '内容维护',
        contentEditDisabled: true,
        contentEditForm: {
          surveyTemplateName: '',
          templateType: '1',
          // 单记录列表
          tableHeaders: [],
          // 固定表列表
          fixedTable: [],
          // 动态表列表
          dynamicTable: [],
        },
        // 内部管理调查数据
        surveyData: {
          list: [],
        },
        costSurveyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
      }
    },
    computed: {
      // 从项目中提取监审期间（字符串或数组），优先 basicInfo.auditPeriod
      auditPeriodFromProject() {
        const p = this.project || {}
        if (p.basicInfo && p.basicInfo.auditPeriod)
          return p.basicInfo.auditPeriod
        if (p.auditPeriod) return p.auditPeriod
        if (p.data && p.data.basicInfo && p.data.basicInfo.auditPeriod) {
          return p.data.basicInfo.auditPeriod
        }
        return ''
      },
    },
    watch: {
      // 监听project变化，确保有项目ID时刷新数据
      project: {
        handler(newVal) {
          if (newVal && newVal.projectId) {
            this.loadSurveyData()
          }
        },
        deep: true,
        immediate: true,
      },
    },
    mounted() {
      // 组件挂载时加载数据
      if (this.project && this.project.projectId) {
        this.loadSurveyData()
      }
    },

    methods: {
      // 加载调查模板数据
      loadSurveyData() {
        if (!this.project || !this.project.projectId) {
          console.warn('项目ID不存在，无法加载调查模板数据')
          return
        }
        this.loading = true
        const params = {
          catalogId:
            this.project.catalogId ||
            this.project.catalogid ||
            this.project.catalogID ||
            '',
          pageNum: this.costSurveyPagination.currentPage,
          pageSize: this.costSurveyPagination.pageSize,
        }
        getCostSurveyForms(params)
          .then((res) => {
            const value = res?.value || {}
            const records = Array.isArray(value.records)
              ? value.records
              : Array.isArray(value?.value?.records)
              ? value.value.records
              : []
            // 直接用 records；若无 records 则尝试把 value 视作数组
            this.surveyData.list =
              Array.isArray(records) && records.length > 0
                ? records
                : Array.isArray(value)
                ? value
                : []
            const total =
              value.total ??
              value?.value?.total ??
              (Array.isArray(records) ? records.length : 0)
            this.costSurveyPagination.total = Number(total) || 0
          })
          .catch((error) => {
            console.error('加载调查模板数据失败:', error)
            this.surveyData.list = []
          })
          .finally(() => {
            this.loading = false
          })
      },

      // 获取带操作按钮的表格列配置
      getSurveyColumns() {
        return [
          {
            prop: 'surveyTemplateName',
            label: '模板名称',
            minWidth: 220,
            align: 'left',
            headerAlign: 'center',
            showOverflowTooltip: true,
          },
          {
            prop: 'templateType',
            label: '模板类型',
            width: 120,
            align: 'center',
            headerAlign: 'center',
            formatter: (row) => {
              return row.templateType == '1'
                ? '单记录'
                : row.templateType == '2'
                ? '固定表'
                : '动态表'
            },
          },
          {
            prop: 'action',
            label: '操作',
            align: 'center',
            headerAlign: 'center',
            width: 140,
            actions: [
              {
                name: 'view',
                label: '查看模板',
                type: 'text',
                onClick: this.handleViewTemplate,
              },
            ],
          },
        ]
      },
      // 查看成本调查表内容弹窗
      handleViewTemplate(data) {
        this.contentEditForm = {
          surveyTemplateName: data.surveyTemplateName || '',
          templateType: data.templateType || '1',
          data: {
            ...data,
            surveyId: data.surveyId,
          },
          tableHeaders: [],
          fixedTable: {
            tableHeaders: [],
            fixedTables: [],
            fixedTablesTitle: [],
            fixedTableHeaders: [],
          },
          dynamicTable: {
            tableHeaders: [],
            dynamicTables: [],
            dynamicTablesTitle: [],
            dynamicTableHeaders: [],
          },
          isDynamicTables: false,
          isFixedTables: false,
        }
        this.contentEditDialogTitle = '查看'
        this.contentEditDialogVisible = true
      },
      handlePaginationChange({ currentPage, pageSize }) {
        this.costSurveyPagination.currentPage = currentPage
        this.costSurveyPagination.pageSize = pageSize
        this.loadSurveyData()
      },
      // 关闭内容编辑弹窗
      handleContentEditCancel() {
        this.contentEditDialogVisible = false
        this.contentEditForm = {
          surveyTemplateName: '',
          templateType: '1',
          tableHeaders: [],
          fixedTable: [],
          dynamicTable: [],
        }
      },
    },
  }
</script>
<style lang="scss" scoped></style>
