<template>
  <el-dialog
    :visible.sync="visible"
    title="监审任务"
    width="80%"
    top="5vh"
    :close-on-click-modal="false"
    class="audit-task-manage-dialog"
    @close="handleClose"
  >
    <div class="audit-task-manage-container">
      <!-- 标签页容器 -->
      <div class="tabs-container">
        <el-tabs
          v-model="activeTab"
          type="border-card"
          @tab-click="handleTabClick"
        >
          <!-- 监审立项信息 -->
          <el-tab-pane label="监审立项信息" name="basicInfo">
            <basicInfoTab :project="formData.basicInfo" :is-view="isView" />
          </el-tab-pane>

          <!-- 监审工作方案 -->
          <el-tab-pane label="监审工作方案" name="scenario">
            <el-form
              v-loading="scenarioData.saveScenario"
              :model="formData.workPlan"
              label-width="150px"
              label-position="top"
              style="width: 50%"
              :disabled="isView"
            >
              <el-form-item label="监审项目基本情况" class="form-section">
                <el-input
                  v-model="formData.workPlan.basicInfo"
                  type="textarea"
                  :rows="5"
                  placeholder="(非必填写)"
                  class="form-textarea"
                  :maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item
                label="监审的范围、内容、重点及其他重要事项"
                class="form-section"
              >
                <el-input
                  v-model="formData.workPlan.scopeContent"
                  type="textarea"
                  :rows="5"
                  placeholder="(非必填写)"
                  class="form-textarea"
                  :maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="监审的步骤和方法" class="form-section">
                <el-input
                  v-model="formData.workPlan.stepsMethods"
                  type="textarea"
                  :rows="5"
                  placeholder="(非必填写)"
                  class="form-textarea"
                  :maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="其他有关内容" class="form-section">
                <el-input
                  v-model="formData.workPlan.otherContent"
                  type="textarea"
                  :rows="5"
                  placeholder="(非必填写)"
                  class="form-textarea"
                  :maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="相关资料" class="form-section">
                <div class="file-upload-wrapper">
                  <UploadComponent
                    :upload-mode="'multiple'"
                    :max-size="50 * 1024 * 1024"
                    :allowed-types="['xlsx', 'xls', 'doc', 'docx', 'pdf']"
                    :files-list="formData.workPlan.attachmentIds"
                    button-text="上传附件"
                    :is-disabled="isView"
                    @removeFile="removeFile"
                    @saveFiles="saveFiles"
                  />
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 报送资料要求 -->
          <el-tab-pane label="报送资料要求" name="material">
            <materialTab :project="project" :is-view="isView" />
          </el-tab-pane>

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

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

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

<script>
  import UploadComponent from '@/components/costAudit/UploadComponent.vue'
  import basicInfoTab from './BasicInfoTab.vue'
  import materialTab from './MaterialTab.vue'
  import surveyTab from './surveyTab.vue'
  import workflowTab from './workflowTab.vue'
  import auditNoticeTab from './auditNoticeTab.vue'
  import { taskMixin } from './index.js'
  import {
    addCostProjectScenario,
    updateCostProjectScenario,
  } from '@/api/taskCustomizedRelease.js'

  export default {
    name: 'TaskCustomizedReleaseDialog',
    components: {
      UploadComponent,
      basicInfoTab,
      materialTab,
      surveyTab,
      workflowTab,
      auditNoticeTab,
    },
    mixins: [taskMixin],
    props: {
      // 弹窗显示控制
      visible: {
        type: Boolean,
        default: false,
      },
      // 项目信息
      project: {
        type: Object,
        default: () => ({}),
      },
      // 是否查看模式
      isView: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {}
    },
    watch: {
      // 弹窗打开时默认切换到"监审立项信息"标签
      visible(newVal) {
        if (newVal) {
          this.activeTab = 'basicInfo'
          this.handleTabClick()
        }
      },
    },
    mounted() {},
    methods: {
      // 保存
      handleSave() {
        switch (this.activeTab) {
          case 'scenario':
            this.saveWorkPlan()
            break
          case 'material':
            this.saveMaterial()
            break
          case 'auditNotice':
            this.$refs.auditNoticeTab &&
              this.$refs.auditNoticeTab.handleSaveDocument &&
              this.$refs.auditNoticeTab.handleSaveDocument()
            break
          default:
            break
        }
      },
      // 保存文件
      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(index, removedFile) {
        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)
        }
      },
      // 保存工作方案
      saveWorkPlan() {
        this.scenarioData.saveScenario = true
        const data = {
          ...this.formData.workPlan,
          attachmentIds: this.formData.workPlan.attachmentIds.join(','),
          projectId: this.project.projectId,
        }
        if (this.scenarioData.addScenario) {
          addCostProjectScenario(data).then(() => {
            this.scenarioData.saveScenario = false
            this.$message.success('保存成功')
          })
        } else {
          updateCostProjectScenario(data).then(() => {
            this.scenarioData.saveScenario = false
            this.$message.success('保存成功')
          })
        }
      },
      // 返回
      handleBack() {
        this.$emit('backToList')
      },
      handleClose() {
        this.$emit('update:visible', false)
        this.$emit('close')
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';
</style>
