<template>
  <div class="details-container">
    <el-drawer
      :visible.sync="drawerVisible"
      :title="dialogTitle"
      size="90%"
      @close="handleClose"
    >
      <!-- 操作按钮区域 -->
      <div class="btn-group">
        <div class="process-actions">
          <el-button type="primary" @click="handleNextStep">
            流转下一步
          </el-button>
          <el-button type="primary" @click="handlePrevStep">
            退回上一步
          </el-button>
          <el-button
            v-if="currentNode === 'cjbg'"
            type="primary"
            @click="handleAddTask"
          >
            办结任务
          </el-button>
          <el-button type="primary" @click="handleAssign">返回</el-button>
          <el-tooltip
            v-if="
              (currentNode !== 'clcs' && currentNode !== 'sdsh') ||
              currentNode === 'yjfk'
            "
            class="item"
            effect="dark"
            content="点击此按钮整体阶段将退回到实体审核,重新复核"
            placement="top-start"
          >
            <el-button type="primary" icon="el-icon-s-flag" @click="handleFh">
              复核
            </el-button>
          </el-tooltip>
        </div>
      </div>
      <!-- 标签页面 -->
      <el-tabs v-model="activeTab" type="card" class="audit-tabs">
        <el-tab-pane label="监审文书" name="submitData">
          <auditDocumentsMain
            :id="id"
            :project="project"
            :current-node="currentNode"
            :current-status="currentStatus"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="
            currentNode === 'jtsy' ||
            currentNode === 'cjbg' ||
            currentNode === 'gd'
          "
          label="集体审议"
          name="costSurvey"
        >
          <collectiveMain
            :id="id"
            :current-node="currentNode"
            :current-status="currentStatus"
            :project-name="projectName"
            :audit-object="auditObject"
            :is-editable="currentNode === 'jtsy'"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="currentNode === 'cjbg' || currentNode === 'gd'"
          label="出具结论"
          name="costAudit"
        >
          <conclusionMain
            :id="id"
            :active="activeTab === 'costAudit'"
            :current-node="currentNode"
            :current-status="currentStatus"
            :is-editable="currentNode === 'cjbg'"
            @saved="handleConclusionSaved"
          />
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
    <!-- 流转下一步/退回上一步弹窗 -->
    <el-dialog
      :visible.sync="showProcessDialog"
      :title="processDialogTitle"
      width="600px"
      :modal="false"
      custom-class="process-dialog"
    >
      <div class="dialog-content">
        <div class="form-item process-form-item">
          <label class="form-label">意见:</label>
          <div class="form-content">
            <el-input
              v-model="processParams.content"
              type="textarea"
              :rows="6"
              placeholder="请输入意见"
              maxlength="500"
              show-word-limit
            />
          </div>
        </div>
        <!-- <div class="form-item process-form-item">
          <label class="form-label">发送方式:</label>
          <div class="form-content">
            <el-checkbox-group v-model="processParams.sendType">
              <el-checkbox label="1">站内消息</el-checkbox>
              <el-checkbox label="2">短信通知</el-checkbox>
            </el-checkbox-group>
          </div>
        </div> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showProcessDialog = false">取消</el-button>
        <el-button type="primary" @click="submitProcess">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="showFhDialog"
      title="任务复核"
      width="600px"
      :modal="false"
      custom-class="process-dialog"
    >
      <div class="dialog-content">
        <div class="form-item process-form-item">
          <label class="form-label">意见:</label>
          <div class="form-content">
            <el-input
              v-model="processParams.content"
              type="textarea"
              :rows="6"
              placeholder="请输入意见"
              maxlength="500"
              show-word-limit
            />
          </div>
        </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="showFhDialog = false">取消</el-button>
        <el-button type="primary" @click="submitFh">发送</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import auditDocumentsMain from './auditDocumentsMain'
  import collectiveMain from './collectiveMain'
  import conclusionMain from './conclusionMain'
  import {
    getDataPreliminaryReviewButton,
    doProcessBtn,
  } from '@/api/dataPreliminaryReview'
  import { getReviewTask } from '@/api/audit/reviewTask'
  export default {
    name: 'Details',
    components: {
      auditDocumentsMain,
      collectiveMain,
      conclusionMain,
    },
    props: {
      visible: {
        type: Boolean,
        default: true,
      },
      project: {
        type: Object,
        default: () => {},
      },
      id: {
        type: [String, Number],
        default: null,
      },
      currentNode: {
        type: String,
        default: '',
      },
      currentStatus: {
        type: String,
        default: '',
      },
      projectName: {
        type: String,
        default: '',
      },
      auditObject: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        buttonData: [], //资料初审按钮数据
        activeTab: 'submitData', // 默认选中报送资料标签页
        drawerVisible: this.visible, // 本地变量控制drawer显示状态
        // 弹窗显示状态
        showSupplementDialog: false,
        showAbortDialog: false,
        showRejectDialog: false,
        showProcessDialog: false, // 流转下一步/退回上一步弹窗
        showFhDialog: false,
        // 弹窗数据
        additionalParams: {},
        // 当前操作按钮信息
        currentButton: null,
        // 流转/退回操作参数
        processParams: {
          content: '', // 意见
          // sendType: [], // 发送方式
        },
        // 当前操作类型：'next' 流转下一步, 'prev' 退回上一步
        currentProcessType: '',
      }
    },
    computed: {
      dialogTitle() {
        // 基础标题
        let baseTitle = ''
        // 根据节点类型设置标题
        if (
          this.currentNode === 'sdshenhe' &&
          this.currentStatus === '审核中'
        ) {
          baseTitle = '审核详情'
        } else if (this.currentNode === 'clcs') {
          baseTitle = '成本调查详情'
        } else if (
          this.currentNode === 'yjgaozhi' ||
          this.currentNode === 'yjfk'
        ) {
          baseTitle = '意见告知'
        } else {
          baseTitle = '成本审核详情'
        }

        // 添加项目名称和监审对象
        let titleParts = [baseTitle]
        if (this.projectName) {
          titleParts.push(` - ${this.projectName}`)
        }
        if (this.auditObject) {
          titleParts.push(` (${this.auditObject})`)
        }

        return titleParts.join('')
      },
      // 流转/退回/办结弹窗标题
      processDialogTitle() {
        if (this.currentProcessType === 'next') {
          return '流转下一步'
        } else if (this.currentProcessType === 'prev') {
          return '退回上一步'
        } else if (this.currentProcessType === 'complete') {
          return '办结任务'
        }
        return '操作'
      },
    },
    watch: {
      visible(newVal) {
        // 监听visible prop变化，更新本地drawerVisible变量
        this.drawerVisible = newVal
        // 弹窗打开时设置标签页并获取按钮数据
        if (newVal && this.id) {
          // 使用 $nextTick 确保 props 已更新
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 弹窗打开时，无论什么情况都要获取资料初审按钮数据
            this.getPreliminaryReviewButton()
          })
        }
      },
      // 监听currentNode变化，如果弹窗已打开，更新标签页并重新获取按钮数据
      currentNode(newVal, oldVal) {
        if (this.drawerVisible && this.id && newVal && newVal !== oldVal) {
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 重新获取按钮数据
            this.getPreliminaryReviewButton()
          })
        }
      },
      // 监听currentStatus变化，如果弹窗已打开，更新标签页并重新获取按钮数据
      currentStatus(newVal, oldVal) {
        if (this.drawerVisible && this.id && newVal && newVal !== oldVal) {
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 重新获取按钮数据
            this.getPreliminaryReviewButton()
          })
        }
      },
      // 监听id变化，如果弹窗已打开，重新获取按钮数据
      id(newVal) {
        if (this.drawerVisible && newVal) {
          this.$nextTick(() => {
            // 设置标签页
            this.setActiveTab()
            // 获取按钮数据
            this.getPreliminaryReviewButton()
          })
        }
      },
    },
    mounted() {
      // 设置标签页
      this.setActiveTab()
      // 如果组件挂载时弹窗已打开且有id，也要获取按钮数据
      if (this.drawerVisible && this.id) {
        this.$nextTick(() => {
          // 弹窗打开时，无论什么情况都要获取资料初审按钮数据
          this.getPreliminaryReviewButton()
        })
      }
    },
    methods: {
      // 根据 currentNode 和 currentStatus 设置活动标签页
      setActiveTab() {},
      // 获取资料初审按钮
      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.drawerVisible = false
        this.$emit('update:visible', false)
        this.$emit('close')
      },
      // 处理审核意见保存成功后的刷新
      handleAuditOpinionRefresh() {
        // 触发父组件刷新列表
        this.$emit('refresh')
      },
      open() {
        // 打开弹窗方法，供父组件通过ref调用
        this.drawerVisible = true
        this.$emit('update:visible', true)
      },
      // 处理结论保存成功
      handleConclusionSaved() {
        // 关闭弹窗
        this.handleClose()
        // 触发父组件刷新列表
        this.$emit('refresh')
      },
      // 处理返回按钮点击
      handleAssign() {
        // 关闭弹窗
        this.handleClose()
        // 触发父组件刷新列表
        this.$emit('refresh')
      },
      // 处理审核操作按钮点击
      handleAuditPass(item) {},

      // 流转下一步
      handleNextStep() {
        this.currentProcessType = 'next'
        this.processParams = {
          content: '',
          // sendType: [],
        }
        this.showProcessDialog = true
      },

      // 退回上一步
      handlePrevStep() {
        this.currentProcessType = 'prev'
        this.processParams = {
          content: '',
          // sendType: [],
        }
        this.showProcessDialog = true
      },

      // 办结任务
      handleAddTask() {
        this.currentProcessType = 'complete'
        this.processParams = {
          content: '',
          // sendType: [],
        }
        this.showProcessDialog = true
      },

      // 提交流转/退回操作
      async submitProcess() {
        if (!this.id) {
          this.$message.error('缺少任务ID')
          return
        }

        // 验证发送方式
        // if (
        //   !this.processParams.sendType ||
        //   this.processParams.sendType.length === 0
        // ) {
        //   this.$message.warning('请选择至少一种发送方式')
        //   return
        // }

        try {
          // 根据操作类型确定key值
          let keyValue
          if (this.currentProcessType === 'next') {
            keyValue = 7 // 流转下一步
          } else if (this.currentProcessType === 'prev') {
            keyValue = 6 // 退回上一步
          } else if (this.currentProcessType === 'complete') {
            keyValue = 3 // 办结任务
          }

          const params = {
            taskId: this.id,
            processNodeKey: this.currentNode,
            key: keyValue,
            // sendType: this.processParams.sendType.join(','), // 发送方式用","分割
            content: this.processParams.content || '', // 意见
          }

          const response = await getReviewTask(params)

          if (response && response.code === 200) {
            // 根据操作类型显示成功消息
            let actionText
            if (this.currentProcessType === 'next') {
              actionText = '流转下一步'
            } else if (this.currentProcessType === 'prev') {
              actionText = '退回上一步'
            } else if (this.currentProcessType === 'complete') {
              actionText = '办结任务'
            }
            this.$message.success(response.message)
            // 关闭弹窗
            this.showProcessDialog = false
            // 重置参数
            this.processParams = {
              content: '',
              // sendType: [],
            }
            this.currentProcessType = ''
            // 关闭主弹窗
            this.handleClose()
            // 触发父组件刷新列表
            this.$emit('refresh')
          }
        } catch (error) {
          // 根据操作类型显示失败消息
          let actionText
          if (this.currentProcessType === 'next') {
            actionText = '流转下一步'
          } else if (this.currentProcessType === 'prev') {
            actionText = '退回上一步'
          } else if (this.currentProcessType === 'complete') {
            actionText = '办结任务'
          }
          // this.$message.error(actionText + '操作失败')
          console.error(actionText + '操作失败:', error)
        }
      },

      // 执行审核操作
      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)
          this.handleOperationResponse(response)
        } catch (error) {
          // this.$message.error(this.currentButton.value + '操作失败')
          console.error(this.currentButton.value + '操作失败')
        }
      },

      // 处理操作响应
      handleOperationResponse(response) {
        if (response && response.code === 200) {
          this.$message.success(this.currentButton.value + '操作成功')
          // 关闭所有弹窗
          this.showSupplementDialog = false
          this.showAbortDialog = false
          this.showRejectDialog = false
          this.showProcessDialog = false
          // 关闭主弹窗
          this.handleClose()
          // 触发父组件刷新列表
          this.$emit('refresh')
        } else {
          this.$message.error(
            response?.message || this.currentButton.value + '操作失败'
          )
        }
      },
      handleFh() {
        this.showFhDialog = true
      },
      async submitFh() {
        if (!this.processParams.content || !this.processParams.content.trim()) {
          this.$message.error('请输入退回意见')
          return
        }
        const params = {
          taskId: this.id,
          processNodeKey: this.currentNode,
          key: 8,
          content: this.processParams.content,
        }
        const response = await doProcessBtn(params)
        if (response && response.code === 200) {
          this.$message.success('操作成功')
          // 关闭所有弹窗
          this.showFhDialog = false
          this.showSupplementDialog = false
          this.showAbortDialog = false
          this.showRejectDialog = false
          this.showProcessDialog = false
          // 关闭主弹窗
          this.handleClose()
          // 触发父组件刷新列表
          this.$emit('refresh')
        } else {
          this.$message.error(response?.message || '操作失败')
        }
      },
    },
  }
</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 {
    margin-bottom: 20px;
  }

  .form-label {
    display: inline-block;
    width: 100px;
    text-align: right;
    margin-right: 0;
    color: #606266;
    vertical-align: middle;
  }

  .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__inner {
    width: calc(100% - 115px);
    margin-left: 115px;
  }

  /* 流转/退回弹窗样式优化 */
  .process-dialog .dialog-content {
    padding: 20px 0;
  }

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

  .process-dialog .process-form-item:last-child {
    margin-bottom: 0;
  }

  .process-dialog .form-label {
    width: 80px;
    text-align: left;
    margin-right: 8px;
    color: #303133;
    font-size: 14px;
    line-height: 32px;
    flex-shrink: 0;
  }

  .process-dialog .form-content {
    flex: 1;
  }

  .process-dialog .form-content .el-textarea {
    width: 100%;
  }

  .process-dialog .form-content .el-checkbox-group {
    display: flex;
    /* flex-direction: column; */
  }

  .process-dialog .form-content .el-checkbox {
    margin-right: 0;
    margin-left: 12px;
  }

  .process-dialog .form-content .el-checkbox:last-child {
    margin-bottom: 0;
  }

  .process-dialog .dialog-footer {
    text-align: right;
    padding-top: 10px;
  }
</style>
