<template>
  <div class="details-container">
    <el-drawer
      :visible.sync="visible"
      :title="dialogTitle"
      size="90%"
      @close="handleClose"
    >
      <!-- 操作按钮区域 -->
      <div class="btn-group">
        <el-button
          v-for="item in buttonData"
          :key="item.id"
          type="primary"
          @click="handleAuditPass(item)"
        >
          {{ item.value }}
        </el-button>
      </div>
      <!-- 标签页面 -->
      <el-tabs
        v-model="activeTab"
        type="card"
        class="audit-tabs"
        @tab-click="handleTabClick"
      >
        <el-tab-pane label="报送资料" name="submitData">
          <submit-data
            :id="id"
            :current-node="currentNode"
            :current-status="currentStatus"
            :materials="submitMaterials"
          />
        </el-tab-pane>
        <el-tab-pane label="成本调查表" name="costSurvey">
          <cost-survey
            :id="id"
            :current-node="currentNode"
            :current-status="currentStatus"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="currentNode !== 'clcs'"
          label="成本审核"
          name="costAudit"
        >
          <cost-audit
            :id="id"
            :selected-project="selectedProject"
            :current-node="currentNode"
            :current-status="currentStatus"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="currentNode !== 'clcs'"
          label="工作底稿"
          name="workDraft"
        >
          <work-draft
            :id="id"
            :current-node="currentNode"
            :current-status="currentStatus"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="currentNode !== 'clcs'"
          label="提取材料登记"
          name="extractMaterial"
        >
          <extract-material
            :id="id"
            :current-node="currentNode"
            :current-status="currentStatus"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="currentNode !== 'clcs' && currentNode !== 'sdsh'"
          label="成本审核意见"
          name="auditOpinion"
        >
          <audit-opinion
            :id="id"
            :current-node="currentNode"
            :current-status="currentStatus"
            @refresh="handleAuditOpinionRefresh"
            @close="handleClose"
          />
        </el-tab-pane>
        <el-tab-pane label="消息通知" name="messageNotify">
          <message-notify :id="id" />
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
    <!-- 补充资料弹窗 -->
    <el-dialog
      :visible.sync="showSupplementDialog"
      title="补充资料"
      width="500px"
      :modal="false"
    >
      <div class="dialog-content">
        <div class="form-item">
          <label class="form-label">补充意见:</label>
          <el-input
            v-model="additionalParams.content"
            type="textarea"
            :rows="6"
            placeholder="请输入补充意见"
            maxlength="500"
            show-word-limit
          />
        </div>
        <!-- <div class="form-item">
          <label class="form-label">发送方式:</label>
          <el-checkbox-group v-model="additionalParams.sendType">
            <el-checkbox label="site">站内消息</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
          </el-checkbox-group>
        </div> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showSupplementDialog = false">取消</el-button>
        <el-button type="primary" @click="submitSupplement">发送</el-button>
      </div>
    </el-dialog>

    <!-- 中止监审弹窗 -->
    <el-dialog
      :visible.sync="showAbortDialog"
      title="中止监审"
      width="500px"
      :modal="false"
    >
      <div class="dialog-content">
        <div class="form-item">
          <label class="form-label">中止意见:</label>
          <el-input
            v-model="additionalParams.content"
            type="textarea"
            :rows="6"
            placeholder="请输入中止意见"
            maxlength="500"
            show-word-limit
          />
        </div>
        <!-- <div class="form-item">
          <label class="form-label">发送方式:</label>
          <el-checkbox-group v-model="additionalParams.sendType">
            <el-checkbox label="site">站内消息</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
          </el-checkbox-group>
        </div> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAbortDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAbort">发送</el-button>
      </div>
    </el-dialog>

    <!-- 初审退回弹窗 -->
    <el-dialog
      :visible.sync="showRejectDialog"
      title="初审退回"
      width="500px"
      :modal="false"
    >
      <div class="dialog-content">
        <div class="form-item">
          <label class="form-label">退回意见:</label>
          <el-input
            v-model="additionalParams.content"
            type="textarea"
            :rows="6"
            placeholder="请输入退回意见"
            maxlength="500"
            show-word-limit
          />
        </div>
        <!-- <div class="form-item">
          <label class="form-label">发送方式:</label>
          <el-checkbox-group v-model="additionalParams.sendType">
            <el-checkbox label="site">站内消息</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
          </el-checkbox-group>
        </div> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showRejectDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReject">发送</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import costAudit from './costAudit.vue'
  import costSurvey from './costSurvey.vue'
  import submitData from './submitData.vue'
  import workDraft from './workDraft.vue'
  import extractMaterial from './extractMaterial.vue'
  import auditOpinion from './auditOpinion.vue'
  import messageNotify from './messageNotify.vue'
  import {
    getDataPreliminaryReviewButton,
    doProcessBtn,
  } from '@/api/dataPreliminaryReview'
  import { getTaskRequirementList } from '@/api/auditTaskProcessing'
  export default {
    name: 'Details',
    components: {
      costAudit,
      costSurvey,
      submitData,
      workDraft,
      extractMaterial,
      auditOpinion,
      messageNotify,
    },
    props: {
      visible: {
        type: Boolean,
        default: true,
      },
      id: {
        type: [String, Number],
        default: null,
      },
      selectedProject: {
        type: Object,
        default: () => ({}),
      },
      currentNode: {
        type: String,
        default: '',
      },
      currentStatus: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        buttonData: [], //资料初审按钮数据
        activeTab: 'submitData', // 默认选中报送资料标签页
        // 报送资料数据（从接口获取后下发给子组件）
        submitMaterials: [],
        // 弹窗显示状态
        showSupplementDialog: false,
        showAbortDialog: false,
        showRejectDialog: false,
        // 弹窗数据
        additionalParams: {},
        // 当前操作按钮信息
        currentButton: null,
      }
    },
    computed: {
      dialogTitle() {
        // 根据节点类型设置标题
        if (
          this.currentNode === 'sdshenhe' &&
          this.currentStatus === '审核中'
        ) {
          return '审核详情'
        } else if (this.currentNode === 'clcs') {
          return '成本调查详情'
        } else if (
          this.currentNode === 'yjgaozhi' ||
          this.currentNode === 'yjfk'
        ) {
          return '意见告知'
        }
        return '成本审核详情'
      },
    },
    watch: {
      visible(newVal) {
        // 监听visible变化，弹窗打开时设置标签页并获取按钮数据
        if (newVal && this.id) {
          // 使用 $nextTick 确保 props 已更新
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 弹窗打开时，无论什么情况都要获取资料初审按钮数据
            this.getPreliminaryReviewButton()
            // 若默认在报送资料页，加载报送资料
            if (this.activeTab === 'submitData') {
              this.loadSubmitMaterials()
            }
          })
        }
      },
      // 监听currentNode变化，如果弹窗已打开，更新标签页并重新获取按钮数据
      currentNode(newVal, oldVal) {
        if (this.visible && this.id && newVal && newVal !== oldVal) {
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 重新获取按钮数据
            this.getPreliminaryReviewButton()
          })
        }
      },
      // 监听currentStatus变化，如果弹窗已打开，更新标签页并重新获取按钮数据
      currentStatus(newVal, oldVal) {
        if (this.visible && this.id && newVal && newVal !== oldVal) {
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 重新获取按钮数据
            this.getPreliminaryReviewButton()
          })
        }
      },
      // 监听id变化，如果弹窗已打开，重新获取按钮数据
      id(newVal) {
        if (this.visible && newVal) {
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 获取按钮数据
            this.getPreliminaryReviewButton()
            // 任务变化时，若在报送资料页，刷新报送资料
            if (this.activeTab === 'submitData') {
              this.loadSubmitMaterials()
            }
          })
        }
      },
    },
    mounted() {
      // 设置标签页
      this.setActiveTab()
      // 如果组件挂载时弹窗已打开且有id，也要获取按钮数据
      if (this.visible && this.id) {
        this.$nextTick(() => {
          // 弹窗打开时，无论什么情况都要获取资料初审按钮数据
          this.getPreliminaryReviewButton()
          if (this.activeTab === 'submitData') {
            this.loadSubmitMaterials()
          }
        })
      }
    },
    methods: {
      // 根据 currentNode 和 currentStatus 设置活动标签页
      setActiveTab() {
        if (this.currentNode === 'sdsh' && this.currentStatus === '审核中') {
          this.activeTab = 'costAudit'
        } else if (this.currentNode === 'clcs') {
          // 如果 currentNode 是 'clcs'，显示成本调查表标签页
          this.activeTab = 'submitData'
        } else if (
          this.currentNode === 'yjgaozhi' ||
          this.currentNode === 'yjfk'
        ) {
          // 如果 currentNode 是 'yjgaozhi'，显示意见告知标签页（成本审核意见）
          this.activeTab = 'auditOpinion'
        } else {
          // 其他情况默认显示报送资料标签页
          this.activeTab = 'submitData'
        }
      },
      // 获取资料初审按钮
      async getPreliminaryReviewButton() {
        // 直接从 props 获取 currentNode，确保是最新的值
        const currentNode = this.currentNode

        // 构建参数对象
        const params = {
          taskId: this.id,
        }

        // 只有当 currentNode 有值时才添加 processNodeKey
        if (currentNode && currentNode.trim() !== '') {
          params.processNodeKey = currentNode === 'ccls' ? 'clcs' : currentNode
        }

        try {
          const response = await getDataPreliminaryReviewButton(params)
          this.buttonData = response.value || []
        } catch (error) {
          this.buttonData = []
        }
      },
      handleClose() {
        // 关闭弹窗时触发事件
        this.$emit('update:visible', false)
        this.$emit('close')
      },
      // 处理审核意见保存成功后的刷新
      handleAuditOpinionRefresh() {
        // 触发父组件刷新列表
        this.$emit('refresh')
      },
      open() {
        // 打开弹窗方法，供父组件通过ref调用
        this.$emit('update:visible', true)
      },
      handleTabClick(tab) {
        if (tab && tab.name === 'submitData' && this.id) {
          this.loadSubmitMaterials()
        }
      },
      async loadSubmitMaterials() {
        try {
          const resp = await getTaskRequirementList(this.id)
          const list = resp?.value || resp?.data || resp || []
          this.submitMaterials = Array.isArray(list) ? list : []
        } catch (e) {
          this.submitMaterials = []
        }
      },
      // 处理审核操作按钮点击
      handleAuditPass(item) {
        this.additionalParams = {
          content: '',
          // sendType: [], // 默认选中站内消息和短信通知
        }
        this.currentButton = item // 保存当前按钮信息
        console.log('点击的按钮数据:', item)
        const key = Number(item.key)
        if (key === 1) {
          this.showSupplementDialog = true
        } else if (key === 2) {
          // 中止监审
          this.showAbortDialog = true
        } else if (key === 4) {
          // 初审退回
          this.showRejectDialog = true
        } else {
          // 添加确认对话框
          this.$confirm(
            `确定要执行"${this.currentButton.value}"操作吗？`,
            '操作确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              this.executeAuditOperation()
            })
            .catch(() => {
              // 用户取消操作
              this.$message.info('已取消操作')
            })
        }
      },

      // 执行审核操作
      async executeAuditOperation() {
        if (!this.id) {
          this.$message.error('缺少任务ID')
          return
        }
        if (!this.currentButton) {
          this.$message.error('操作失败：缺少按钮信息')
          return
        }
        try {
          const params = {
            taskId: this.id,
            processNodeKey: this.currentNode,
            key: this.currentButton.key,
            // sendType: this.additionalParams.sendType?.join(','),
            content: this.additionalParams.content,
          }

          const response = await doProcessBtn(params)

          if (response && response.code === 200) {
            this.$message.success(this.currentButton.value + '操作成功')
            // 关闭所有弹窗
            this.showSupplementDialog = false
            this.showAbortDialog = false
            this.showRejectDialog = false
            // 关闭主弹窗
            this.handleClose()
            // 触发父组件刷新列表
            this.$emit('refresh')
          } else {
            this.$message.error(
              response?.message || this.currentButton.value + '操作失败'
            )
          }
        } catch (error) {
          this.$message.error(this.currentButton.value + '操作失败')
        }
      },

      // 提交补充资料
      submitSupplement() {
        if (
          !this.additionalParams.content ||
          !this.additionalParams.content.trim()
        ) {
          this.$message.error('请输入补充意见')
          return
        }
        if (this.currentButton) {
          this.executeAuditOperation(this.currentButton)
        } else {
          this.$message.error('操作失败：缺少按钮信息')
        }
      },

      // 提交中止监审
      submitAbort() {
        if (
          !this.additionalParams.content ||
          !this.additionalParams.content.trim()
        ) {
          this.$message.error('请输入中止意见')
          return
        }
        if (this.currentButton) {
          this.executeAuditOperation(this.currentButton)
        } else {
          this.$message.error('操作失败：缺少按钮信息')
        }
      },

      // 提交初审退回
      submitReject() {
        if (
          !this.additionalParams.content ||
          !this.additionalParams.content.trim()
        ) {
          this.$message.error('请输入退回意见')
          return
        }
        if (this.currentButton) {
          this.executeAuditOperation(this.currentButton)
        } else {
          this.$message.error('操作失败：缺少按钮信息')
        }
      },
    },
  }
</script>

<style scoped>
  .btn-group {
    margin-bottom: 20px;
    margin-left: 20px;
  }

  .btn-group .el-button {
    margin-right: 10px;
  }
  .details-container {
    width: 100%;
    height: 100%;
  }

  .audit-tabs {
    height: calc(100vh - 150px);
  }

  .audit-tabs .el-tabs__header {
    margin-bottom: 0;
    padding: 15px 15px 0;
    background: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
  }

  .audit-tabs .el-tabs__nav-wrap {
    padding-bottom: 10px;
  }

  .audit-tabs .el-tabs__content {
    height: calc(100% - 60px);
    padding: 15px;
    overflow-y: auto;
  }

  .audit-tabs .el-tab-pane {
    height: 100%;
  }

  /* 弹窗样式 */
  .dialog-content {
    padding: 10px 0;
  }

  .form-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
  }

  .form-label {
    display: inline-block;
    width: 100px;
    text-align: center;
    color: #606266;
    vertical-align: top;
    flex-shrink: 0;
  }

  .form-item .el-checkbox-group {
    display: inline-block;
    margin-left: 10px;
  }

  .form-item .el-checkbox {
    margin-right: 20px;
    vertical-align: middle;
  }

  .form-item .el-input,
  .form-item .el-textarea {
    flex: 1;
  }

  .form-item .el-input__inner {
    width: 100%;
    margin-left: 0;
  }
</style>
