<template>
  <div class="opinions-content">
    <!-- 初步审核意见 -->
    <div class="opinion-section">
      <div class="opinion-header">
        <h3>成本审核初步意见</h3>
        <el-button
          class="ml10"
          type="primary"
          size="small"
          :disabled="isPreliminaryDisabled"
          @click="handleSavePreliminaryOpinion"
        >
          保存
        </el-button>
      </div>

      <el-form
        :model="preliminaryOpinionForm"
        label-width="180px"
        :class="{ 'disabled-section': isPreliminaryDisabled }"
      >
        <el-form-item label="被监审单位基本情况及主要财务状况：">
          <el-input
            v-model="preliminaryOpinionForm.basicSituation"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
            :disabled="isPreliminaryDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="监审项目现行执行的价格标准：">
          <el-input
            v-model="preliminaryOpinionForm.currentPriceStandard"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
            :disabled="isPreliminaryDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="监审项目的成本构成、数据核增核减情况、依据及理由："
        >
          <el-input
            v-model="preliminaryOpinionForm.costComposition"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
            :disabled="isPreliminaryDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="成本审核初步意见：">
          <el-input
            v-model="preliminaryOpinionForm.preliminaryOpinion"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
            :disabled="isPreliminaryDisabled"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 被审核单位反馈意见 -->
    <div v-if="isConclusionEditable" class="opinion-section">
      <div class="opinion-header">
        <h3>监审单位反馈意见：</h3>
      </div>

      <el-form :model="feedbackForm" label-width="180px">
        <el-form-item label="被监审单位反馈的意见：">
          <el-input
            v-model="feedbackForm.feedbackOpinion"
            disabled
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="被监审单位反馈资料：">
          <div v-if="feedbackForm.feedbackMaterial" class="file-item">
            <i class="iconfont-5039297 icon-wenjian"></i>
            <span
              class="file-link"
              @click="handleFileView(feedbackForm.feedbackMaterial)"
            >
              {{ getFileName(feedbackForm.feedbackMaterial) }}
            </span>
          </div>
          <div v-else class="no-file">
            <span style="color: #909399">暂无附件</span>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 成本审核结论意见 -->
    <div v-if="isConclusionEditable" class="opinion-section">
      <div class="opinion-header">
        <h3>成本审核结论意见</h3>
        <el-button
          class="ml10"
          type="primary"
          size="small"
          :disabled="!isConclusionEditable"
          @click="handleSaveConclusionOpinion"
        >
          保存
        </el-button>
      </div>

      <el-form :model="conclusionOpinionForm" label-width="180px">
        <el-form-item label="成本审核结论意见：">
          <el-input
            v-model="conclusionOpinionForm.conclusionOpinion"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
            :disabled="!isConclusionEditable"
          ></el-input>
        </el-form-item>
        <el-form-item label="其他需要说明的事项：">
          <el-input
            v-model="conclusionOpinionForm.otherExplanations"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
            :disabled="!isConclusionEditable"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model="conclusionOpinionForm.remark"
            type="textarea"
            :rows="3"
            maxlength="500"
            show-word-limit
            :disabled="!isConclusionEditable"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
  import {
    getPreliminaryOpinion,
    addPreliminaryOpinion,
  } from '@/api/audit/preliminaryOpinion'
  export default {
    name: 'AuditOpinion',
    props: {
      id: {
        type: [String, Number],
        default: null,
      },
      currentNode: {
        type: String,
        default: '',
      },
      currentStatus: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        // 审核意见表单数据
        preliminaryOpinionForm: {
          id: '',
          basicSituation: '',
          currentPriceStandard: '',
          costComposition: '',
          preliminaryOpinion: '',
        },

        feedbackForm: {
          feedbackOpinion: '',
          feedbackMaterial: '', // 反馈附件（单个URL字符串）
        },

        conclusionOpinionForm: {
          id: '',
          conclusionOpinion: '',
          otherExplanations: '',
          remark: '',
        },
      }
    },
    computed: {
      // 判断初步意见是否需要置灰（currentNode === 'yjfk' && status === '已反馈'）
      isPreliminaryDisabled() {
        return this.currentNode === 'yjfk' && this.currentStatus === '260'
      },
      // 判断结论意见是否可编辑（currentNode === 'yjfk' && status === '已反馈'）
      isConclusionEditable() {
        return this.currentNode === 'yjfk' && this.currentStatus === '260'
      },
    },
    watch: {
      id(newVal) {
        // 当 id 变化时，重新获取数据
        if (newVal) {
          this.getPreliminaryOpinionData()
        }
      },
    },
    mounted() {
      console.log(this.currentStatus, '意见反馈this.currentStatus')
      // 组件挂载时，如果有 id，获取数据
      if (this.id) {
        this.getPreliminaryOpinionData()
      }
    },
    methods: {
      // 获取初步审核意见数据
      async getPreliminaryOpinionData() {
        if (!this.id) {
          return
        }
        try {
          const res = await getPreliminaryOpinion({ taskId: this.id })
          if (res && res.value) {
            const data = res.value
            // 回显初步审核意见数据
            if (data.id) {
              this.preliminaryOpinionForm = {
                id: data.id,
                basicSituation: data.basicSituation || '',
                currentPriceStandard: data.currentPriceStandard || '',
                costComposition: data.costComposition || '',
                preliminaryOpinion: data.preliminaryOpinion || '',
              }
            }
            // 回显结论意见数据（如果接口返回了结论意见）
            if (
              data.conclusionOpinion !== undefined ||
              data.otherExplanations !== undefined ||
              data.remark !== undefined
            ) {
              this.conclusionOpinionForm = {
                id: data.conclusionId || data.id || '',
                conclusionOpinion: data.conclusionOpinion || '',
                otherExplanations: data.otherExplanations || '',
                remark: data.remark || '',
              }
            }
            // 回显反馈意见数据（如果接口返回了反馈意见）
            if (
              data.feedbackOpinion !== undefined ||
              data.feedbackMaterials !== undefined
            ) {
              // 处理单个附件（可能是字符串或数组的第一个元素）
              let feedbackMaterial = ''
              if (data.feedbackMaterials) {
                if (typeof data.feedbackMaterials === 'string') {
                  // 如果是字符串，直接使用
                  feedbackMaterial = data.feedbackMaterials
                } else if (
                  Array.isArray(data.feedbackMaterials) &&
                  data.feedbackMaterials.length > 0
                ) {
                  // 如果是数组，取第一个元素
                  const firstItem = data.feedbackMaterials[0]
                  if (typeof firstItem === 'string') {
                    feedbackMaterial = firstItem
                  } else if (firstItem && firstItem.url) {
                    feedbackMaterial = firstItem.url
                  } else if (
                    firstItem &&
                    firstItem.response &&
                    firstItem.response.savePath
                  ) {
                    feedbackMaterial = firstItem.response.savePath
                  }
                }
              }

              this.feedbackForm = {
                feedbackOpinion: data.feedbackOpinion || '',
                feedbackMaterial: feedbackMaterial,
              }
            }
          }
        } catch (error) {
          console.error('获取初步审核意见失败:', error)
          // 获取失败不影响页面显示，静默处理
        }
      },
      // 成本审核意见操作
      handleSavePreliminaryOpinion() {
        if (!this.id) {
          this.$message.error('缺少任务ID')
          return
        }

        // 判断是新增还是编辑（根据是否有 id）
        const formData = {
          basicSituation: this.preliminaryOpinionForm.basicSituation || '',
          currentPriceStandard:
            this.preliminaryOpinionForm.currentPriceStandard || '',
          costComposition: this.preliminaryOpinionForm.costComposition || '',
          preliminaryOpinion:
            this.preliminaryOpinionForm.preliminaryOpinion || '',
          taskId: this.id,
        }

        // 如果有 id，则是编辑，需要添加 id 字段
        if (this.preliminaryOpinionForm.id) {
          formData.id = this.preliminaryOpinionForm.id
        }

        addPreliminaryOpinion(formData)
          .then((res) => {
            if (res.code === 200) {
              this.$message({ type: 'success', message: '初步审核意见已保存' })
              // 保存成功后，如果有返回 id，更新表单中的 id
              if (res.value && res.value.id) {
                this.preliminaryOpinionForm.id = res.value.id
              }
              // 通知父组件刷新列表并关闭弹窗，要求分页回到第一页
              // this.$emit('refresh', { resetToFirst: true })
              // this.$emit('close')
            } else {
              this.$message({ type: 'error', message: res.message })
            }
          })
          .catch((error) => {
            // this.$message({ type: 'error', message: '保存失败，请稍后重试' })
            console.error('保存初步审核意见失败:', error)
          })
      },

      handleSaveConclusionOpinion() {
        if (!this.id) {
          this.$message.error('缺少任务ID')
          return
        }

        // 判断是新增还是编辑（根据是否有 id）
        // 传递所有字段（包括初步意见、结论意见和反馈意见）
        const formData = {
          // 成本监审意见数据（初步意见）
          basicSituation: this.preliminaryOpinionForm.basicSituation || '',
          currentPriceStandard:
            this.preliminaryOpinionForm.currentPriceStandard || '',
          costComposition: this.preliminaryOpinionForm.costComposition || '',
          preliminaryOpinion:
            this.preliminaryOpinionForm.preliminaryOpinion || '',
          // 成本审核结论意见数据
          conclusionOpinion: this.conclusionOpinionForm.conclusionOpinion || '',
          otherExplanations: this.conclusionOpinionForm.otherExplanations || '',
          remark: this.conclusionOpinionForm.remark || '',
          // 监审单位反馈意见数据
          feedbackOpinion: this.feedbackForm.feedbackOpinion || '',
          feedbackMaterials: this.feedbackForm.feedbackMaterial || '', // 反馈附件（单个URL字符串）
          taskId: this.id,
        }

        // 如果有初步意见的 id，则添加 id 字段（用于编辑）
        if (this.preliminaryOpinionForm.id) {
          formData.id = this.preliminaryOpinionForm.id
        }
        // 如果有结论意见的 id，也添加（可能是 conclusionId）
        if (
          this.conclusionOpinionForm.id &&
          this.conclusionOpinionForm.id !== this.preliminaryOpinionForm.id
        ) {
          formData.conclusionId = this.conclusionOpinionForm.id
        }

        addPreliminaryOpinion(formData)
          .then((res) => {
            if (res.code === 200) {
              this.$message({ type: 'success', message: '审核结论意见已保存' })
              // 保存成功后，如果有返回 id，更新表单中的 id
              if (res.value && res.value.id) {
                this.preliminaryOpinionForm.id = res.value.id
              }
              if (res.value && res.value.conclusionId) {
                this.conclusionOpinionForm.id = res.value.conclusionId
              }
              // 通知父组件刷新列表并关闭弹窗，要求分页回到第一页
              // this.$emit('refresh', { resetToFirst: true })
              // this.$emit('close')
            } else {
              this.$message({ type: 'error', message: res.message })
            }
          })
          .catch((error) => {
            // this.$message({ type: 'error', message: '保存失败，请稍后重试' })
            console.error('保存审核结论意见失败:', error)
          })
      },
      // 从URL获取文件名
      getFileNameFromUrl(url) {
        if (!url) return '未知文件'
        try {
          const urlParts = url.split('/')
          const fileName = urlParts[urlParts.length - 1]
          // 如果有查询参数，去除
          return fileName.split('?')[0] || '未知文件'
        } catch (e) {
          return '未知文件'
        }
      },
      // 获取文件名（支持对象和字符串）
      getFileName(file) {
        if (typeof file === 'string') {
          return this.getFileNameFromUrl(file)
        }
        if (file && file.name) {
          return file.name
        }
        if (file && file.url) {
          return this.getFileNameFromUrl(file.url)
        }
        return '未知文件'
      },
      // 查看文件
      handleFileView(file) {
        let fileUrl = ''
        if (typeof file === 'string') {
          fileUrl = file
        } else if (file && file.url) {
          fileUrl = file.url
        } else if (file && file.response) {
          fileUrl = file.response.savePath || file.response.url || ''
        } else if (file && file.savePath) {
          fileUrl = file.savePath
        }

        if (!fileUrl) {
          this.$message &&
            this.$message.warning &&
            this.$message.warning('文件地址无效')
          return
        }

        const normalized = this.normalizeUrl(fileUrl)
        const suggestName =
          (file && (file.name || file.fileName)) ||
          this.getFileName(file) ||
          '下载文件'
        this.downloadByFetch(normalized, suggestName).catch((e) => {
          console.error('文件下载失败: ', e)
        })
      },
      normalizeUrl(u) {
        if (!u) return ''
        if (/^https?:\/\//i.test(u)) return u
        const base = (window.context && window.context.form) || ''
        if (!base) return u
        if (u.startsWith('/')) return base + u
        return base.replace(/\/$/, '') + '/' + u
      },
      extractFileName(contentDisposition) {
        if (!contentDisposition) return ''
        const match = /filename[^;=\n]*=((['"])?.*?\2|[^;\n]*)/i.exec(
          contentDisposition
        )
        if (match && match[1]) {
          try {
            return decodeURIComponent(match[1].replace(/['"]/g, ''))
          } catch (e) {
            return match[1].replace(/['"]/g, '')
          }
        }
        return ''
      },
      async downloadByFetch(rawUrl, fallbackName) {
        const url = this.normalizeUrl(rawUrl)
        let loading
        try {
          loading = this.$baseLoading
            ? this.$baseLoading(1, '文件下载中...')
            : this.$loading({
                lock: true,
                text: '文件下载中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0,0,0,0.7)',
              })
          const res = await fetch(url, { method: 'GET' })
          if (!res.ok) throw new Error('下载失败')
          const blob = await res.blob()
          let fileName =
            this.extractFileName(res.headers.get('content-disposition')) ||
            fallbackName ||
            '下载文件'
          if (!/\.[a-zA-Z0-9]+$/.test(fileName)) {
            const extFromUrl = (
              url.split('?')[0].split('#')[0].split('.').pop() || ''
            ).toLowerCase()
            fileName = extFromUrl ? `${fileName}.${extFromUrl}` : fileName
          }
          const objectUrl = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = objectUrl
          link.download = fileName
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(objectUrl)
          this.$message &&
            this.$message.success &&
            this.$message.success('开始下载文件')
        } catch (e) {
          console.log(e.message || '文件下载失败')
        } finally {
          if (loading && loading.close) loading.close()
        }
      },
    },
  }
</script>

<style scoped>
  .opinions-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-top: -20px;
  }

  .opinion-section {
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 20px;
    margin-top: 20px;
  }

  .disabled-section {
    opacity: 0.7;
    background-color: #f5f5f5;
  }

  .opinion-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }

  .opinion-header h3 {
    margin: 0;
    font-size: 14px;
    font-weight: 500;
  }

  .opinion-section .el-form-item {
    margin-bottom: 15px;
  }

  .ml10 {
    margin-left: 10px;
  }

  .file-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .file-item:hover {
    background-color: #e4e7ed;
  }

  .file-item i {
    margin-right: 8px;
    color: #409eff;
    font-size: 16px;
  }

  .file-link {
    color: #409eff;
    text-decoration: none;
    cursor: pointer;
  }

  .file-link:hover {
    text-decoration: underline;
  }

  .no-file {
    color: #909399;
    padding: 8px 0;
  }
</style>
