<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <!-- 操作按钮 -->
    <div slot="title" class="operation-bar">
      <span>{{ title }}</span>
    </div>

    <!-- 标签页容器 -->
    <div class="tabs-container">
      <el-tabs
        v-model="activeTab"
        type="border-card"
        @tab-click="handleTabClick"
      >
        <!-- 监审立项信息 -->
        <el-tab-pane label="监审立项信息" name="basicInfo">
          <basicInfoTab
            ref="basicInfoTab"
            :project="currentProjectData"
            :is-view="isView"
            @catalog-id-updated="handleCatalogIdUpdated"
          />
        </el-tab-pane>

        <!-- 监审工作方案 -->
        <el-tab-pane label="监审工作方案" name="scenario">
          <workPlanTab
            :form-data.sync="formData.workPlan"
            :loading="scenarioData.saveScenario"
            :is-view="isView"
            :project="actualProject"
            @saveFiles="handleSaveFiles"
            @removeFile="handleRemoveFile"
          />
        </el-tab-pane>

        <!-- 报送资料要求 -->
        <el-tab-pane label="报送资料要求" name="material">
          <materialTab
            :project="actualProject"
            :is-view="isView"
            :material-data="materialData"
            @refresh="getMaterialData"
            @paginationChange="handlePaginationChange"
            @update:materialData="(val) => (materialData = val)"
          />
        </el-tab-pane>

        <!-- 成本调查表 -->
        <el-tab-pane label="成本调查表" name="survey">
          <surveyTab
            :project="actualProject"
            :is-view="isView"
            :survey-data="surveyData"
          />
        </el-tab-pane>

        <!-- 监审工作流程 -->
        <el-tab-pane label="监审工作流程" name="workflow">
          <workflowTab
            :project="actualProject"
            :is-view="isView"
            :workflow-data.sync="workflowData"
          />
        </el-tab-pane>

        <!-- 监审通知 -->
        <el-tab-pane label="监审通知" name="auditNotice">
          <auditNoticeTab
            ref="auditNoticeTab"
            :project="actualProject"
            :is-view="isView"
            :document-data="documentData"
            @refresh="getDocumentData"
            @paginationChange="handlePaginationChange"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script>
  import {
    addCostProjectScenario,
    updateCostProjectScenario,
  } from '@/api/taskCustomizedRelease.js'
  import basicInfoTab from './taskComponents/basicInfoTab.vue'
  import workPlanTab from './taskComponents/workPlanTab.vue'
  import materialTab from './taskComponents/materialTab.vue'
  import surveyTab from './taskComponents/surveyTab.vue'
  import workflowTab from './taskComponents/workflowTab.vue'
  import auditNoticeTab from './taskComponents/auditNoticeTab.vue'
  import { taskMixin } from '@/views/costAudit/projectInfo/auditTaskManage/taskCustomizedRelease/index.js'
  export default {
    name: 'TaskDetail',
    components: {
      basicInfoTab,
      workPlanTab,
      materialTab,
      surveyTab,
      workflowTab,
      auditNoticeTab,
    },
    mixins: [taskMixin],
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      title: {
        type: String,
        default: '任务详情',
      },
      project: {
        type: Object,
        default: () => {},
      },
      isView: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        dialogVisible: false,
        currentProjectData: null,
      }
    },
    computed: {
      // 优先使用 currentProjectData，其次使用 project prop
      actualProject() {
        return this.currentProjectData || this.project
      },
    },
    watch: {
      visible(newVal) {
        this.dialogVisible = newVal
        if (newVal && this.actualProject && this.actualProject.projectId) {
          this.initData()
        }
      },
      dialogVisible(newVal) {
        this.$emit('update:visible', newVal)
      },
      // 监听 actualProject 变化，确保数据更新时重新加载
      'actualProject.projectId': {
        handler(newProjectId) {
          if (newProjectId && this.dialogVisible) {
            this.initData()
          }
        },
        immediate: false,
      },
    },
    mounted() {
      this.dialogVisible = this.visible
      if (this.visible && this.actualProject && this.actualProject.projectId) {
        this.initData()
      }
    },
    methods: {
      initData() {
        this.handleTabClick()
      },
      // 处理 catalogId 更新事件
      handleCatalogIdUpdated(catalogId) {
        if (catalogId && this.currentProjectData) {
          // 更新 currentProjectData 中的 catalogId
          this.$set(this.currentProjectData, 'catalogId', catalogId)
          // 同时更新 basicInfo.catalogId，确保 surveyTab 可以获取到
          if (!this.currentProjectData.basicInfo) {
            this.$set(this.currentProjectData, 'basicInfo', {})
          }
          this.$set(this.currentProjectData.basicInfo, 'catalogId', catalogId)
        }
      },
      // 保存
      handleSave() {
        switch (this.activeTab) {
          case 'scenario':
            this.saveWorkPlan()
            break
          case 'material':
            this.saveMaterial()
            break
          case 'auditNotice':
            this.$refs.auditNoticeTab.handleSaveDocument()
            break
          default:
            break
        }
      },
      // saveFiles 方法
      handleSaveFiles(data) {
        this.saveFiles(data)
      },
      // removeFile 方法
      handleRemoveFile(index, removedFile, currentFiles) {
        this.removeFile(index, removedFile, currentFiles)
      },
      // saveFiles 方法（来自 mixin 的方法，但需要在组件中实现）
      saveFiles(data) {
        try {
          if (!Array.isArray(this.formData.workPlan.attachmentIds)) {
            this.formData.workPlan.attachmentIds = []
          }
          if (!Array.isArray(data)) {
            console.warn('saveFiles方法期望接收数组类型参数')
            return
          }
          const newPaths = data
            .map((element) => {
              if (typeof element === 'string') {
                return element
              }
              return element?.savePath || element?.filePath || null
            })
            .filter((path) => path && typeof path === 'string')
          const uniquePaths = [
            ...new Set([...this.formData.workPlan.attachmentIds, ...newPaths]),
          ]
          this.formData.workPlan.attachmentIds = uniquePaths
        } catch (error) {
          console.error('处理文件路径时发生错误:', error)
        }
      },
      // removeFile 方法
      removeFile(index, removedFile, currentFiles) {
        try {
          const currentPaths = this.formData.workPlan.attachmentIds || []
          if (currentPaths.length > 0 && typeof currentPaths[0] === 'string') {
            currentPaths.splice(index, 1)
            this.formData.workPlan.attachmentIds = [...currentPaths]
          } else {
            const filteredPaths = currentPaths.filter((item) => {
              if (typeof item === 'string') {
                const fileName = item.substring(item.lastIndexOf('/') + 1)
                return fileName !== removedFile.fileName
              }
              return (
                item !== removedFile && item.fileName !== removedFile.fileName
              )
            })
            this.formData.workPlan.attachmentIds = filteredPaths
          }
        } catch (error) {
          console.error('删除文件时发生错误:', error)
        }
      },
      // 打开弹窗方法
      open(data, type) {
        console.log('taskDetail open - data:', data)
        console.log('taskDetail open - type:', type)

        // 设置项目数据
        if (data) {
          // 根据类型提取 projectId
          const projectId =
            type === 'chengben'
              ? data.projectId || data.id
              : data.id || data.projectId

          // 构造项目对象
          this.currentProjectData = {
            projectId: projectId,
            taskId:
              type === 'chengben'
                ? data.taskId || data.id
                : data.userTask?.id || data.taskId || data.id,
            ...data,
          }
        }

        // 打开弹窗
        this.dialogVisible = true
        this.activeTab = 'basicInfo'

        // 初始化数据
        if (this.currentProjectData && this.currentProjectData.projectId) {
          this.$nextTick(() => {
            this.initData()
          })
        }
      },
      // 保存工作方案
      saveWorkPlan() {
        this.scenarioData.saveScenario = true
        let data = {
          ...this.formData.workPlan,
          attachmentIds: this.formData.workPlan.attachmentIds.join(','),
          projectId: this.actualProject.projectId,
        }
        if (this.scenarioData.addScenario) {
          addCostProjectScenario(data)
            .then((res) => {
              this.scenarioData.saveScenario = false
              this.$message.success('保存成功')
            })
            .catch(() => {
              this.scenarioData.saveScenario = false
            })
        } else {
          updateCostProjectScenario(data)
            .then((res) => {
              this.scenarioData.saveScenario = false
              this.$message.success('保存成功')
            })
            .catch(() => {
              this.scenarioData.saveScenario = false
            })
        }
      },
      // 关闭
      handleClose() {
        this.dialogVisible = false
        this.$emit('close')
      },
    },
  }
</script>

<style scoped lang="scss">
  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .header-buttons {
      display: flex;
      gap: 10px;
    }
  }

  .tabs-container {
    margin-top: 10px;
  }

  ::v-deep .el-dialog__header {
    padding: 20px 20px 10px;
  }

  ::v-deep .el-dialog__body {
    padding: 10px 20px 20px;
  }
</style>
