<template>
  <div class="apaas-custom-page-mydemo custom-page">
    <template v-if="!showReportDetail">
      <!-- <div class="page-header">
        <div class="title">
          报告管理
        </div>
        <div class="operation">
          <x-svg-icon
            :name="'refresh-icon'"
            class="pointer"
            style="cursor: pointer;"
            @click.native="handleRefresh()"
          ></x-svg-icon>
        </div>
      </div> -->

      <div class="page-search-panel">
        <div class="searched-fields">
          <!-- <div class="searched-field">
            <span class="fielded-label">厂家</span>
            <el-input v-model="searchPanelValue.manufacturerName" placeholder="请输入" />
          </div> -->
          <div class="searched-field">
            <span class="fielded-label">标题</span>
            <el-input v-model="searchPanelValue.template" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">状态</span>
            <el-select v-model="searchPanelValue.status" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in statusOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="searched-field">
            <span class="fielded-label">申请人</span>
            <el-input v-model="searchPanelValue.username" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">申请时间</span>
            <el-date-picker
              v-model="searchPanelValue.createDate"
              type="date"
              placeholder="请选择"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </div>
          <!-- <div class="searched-field">
            <span class="fielded-label">板块</span>
            <el-input v-model="searchPanelValue.plate" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">平台</span>
            <el-input v-model="searchPanelValue.platform" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">系列</span>
            <el-input v-model="searchPanelValue.series" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">细分市场</span>
            <el-input v-model="searchPanelValue.marketSegment" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">项目名称</span>
            <el-input v-model="searchPanelValue.projectName" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">项目编号</span>
            <el-input v-model="searchPanelValue.projectNumber" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">领域/模块</span>
            <el-input v-model="searchPanelValue.module" placeholder="请输入" />
          </div>
          <div class="searched-field">
            <span class="fielded-label">状态</span>
              <el-select
                v-model="searchPanelValue.status"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
              </el-select>
          </div>
          <div class="searched-field">
            <span class="fielded-label">标题</span>
            <el-input v-model="searchPanelValue.title" placeholder="请输入" />
          </div> -->
          <div class="search-actions">
            <el-button type="primary" @click="handleSearch">
              查询
            </el-button>
            <el-button @click="resetSearch">
              重置
            </el-button>
          </div>
        </div>
      </div>

      <!-- <div class="toolbar">
        <el-button type="primary" @click="handleCreate">新增</el-button>

      </div> -->
      <div class="page-data-list">
        <x-vxe-table
          ref="vxeTable"
          :border="true"
          :seqWidth="40"
          :colConfigs="tableConfig.colConfigs"
          :tableData="tableData"
          :rowDraggable="tableConfig.rowDraggable"
          :seqType="tableConfig.seqType"
          :pagination="pagination"
          :layout="tableConfig.layout"
          :seqConfig="tableConfig.seqConfig"
          :autoSize="tableConfig.autoSize"
          :pageConfig="tableConfig.pageConfig"
          class="block-table"
          @table-row-click="rowClickEvent"
          @size-change="pageSizeChange"
          @current-page-change="currentChange"
          @select-data-change="selectDataChange"
        >
          <template
            v-for="(colConfig, index) in tableConfig.colConfigs"
            v-slot:[colConfig.customHeadSlot]="{ column }"
          >
            <div v-if="colConfig.customHeadSlot" :key="index"> {{ column }} {{ colConfig }} </div>
          </template>

          <template
            v-for="(colConfig, index) in tableConfig.colConfigs"
            v-slot:[colConfig.customSlot]="{ row, rowIndex }"
          >
            <div v-if="colConfig.customSlot === 'status'" :key="index + '' + rowIndex">
              <span
                v-if="row[colConfig.prop] === 'APPROVING'"
                style="background: #E6A23C; padding: 4px 8px; color: white; border-radius: 20px;"
                >审核中</span
              >
              <span
                v-else-if="row[colConfig.prop] === 'COMPLETE'"
                style="background: #67C23A; padding: 4px 8px; color: white; border-radius: 20px;"
                >已完成</span
              >
              <span
                v-else-if="row[colConfig.prop] === 'DRAFT'"
                style="background: #909399; padding: 4px 8px; color: white; border-radius: 20px;"
                >草稿</span
              >
              <span
                v-else-if="row[colConfig.prop] === 'REJECTED'"
                style="background: #F56C6C; padding: 4px 8px; color: white; border-radius: 20px;"
                >已拒绝</span
              >
              <span
                v-else
                style="background: #909399; padding: 4px 8px; color: white; border-radius: 20px;"
                >-</span
              >
            </div>
            <div v-if="colConfig.customSlot === 'options'" :key="'op' + index + '' + rowIndex">
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleRowView(row)"
                >查看</a
              >
              <span style="width: 6px; display: inline-block"></span>
              <a
                v-if="row.filePath"
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleDownload(row)"
                >下载</a
              >
            </div>
          </template>

          <template slot="empty">
            <div class="table-empty">
              <x-empty-page></x-empty-page>
            </div>
          </template>
        </x-vxe-table>
      </div>
    </template>
    <report-detail
      v-else
      :detail="currentReportDetail"
      @close="closeReportDetail"
      @refresh="handleReportDetailRefresh"
    />

    <!-- 新增/修改报告弹窗 -->
    <el-dialog
      :title="dialogMode === 'edit' ? '修改报告' : '新增报告'"
      :visible.sync="createDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      :modal="false"
      custom-class="create-report-dialog"
      @close="handleDialogClose"
    >
      <div class="dialog-body-wrapper">
        <el-form
          ref="createForm"
          :model="createFormData"
          :rules="createFormRules"
          label-width="150px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="标题名称" prop="title">
                <el-input v-model="createFormData.title" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="厂家名称（全称）" prop="manufacturerName">
                <el-input v-model="createFormData.manufacturerName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品型号（全称）" prop="modelName">
                <el-input v-model="createFormData.modelName" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="厂家简称" prop="manufacturerAbbreviation">
                <el-input v-model="createFormData.manufacturerAbbreviation" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品型号简称" prop="modelAbbreviation">
                <el-input v-model="createFormData.modelAbbreviation" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品编号" prop="productNumber">
                <el-input v-model="createFormData.productNumber" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="领域/模块" prop="module">
                <el-input v-model="createFormData.module" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="板块" prop="plate">
                <el-input v-model="createFormData.plate" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="平台" prop="platform">
                <el-input v-model="createFormData.platform" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="系列" prop="series">
                <el-input v-model="createFormData.series" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="细分市场" prop="marketSegment">
                <el-input v-model="createFormData.marketSegment" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="createFormData.projectName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目编号" prop="projectNumber">
                <el-input v-model="createFormData.projectNumber" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="附件上传" prop="attachments">
            <el-upload
              ref="upload"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              :limit="1"
              accept=".doc,.pdf,.xls,.xlsx,.ppt,.pptx"
            >
              <el-button type="primary" icon="el-icon-upload">
                选择文件
              </el-button>
              <div slot="tip" class="el-upload__tip"
                >支持扩展名: .doc .pdf .xls .xlsx .ppt .pptx，仅支持上传一个文件</div
              >
            </el-upload>
          </el-form-item>
          <el-form-item label="说明" prop="explanation">
            <el-input
              v-model="createFormData.explanation"
              type="textarea"
              :rows="4"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
    <!-- 发起弹窗 -->
    <el-dialog
      title="发起"
      :visible.sync="launchDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
      @close="handleLaunchDialogClose"
    >
      <div class="dialog-body-wrapper">
        <div class="approval-workflow">
          <div class="workflow-title">
            审批环节
          </div>
          <div class="workflow-table">
            <table class="workflow-table-content">
              <thead>
                <tr>
                  <th class="step-name-col">
                    环节名称
                  </th>
                  <th class="handler-col">
                    处理人
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(step, index) in launchWorkflowSteps" :key="index" class="workflow-row">
                  <td class="step-name-cell">
                    <span class="step-name">
                      {{ step.name }}
                      <span v-if="step.required" class="required-mark">*</span>
                    </span>
                  </td>
                  <td class="handler-cell">
                    <el-select
                      v-model="step.handlers"
                      multiple
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请选择"
                      :remote-method="(query) => handleLaunchRemoteSearch(query, index)"
                      :loading="step.loading"
                      class="handler-select"
                      @change="(value) => handleLaunchHandlerChange(index, value)"
                    >
                      <el-option
                        v-for="person in step.options"
                        :key="person.userNumber"
                        :value="person.userId"
                        :label="person.username"
                      >
                        <span class="username-text">{{ person.username }}</span>
                        <span class="user-id-text">{{ person.userNumber }}</span>
                      </el-option>
                    </el-select>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleLaunchDialogClose">取消</el-button>
        <el-button type="primary" :loading="launching" @click="handleLaunchSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 审批弹窗 -->
    <el-dialog
      title="审核"
      :visible.sync="approvalDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
      @close="handleApprovalDialogClose"
    >
      <el-form ref="approvalForm" :model="approvalFormData" label-width="80px">
        <el-form-item label="审核">
          <el-radio-group v-model="approvalFormData.result">
            <el-radio label="PASS">
              通过
            </el-radio>
            <el-radio label="REJECT">
              退回
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="approvalFormData.opinion"
            type="textarea"
            :rows="4"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleApprovalDialogClose">
          取消
        </el-button>
        <el-button type="primary" :loading="approvalSubmitting" @click="handleApprovalSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ReportDetail from './reportDetail.vue'
import api from '@/api'
import { getUserId } from '@/utils'

export default {
  name: 'ReportPage',
  components: {
    ReportDetail
  },
  data: function() {
    return {
      searchPanelValue: {
        title: '',
        manufacturerName: '',
        modelName: '',
        productNumber: '',
        module: '',
        plate: '',
        platform: '',
        series: '',
        marketSegment: '',
        projectName: '',
        projectNumber: '',
        status: ''
      },
      statusOptions: [
        { id: 'DRAFT', label: '草稿' },
        { id: 'APPROVING', label: '审批中' },
        { id: 'COMPLETE', label: '已完成' },
        { id: 'REJECTED', label: '已拒绝' }
      ],
      tableData: [],
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      createDialogVisible: false,
      selectedFile: null,
      fileList: [],
      uploading: false,
      dialogMode: 'create', // 'create' 表示新增，'edit' 表示修改，'restart' 表示重新发起
      currentRestartRow: null, // 当前要重新发起的行数据
      currentEditRow: null, // 当前要修改的行数据
      launchDialogVisible: false, // 发起弹窗显示状态
      currentLaunchRow: null, // 当前要发起的行数据
      launchWorkflowSteps: [
        {
          name: '校对',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '审核',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '批准',
          required: true,
          handlers: [],
          options: [],
          loading: false
        }
      ],
      launching: false, // 发起中状态
      createFormData: {
        title: '',
        manufacturerName: '',
        modelName: '',
        manufacturerAbbreviation: '',
        modelAbbreviation: '',
        productNumber: '',
        module: '',
        plate: '',
        fileUrl: '',
        platform: '',
        series: '',
        marketSegment: '',
        projectName: '',
        projectNumber: '',
        explanation: ''
      },
      createFormRules: {
        title: [{ required: true, message: '请输入标题名称', trigger: 'blur' }],
        manufacturerName: [{ required: true, message: '请输入厂家名称（全称）', trigger: 'blur' }],
        modelName: [{ required: true, message: '请输入产品型号（全称）', trigger: 'blur' }],
        manufacturerAbbreviation: [{ required: true, message: '请输入厂家简称', trigger: 'blur' }],
        modelAbbreviation: [{ required: true, message: '请输入产品型号简称', trigger: 'blur' }],
        productNumber: [{ required: true, message: '请输入产品编号', trigger: 'blur' }],
        module: [{ required: true, message: '请输入领域/模块', trigger: 'blur' }],
        plate: [{ required: true, message: '请输入板块', trigger: 'blur' }],
        platform: [{ required: true, message: '请输入平台', trigger: 'blur' }],
        series: [{ required: true, message: '请输入系列', trigger: 'blur' }],
        marketSegment: [{ required: true, message: '请输入细分市场', trigger: 'blur' }],
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        projectNumber: [{ required: true, message: '请输入项目编号', trigger: 'blur' }]
      },
      approvalWorkflowSteps: [
        {
          name: '校对',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '审核',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },

        {
          name: '批准',
          required: true,
          handlers: [],
          options: [],
          loading: false
        }
      ],
      approvalDialogVisible: false,
      approvalFormData: {
        result: '',
        opinion: ''
      },
      approvalSubmitting: false,
      currentApprovalRow: null,
      showReportDetail: false,
      currentReportDetail: null,
      downloadingRowId: ''
    }
  },
  computed: {
    tableConfig() {
      return {
        rowDraggable: false,
        colConfigs: [
          { prop: 'title', label: '标题', showOverflowTooltip: true, minWidth: '140' },
          {
            prop: 'username',
            label: '申请人',
            showOverflowTooltip: true,
            minWidth: '160'
          },
          { prop: 'createdTime', label: '申请时间', showOverflowTooltip: true, minWidth: '160' },
          {
            prop: 'status',
            label: '状态',
            customSlot: 'status',
            align: 'center',
            minWidth: '100',
            fixed: 'right'
          },
          {
            prop: 'options',
            label: '操作',
            customSlot: 'options',
            align: 'center',
            width: '160',
            fixed: 'right'
          }
        ],
        seqType: 'seq',
        seqConfig: { fixed: true },
        layout: 'total, prev, pager, next, sizes'
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    handleCreate() {
      this.dialogMode = 'create'
      this.currentRestartRow = null
      this.currentEditRow = null
      this.createFormData = {
        title: '',
        manufacturerName: '',
        modelName: '',
        manufacturerAbbreviation: '',
        modelAbbreviation: '',
        productNumber: '',
        module: '',
        plate: '',
        fileUrl: '',
        platform: '',
        series: '',
        marketSegment: '',
        projectName: '',
        projectNumber: '',
        explanation: ''
      }
      this.fileList = []
      this.selectedFile = null
      this.createDialogVisible = true
      // 重置表单
      this.$nextTick(() => {
        if (this.$refs.createForm) {
          this.$refs.createForm.clearValidate()
        }
      })
    },
    handleEdit(row) {
      this.dialogMode = 'edit'
      this.currentEditRow = row
      this.currentRestartRow = null
      // 填充当前行的数据到表单
      this.createFormData = {
        title: row.title || '',
        manufacturerName: row.manufacturerName || '',
        modelName: row.modelName || '',
        manufacturerAbbreviation: row.manufacturerAbbreviation || '',
        modelAbbreviation: row.modelAbbreviation || '',
        productNumber: row.productNumber || '',
        module: row.module || '',
        plate: row.plate || '',
        fileUrl: row.fileUrl || row.filePath || '',
        platform: row.platform || '',
        series: row.series || '',
        marketSegment: row.marketSegment || '',
        projectName: row.projectName || '',
        projectNumber: row.projectNumber || '',
        explanation: row.explanation || ''
      }
      // 如果有文件路径，显示在文件列表中
      if (row.fileUrl || row.filePath) {
        this.fileList = [
          {
            name: row.title || '文件',
            url: row.fileUrl || row.filePath
          }
        ]
      } else {
        this.fileList = []
      }
      this.selectedFile = null
      this.createDialogVisible = true
      // 重置表单验证
      this.$nextTick(() => {
        if (this.$refs.createForm) {
          this.$refs.createForm.clearValidate()
        }
      })
    },
    handleLaunch(row) {
      this.currentLaunchRow = row
      // 重置审批环节
      this.launchWorkflowSteps = [
        {
          name: '校对',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '审核',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '批准',
          required: true,
          handlers: [],
          options: [],
          loading: false
        }
      ]
      this.launchDialogVisible = true
    },
    handleLaunchDialogClose() {
      this.launchDialogVisible = false
      this.currentLaunchRow = null
      // 重置审批环节
      this.launchWorkflowSteps = [
        {
          name: '校对',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '审核',
          required: true,
          handlers: [],
          options: [],
          loading: false
        },
        {
          name: '批准',
          required: true,
          handlers: [],
          options: [],
          loading: false
        }
      ]
    },
    handleLaunchSubmit() {
      // 验证必填环节是否已选择处理人
      const requiredStepsWithoutHandlers = this.launchWorkflowSteps.filter(
        (step) => step.required && (!step.handlers || step.handlers.length === 0)
      )
      if (requiredStepsWithoutHandlers.length > 0) {
        const stepNames = requiredStepsWithoutHandlers.map((step) => step.name).join('、')
        this.$message.warning(`请为必填环节"${stepNames}"选择处理人`)
        return
      }

      if (!this.currentLaunchRow) {
        this.$message.error('缺少报告信息')
        return
      }

      const reportId = this.currentLaunchRow.reportId || this.currentLaunchRow.id
      if (!reportId) {
        this.$message.error('缺少报告ID')
        return
      }

      // 构建提交数据
      const submitData = {
        reportId: reportId,
        proofreadUsers: this.launchWorkflowSteps[0].handlers,
        reviewUsers: this.launchWorkflowSteps[1].handlers,
        countersignUsers: [],
        approveUsers: this.launchWorkflowSteps[2].handlers
      }

      this.launching = true
      const request = {
        ...api.ADD_REPORT,
        params: submitData,
        disableSuccessMsg: true
      }

      this.$request(request)
        .asyncThen((resp) => {
          this.launching = false
          this.handleLaunchDialogClose()
          this.loadData() // 重新加载数据
          this.$message({
            type: 'success',
            message: '发起成功'
          })
        })
        .asyncErrorCatch((err) => {
          console.error('发起失败:', err)
          this.launching = false
          this.$message.error('发起失败，请重试')
        })
    },
    handleLaunchRemoteSearch(query, stepIndex) {
      const step = this.launchWorkflowSteps[stepIndex]
      if (!query || query.trim() === '') {
        // 空查询时，只保留已选择的人员在选项中
        if (step.handlers && step.handlers.length > 0) {
          const selectedOptions = step.options.filter((opt) => step.handlers.includes(opt.userId))
          step.options = selectedOptions
        } else {
          step.options = []
        }
        return
      }

      step.loading = true
      const trimmedQuery = query.trim()
      const request = {
        ...api.GET_ALLUSERS,
        params: {
          name: trimmedQuery
        },
        disableSuccessMsg: true
      }

      this.$request(request)
        .asyncThen((resp) => {
          const respData = resp && resp.data
          let result = []
          if (Array.isArray(respData)) {
            result = respData
          } else if (respData && Array.isArray(respData.result)) {
            result = respData.result
          } else if (respData && respData.data && Array.isArray(respData.data)) {
            result = respData.data
          }
          // 转换为选项格式
          const users = result
            .map((user) => ({
              userId: user.userId || user.id,
              username: user.username || user.name,
              userNumber: user.userNumber || user.userId || user.id
            }))
            .filter((user) => user.userId && user.userNumber)
          const existingIds = new Set(step.handlers || [])
          const filteredUsers = users.filter((user) => !existingIds.has(user.userId))
          const selectedOptions = (step.options || []).filter(
            (opt) => opt.userId && step.handlers && step.handlers.includes(opt.userId)
          )
          const optionsMap = new Map()
          selectedOptions.forEach((opt) => {
            if (opt.userNumber) {
              optionsMap.set(opt.userNumber, opt)
            }
          })
          filteredUsers.forEach((user) => {
            if (user.userNumber && !optionsMap.has(user.userNumber)) {
              optionsMap.set(user.userNumber, user)
            }
          })
          step.options = Array.from(optionsMap.values())
          step.loading = false
        })
        .asyncErrorCatch((err) => {
          console.error('搜索人员失败:', err)
          if (step.handlers && step.handlers.length > 0) {
            const selectedOptions = step.options.filter((opt) => step.handlers.includes(opt.userId))
            step.options = selectedOptions
          } else {
            step.options = []
          }
          step.loading = false
        })
    },
    handleLaunchHandlerChange(stepIndex, selectedIds) {
      // 处理人员选择变化
    },
    handleRestart(row) {
      this.dialogMode = 'restart'
      this.currentRestartRow = row
      this.currentEditRow = null
      // 填充当前行的数据到表单
      this.createFormData = {
        title: row.title || '',
        manufacturerName: row.manufacturerName || '',
        modelName: row.modelName || '',
        manufacturerAbbreviation: row.manufacturerAbbreviation || '',
        modelAbbreviation: row.modelAbbreviation || '',
        productNumber: row.productNumber || '',
        module: row.module || '',
        plate: row.plate || '',
        fileUrl: row.fileUrl || row.filePath || '',
        platform: row.platform || '',
        series: row.series || '',
        marketSegment: row.marketSegment || '',
        projectName: row.projectName || '',
        projectNumber: row.projectNumber || '',
        explanation: row.explanation || ''
      }
      // 重置文件列表
      this.fileList = []
      this.selectedFile = null
      this.createDialogVisible = true
      // 重置表单验证
      this.$nextTick(() => {
        if (this.$refs.createForm) {
          this.$refs.createForm.clearValidate()
        }
      })
    },
    handleDialogClose() {
      this.createDialogVisible = false
      this.dialogMode = 'create'
      this.currentRestartRow = null
      this.currentEditRow = null
      this.createFormData = {
        title: '',
        manufacturerName: '',
        modelName: '',
        manufacturerAbbreviation: '',
        modelAbbreviation: '',
        productNumber: '',
        module: '',
        plate: '',
        fileUrl: '',
        platform: '',
        series: '',
        marketSegment: '',
        projectName: '',
        projectNumber: '',
        explanation: ''
      }
      this.fileList = []
      this.selectedFile = null
      if (this.$refs.createForm) {
        this.$refs.createForm.clearValidate()
      }
    },
    handleFileChange(file, fileList) {
      // 验证文件类型
      const allowedTypes = ['.doc', '.pdf', '.xls', '.xlsx', '.ppt', '.pptx']
      const fileName = file.name.toLowerCase()
      const isValidType = allowedTypes.some((type) => fileName.endsWith(type))

      if (!isValidType) {
        this.$message.error('不支持的文件类型，仅支持 .doc .pdf .xls .xlsx .ppt .pptx')
        this.$refs.upload.handleRemove(file)
        return false
      }

      // 只保留最后一个文件（限制为单个文件）
      this.selectedFile = file && file.raw ? file.raw : null
      this.fileList = fileList.slice(-1)
    },
    handleFileRemove(file, fileList) {
      this.selectedFile = null
      this.fileList = []
    },
    handleFileUpload() {
      if (this.uploading || !this.selectedFile) {
        if (!this.selectedFile) {
          return Promise.resolve(null)
        }
        return Promise.resolve(null)
      }

      const file = this.selectedFile
      const formData = new FormData()
      formData.append('file', file)
      formData.append('createBy', getUserId())

      const request = {
        ...api.TEST_FILE_UPLOAD,
        params: formData,
        disableSuccessMsg: true
      }

      this.uploading = true
      // 显示全屏 loading 提示
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在上传文件，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return this.$upload(request, null, false)
        .then((resp) => {
          console.log('文件上传成功:', resp)
          loadingInstance.close()
          let fileUrl = ''
          if (resp.data && resp) {
            const url = resp.data
            fileUrl = url
            this.createFormData.fileUrl = fileUrl
          }
          return fileUrl
        })
        .catch((err) => {
          console.error('文件上传失败:', err)
          loadingInstance.close()
          this.$message.error('文件上传失败，请重试')
          throw err
        })
        .finally(() => {
          // 确保 loading 在所有情况下都能关闭
          if (loadingInstance) {
            loadingInstance.close()
          }
          this.uploading = false
        })
    },
    handleSubmit() {
      // 表单验证
      this.$refs.createForm.validate((valid) => {
        if (!valid) {
          return false
        }

        // 如果有文件，先上传文件获取文件路径
        const submitData = async () => {
          if (this.selectedFile) {
            try {
              const fileUrl = await this.handleFileUpload()
              // 将文件路径存储到 formData 中
              this.createFormData.fileUrl = fileUrl || ''
            } catch (err) {
              console.error('文件上传失败:', err)
              this.$message.error('文件上传失败，请重试')
              return
            }
          }

          // 根据 dialogMode 选择不同的接口
          let request
          if (this.dialogMode === 'edit' && this.currentEditRow) {
            // 修改：调用 EDIT_REPORT 接口
            const reportId = this.currentEditRow.reportId || this.currentEditRow.id
            request = {
              ...api.EDIT_REPORT,
              params: {
                reportId: reportId,
                ...this.createFormData,
                createBy: getUserId(),
                userId: getUserId()
              }
            }
          } else if (this.dialogMode === 'restart' && this.currentRestartRow) {
            // 重新发起：调用 RESTART_REPORT_APPROVAL 接口
            request = {
              ...api.RESTART_REPORT_APPROVAL,
              params: {
                reportId: this.currentRestartRow.id || this.currentRestartRow.reportId,
                ...this.createFormData,
                proofreadUsers: this.approvalWorkflowSteps[0].handlers,
                reviewUsers: this.approvalWorkflowSteps[1].handlers,
                countersignUsers: [],
                approveUsers: this.approvalWorkflowSteps[2].handlers,
                createBy: getUserId(),
                userId: getUserId()
              }
            }
          } else {
            // 新增：调用 SAVE_REPORT 接口（不传审批人员）
            request = {
              ...api.SAVE_REPORT,
              params: {
                ...this.createFormData,
                createBy: getUserId(),
                userId: getUserId()
              }
            }
          }

          this.$request(request)
            .asyncThen((resp) => {
              this.handleDialogClose()
              // 刷新列表
              this.loadData()
              this.$message({
                type: 'success',
                message: '提交成功'
              })
            })
            .asyncErrorCatch((err) => {
              console.error('提交失败:', err)
              this.$message({
                type: 'error',
                message: '提交失败'
              })
            })
        }

        submitData()
      })
    },
    handleRemoteSearch(query, stepIndex) {
      const step = this.approvalWorkflowSteps[stepIndex]
      if (!query || query.trim() === '') {
        // 空查询时，只保留已选择的人员在选项中
        if (step.handlers && step.handlers.length > 0) {
          const selectedOptions = step.options.filter((opt) => step.handlers.includes(opt.userId))
          const missingIds = step.handlers.filter(
            (id) => !selectedOptions.some((opt) => opt.userId === id)
          )
          if (missingIds.length > 0) {
            step.options = selectedOptions
          } else {
            step.options = selectedOptions
          }
        } else {
          step.options = []
        }
        return
      }

      step.loading = true
      const trimmedQuery = query.trim()
      const request = {
        ...api.GET_ALLUSERS,
        params: {
          name: trimmedQuery
        },
        disableSuccessMsg: true
      }

      this.$request(request)
        .asyncThen((resp) => {
          const respData = resp && resp.data
          let result = []
          if (Array.isArray(respData)) {
            result = respData
          } else if (respData && Array.isArray(respData.result)) {
            result = respData.result
          } else if (respData && respData.data && Array.isArray(respData.data)) {
            result = respData.data
          }
          // 转换为选项格式：{userId: user.userId, username: user.username, userNumber: user.userNumber}
          const users = result
            .map((user) => ({
              userId: user.userId || user.id,
              username: user.username || user.name,
              userNumber: user.userNumber || user.userId || user.id
            }))
            .filter((user) => user.userId && user.userNumber) // 过滤掉没有 userId 或 userNumber 的数据
          // step.handlers 现在是 userId 数组（因为 el-option 的 value 是 userId）
          const existingIds = new Set(step.handlers || [])
          // 过滤掉已选择的人员
          const filteredUsers = users.filter((user) => !existingIds.has(user.userId))
          // 合并：已选择的人员信息（从现有 options 中获取）+ 新的搜索结果
          const selectedOptions = (step.options || []).filter(
            (opt) => opt.userId && step.handlers && step.handlers.includes(opt.userId)
          )
          // 去重：使用 Map 确保每个 userNumber 只出现一次（使用 userNumber 作为 key 确保唯一性）
          const optionsMap = new Map()
          // 先添加已选择的选项
          selectedOptions.forEach((opt) => {
            if (opt.userNumber) {
              optionsMap.set(opt.userNumber, opt)
            }
          })
          // 再添加新的搜索结果
          filteredUsers.forEach((user) => {
            if (user.userNumber && !optionsMap.has(user.userNumber)) {
              optionsMap.set(user.userNumber, user)
            }
          })
          step.options = Array.from(optionsMap.values())
          step.loading = false
        })
        .asyncErrorCatch((err) => {
          console.error('搜索人员失败:', err)
          // 搜索失败时，保留已选择的人员信息
          if (step.handlers && step.handlers.length > 0) {
            const selectedOptions = step.options.filter((opt) => step.handlers.includes(opt.userId))
            step.options = selectedOptions
          } else {
            step.options = []
          }
          step.loading = false
        })
    },
    handleHandlerChange(stepIndex, selectedIds) {
      // 处理人员选择变化
      // selectedIds 是选中的 id 数组，格式: ['id1', 'id2', ...]
      // v-model 已经自动更新了 step.handlers 为 id 数组
      // 由于用户选择的人员通常是从搜索结果中选择的，信息应该已经在 options 中
      // 如果不在，等用户下次搜索时会自动补充
      // 确保已选择的人员信息在选项中，以便正确显示 username
    },
    handleDownloadTemplate() {
      // this.$message && this.$message.success && this.$message.success('开始下载模板')
    },
    handleDownload(row) {
      // 创建 a 标签并模拟点击下载
      const link = document.createElement('a')
      link.href = row.filePath
      // link.download = row.title ? `${row.title}` : '文件下载'
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      // this.$message.success('下载开始，请查看浏览器下载列表')
    },
    handlePreview(row) {
      this.$message && this.$message.info && this.$message.info('预览：' + (row.title || ''))
    },
    handleApprove(row) {
      this.currentApprovalRow = row
      this.approvalFormData = {
        result: '',
        opinion: ''
      }
      this.approvalDialogVisible = true
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.approvalForm) {
          this.$refs.approvalForm.clearValidate()
        }
      })
    },
    handleApprovalDialogClose() {
      this.approvalDialogVisible = false
      this.approvalFormData = {
        result: '',
        opinion: ''
      }
      this.currentApprovalRow = null
      // 清除表单验证
      if (this.$refs.approvalForm) {
        this.$refs.approvalForm.clearValidate()
      }
    },
    handleApprovalSubmit() {
      // 验证是否选择了审核结果
      if (!this.approvalFormData.result) {
        this.$message.warning('请选择审核结果（通过或退回）')
        return
      }

      if (!this.currentApprovalRow) {
        this.$message.error('缺少审批信息')
        return
      }

      // 构建提交数据
      const submitData = {
        flowId: this.currentApprovalRow.flowId,
        userId: getUserId(),
        result: this.approvalFormData.result, // 'PASS' 或 'REJECT'
        opinion: this.approvalFormData.opinion || ''
      }

      this.approvalSubmitting = true
      const request = {
        ...api.START_REPORT_APPROVAL,
        params: submitData,
        disableSuccessMsg: true
      }

      this.$request(request)
        .asyncThen((resp) => {
          this.approvalSubmitting = false
          this.handleApprovalDialogClose()
          this.loadData() // 重新加载数据
          this.approvalSubmitting = false
        })
        .asyncErrorCatch((err) => {
          console.error('审批提交失败:', err)
          this.approvalSubmitting = false
          this.$message.error('审批提交失败，请重试')
        })
    },
    pageSizeChange(size) {
      this.pagination.pageSize = size
    },
    rowClickEvent(row) {
      console.warn(row)
    },
    handleRowView(row) {
      // 获取报告ID
      const reportId = row.reportId || row.id
      if (!reportId) {
        this.$message.error('缺少报告ID，无法查看详情')
        return
      }

      // 只传递 reportId，让详情组件自己调用接口
      this.currentReportDetail = { reportId: reportId, flowId: row.flowId }
      this.showReportDetail = true
    },
    closeReportDetail() {
      this.showReportDetail = false
      this.currentReportDetail = null
    },
    handleReportDetailRefresh() {
      // 刷新列表数据
      this.loadData()
      // 关闭详情页
      this.closeReportDetail()
    },
    currentChange(currentPage) {
      this.pagination.currentPage = currentPage
      this.loadData()
    },
    selectDataChange(data) {
      this.$emit('select-data-change', data)
    },
    resetSearch() {
      // 重置所有搜索字段为空字符串
      this.searchPanelValue = {
        title: '',
        manufacturerName: '',
        modelName: '',
        productNumber: '',
        module: '',
        plate: '',
        platform: '',
        series: '',
        marketSegment: '',
        projectName: '',
        projectNumber: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSearch() {
      this.loadData()
    },
    handleRefresh() {
      this.pagination.currentPage = 1
      this.handleSearch()
    },
    loadData() {
      // 定义所有搜索字段，确保即使为空也传递空字符串
      const searchParams = {
        templateName: '',
        username: '',
        createDate: '',
        status: ''
      }

      // 合并用户输入的搜索值
      Object.keys(searchParams).forEach((key) => {
        if (this.searchPanelValue[key] !== undefined && this.searchPanelValue[key] !== null) {
          searchParams[key] = this.searchPanelValue[key]
        }
      })

      const request = {
        ...api.GET_REPORT_LIST_BY_CONDITION,
        params: {
          pageNumber: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          userId: getUserId(),
          ...searchParams
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          this.tableData = resp.data.result
          this.pagination.total = resp.data.count
        })
        .asyncErrorCatch((err) => {
          console.error('查询失败:', err)
        })
    }
  }
}
</script>

<style lang="scss">
.custom-page {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    align-items: center;
    height: 56px;
    position: relative;
    width: 100%;
    min-height: 56px;
    background: #fff;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;

    .title {
      color: #303133;
      font-weight: 700;
      margin-left: 20px;
      flex: 1;
      font-size: 12px;
    }

    .operation {
      display: flex;
      min-width: 330px;
      justify-content: flex-end;
      margin-right: 20px;
    }
  }

  .toolbar {
    background: #fff;
    padding: 0 20px 12px 20px;
    flex-shrink: 0;
  }

  .page-data-list {
    display: flex;
    flex: 1;
    min-height: 0;
    padding: 20px;

    .x-empty-page {
      top: 0;
    }
  }
}

.file-list {
  margin-top: 10px;

  .file-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #ebeef5;

    .el-icon-document {
      color: #909399;
      font-size: 16px;
      margin-right: 8px;
    }

    .file-name {
      flex: 1;
      font-size: 12px;
      color: #606266;
    }

    .file-remove {
      cursor: pointer;
      color: #909399;
      margin-left: 10px;

      &:hover {
        color: #409eff;
      }
    }
  }
}

.dialog-body-wrapper {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

::v-deep .create-report-dialog {
  .el-dialog__body {
    padding: 20px 20px 10px 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

::v-deep .el-upload-dragger {
  width: 100%;
  height: 180px;
}

::v-deep .el-form-item {
  margin-bottom: 18px;
}

.approval-workflow {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 20px;

  .workflow-title {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }

  .workflow-table {
    width: 100%;

    .workflow-table-content {
      width: 100%;
      border-collapse: collapse;
      border: 1px solid #ebeef5;

      thead {
        background: #f5f7fa;

        th {
          padding: 12px 16px;
          text-align: left;
          font-size: 14px;
          font-weight: 600;
          color: #303133;
          border-bottom: 1px solid #ebeef5;

          &.step-name-col {
            width: 120px;
          }

          &.handler-col {
            width: auto;
          }
        }
      }

      tbody {
        .workflow-row {
          &:not(:last-child) {
            border-bottom: 1px solid #ebeef5;
          }

          .step-name-cell {
            padding: 12px 16px;
            vertical-align: middle;

            .step-name {
              font-size: 14px;
              color: #303133;

              .required-mark {
                color: #f56c6c;
                margin-left: 4px;
              }
            }
          }

          .handler-cell {
            padding: 12px 16px;
            vertical-align: middle;

            .handler-select {
              width: 100%;
              min-width: 200px;

              ::v-deep .el-input__inner {
                height: 32px;
                line-height: 32px;
              }

              ::v-deep .el-tag {
                margin: 2px 4px 2px 0;
              }
            }
          }
        }
      }
    }
  }
}
.page-search-panel {
  background: white;
  padding: 16px 24px !important;
  border-bottom: 1px solid #ebeef5 !important;
  flex-shrink: 0;
  display: flex;
  flex-direction: column !important;
  gap: 16px;

  .search-actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 12px;

    ::v-deep .el-button {
      padding: 0 16px;
      font-size: 14px;
      border-radius: 4px;
      height: 32px;
      line-height: 32px;
    }
  }
}
.searched-fields {
  max-height: 200px !important;
  display: flex !important;
  flex-wrap: wrap !important;
  flex-direction: row !important;
  gap: 16px 32px !important;
  width: 100% !important;
}
.searched-field {
  display: flex !important;
  align-items: center !important;
  gap: 12px !important;
  flex: 1 1 calc((100% - 96px) / 4) !important;
  // min-width: 160px !important;
  max-width: calc(25% - 32px) !important;
  .fielded-label {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    white-space: nowrap;
    min-width: 80px !important;
    text-align: right;
    text-align-last: right;
    text-justify: inter-ideograph;
  }

  .el-input,
  .el-select {
    width: 170px;
  }

  ::v-deep .el-input__inner,
  ::v-deep .el-select .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
}
.el-select-dropdown__item {
  display: flex !important;
  justify-content: space-between !important;
  padding-right: 20px !important;
}
.username-text {
  color: #303133 !important;
  display: inline-block;
  text-align: right !important;
}
.user-id-text {
  color: #909399 !important;
  display: inline-block;
  margin-left: 20px;
  text-align: right !important;
}
</style>
