<template>
  <div class="supervision-review-doc-manage content-container">
    <!-- 列表视图 -->
    <div v-if="activeView === 'list'" class="list-view">
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" size="small">
          <!-- 文本名称输入框 -->
          <el-form-item label="文书名称:">
            <el-input
              v-model="searchForm.documentName"
              placeholder="请输入文书名称"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 是否启用下拉选择 -->
          <el-form-item label="是否启用:">
            <el-select
              v-model="searchForm.status"
              placeholder="全部"
              clearable=""
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>

          <!-- 搜索和重置按钮 -->
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button
              plain
              type="primary"
              icon="el-icon-refresh"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <el-button
          v-region-permission="{
            category: 'auditReviewDocManage',
            action: 'add',
          }"
          plain
          type="success"
          icon="el-icon-circle-plus"
          @click="handleAdd"
        >
          添加
        </el-button>
        <el-button
          v-region-permission="{
            category: 'auditReviewDocManage',
            action: 'delete',
          }"
          plain
          type="danger"
          icon="el-icon-delete"
          :disabled="selectedRows.length === 0"
          @click="handleDelete"
        >
          删除
        </el-button>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          align="center"
          @selection-change="handleSelectionChange"
        >
          <template slot="empty">
            <Empty></Empty>
          </template>
          <!-- 多选列 -->
          <el-table-column
            type="selection"
            width="55"
            show-overflow-tooltip
            align="center"
          ></el-table-column>

          <!-- 序号列 -->
          <el-table-column
            type="index"
            label="序号"
            width="60"
            show-overflow-tooltip
            align="center"
          ></el-table-column>

          <!-- 监审文书名称列 -->
          <el-table-column
            prop="documentName"
            label="监审文书名称"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <div class="text-ellipsis">{{ scope.row.documentName }}</div>
            </template>
          </el-table-column>

          <!-- 别名列 -->
          <el-table-column
            prop="alias"
            label="别名"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <div class="text-ellipsis">{{ scope.row.alias }}</div>
            </template>
          </el-table-column>

          <!-- 类型列 -->
          <el-table-column
            prop="type"
            label="类型"
            width="120"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <span>
                {{ getDictName('documentType', scope.row.type) }}
              </span>
            </template>
          </el-table-column>

          <!-- 是否启用列（开关） -->
          <el-table-column
            prop="status"
            label="是否启用"
            width="120"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                v-region-permission="{
                  category: 'auditReviewDocManage',
                  action: 'edit',
                  displayMode: 'disabled',
                }"
                active-color="#13ce66"
                active-value="1"
                inactive-value="0"
                @change="handleSwitchChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <!-- 创建人列 -->
          <el-table-column
            prop="createBy"
            label="创建人"
            width="120"
            show-overflow-tooltip
            align="center"
          ></el-table-column>

          <!-- 最后更新时间列 -->
          <el-table-column
            prop="updateTime"
            label="最后更新时间"
            width="120"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.updateTime ? scope.row.updateTime.split(' ')[0] : ''
                }}
              </div>
              <div>
                {{
                  scope.row.updateTime ? scope.row.updateTime.split(' ')[1] : ''
                }}
              </div>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column
            label="操作"
            width="180"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                v-region-permission="{
                  category: 'auditReviewDocManage',
                  action: 'view',
                }"
                type="text"
                size="mini"
                @click="handleDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button
                v-region-permission="{
                  category: 'auditReviewDocManage',
                  action: 'edit',
                }"
                type="text"
                size="mini"
                @click="handleEdit(scope.row)"
              >
                修改
              </el-button>
              <el-button
                v-region-permission="{
                  category: 'auditReviewDocManage',
                  action: 'delete',
                }"
                type="text"
                size="mini"
                class="delete-btn"
                @click="handleDeleteRow(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 修改视图 -->
    <div v-else-if="activeView === 'edit'" class="edit-view">
      <div class="edit-header">
        <el-button plain type="primary" @click="backToList">
          <i class="el-icon-arrow-left"></i>
          返回列表
        </el-button>
      </div>
      <h2 v-if="!isDisabled">
        {{ formData.id ? '修改文书模板' : '添加文书模板' }}
      </h2>
      <h2 v-else>详情</h2>

      <!-- 步骤条导航 -->
      <el-steps :active="activeStep" align-center class="steps-container">
        <el-step title="基础信息填写"></el-step>
        <el-step title="模板内容配置"></el-step>
      </el-steps>

      <!-- 步骤内容区域 -->
      <div class="step-content">
        <!-- 步骤1: 基础信息填写 -->
        <div v-if="activeStep === 0" class="form-container">
          <el-form
            ref="basicForm"
            :model="formData"
            :rules="formRules"
            label-width="120px"
            class="basic-info-form"
            :disabled="isDisabled"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="监审文书名称:" prop="documentName">
                  <el-input
                    v-model="formData.documentName"
                    v-pinyin-abbreviation="{
                      target: 'formData.alias',
                    }"
                    placeholder="请输入监审文书名称"
                    maxlength="50"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="监审文书别名:" prop="alias">
                  <el-input
                    v-model="formData.alias"
                    placeholder="请输入监审文书别名"
                    maxlength="50"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="类型:" prop="type">
                  <el-select
                    v-model="formData.type"
                    style="width: 100%"
                    placeholder="请选择类型"
                  >
                    <el-option
                      v-for="item in dictData['documentType']"
                      :key="item.key"
                      :label="item.name"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否需要文号:" prop="isWh">
                  <el-radio-group v-model="formData.isWh">
                    <el-radio label="0">是</el-radio>
                    <el-radio label="1">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="说明:" prop="description">
                  <el-input
                    v-model="formData.description"
                    type="textarea"
                    placeholder="请输入说明"
                    maxlength="200"
                    show-word-limit
                    :rows="4"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-form-item label="*数据来源:" prop="dataSourceType">
              <el-radio-group v-model="formData.dataSourceType">
                <el-radio label="database_table">数据库表</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              v-if="formData.dataSourceType === 'database_table'"
              label="数据库表:"
              prop="tableId"
            >
              <el-input
                v-model="formData.surveyTemplateName"
                style="width: 38%"
                disabled
              ></el-input>
              <el-button type="primary" @click="handleAddCostSurvey">
                选择数据库表
              </el-button>
              <el-select
                v-model="formData.tableId"
                placeholder="请选择数据库表"
              >
                <el-option label="w_cbmx" :value="1"></el-option>
              </el-select>
            </el-form-item> -->
          </el-form>
        </div>

        <!-- 步骤2: 模板内容配置 - 左右布局 -->
        <div v-if="activeStep === 1" class="template-config-container">
          <div class="layout-wrapper">
            <!-- 左侧：上传模板和预览/修改标签页 -->
            <div class="left-panel">
              <!-- 上传模板按钮 -->
              <UploadComponent
                :upload-mode="'single'"
                :max-size="50 * 1024 * 1024"
                :allowed-types="['xlsx', 'xls', 'doc', 'docx', 'pdf']"
                :files-list="formData.fileUrl"
                action-url="/api/file/v1/tempUpload"
                button-text="上传模板"
                :is-disabled="isDisabled"
                @removeFile="removeFile"
                @saveFiles="saveFiles"
              />
              <!-- 预览/修改标签页 -->
              <template-preview-edit
                :active-tab="activeTab"
                :file-url="fileUrl"
              />
            </div>

            <!-- 右侧：数据项表格 -->
            <div class="right-panel">
              <div class="data-fields-section">
                <div class="data-fields-title">以下为数据项内容</div>
                <el-table
                  :data="costDocumentTemplateFiles"
                  border
                  style="width: 100%"
                >
                  <el-table-column prop="tableName" label="表名" align="center">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.tableName"
                        clearable
                        placeholder="请输入表名（英文）"
                        :disabled="isDisabled"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="colName" label="列名" align="center">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.colName"
                        clearable
                        placeholder="请输入列名（英文）"
                        :disabled="isDisabled"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="whereName"
                    label="条件名"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.whereName"
                        clearable
                        placeholder="请输入条件名"
                        :disabled="isDisabled"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="whereValue"
                    label="条件值"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.whereValue"
                        clearable
                        placeholder="请输入条件值"
                        :disabled="isDisabled"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="pinyin"
                    label="拼音"
                    align="center"
                    width="120"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    prop="originalText"
                    label="名称"
                    align="center"
                    width="120"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    prop="labelValue"
                    label="标签"
                    align="center"
                    width="120"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <span>
                        {{ scope.row.labelValue }}
                      </span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="edit-actions">
        <el-button
          v-if="activeStep === 1"
          type="primary"
          plain
          @click="handlePrevStep"
        >
          上一步
        </el-button>
        <el-button
          v-if="activeStep === 0"
          type="primary"
          plain
          @click="handleNextStep"
        >
          下一步
        </el-button>
        <el-button
          v-if="!isDisabled"
          type="primary"
          plain
          style="margin-left: 20px"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </div>
    <!-- 成本调查表表单 -->
    <el-dialog
      title="关联成本调查表"
      :visible.sync="costSurveyDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <cost-audit-table
        :table-data="selectCostSurveyData"
        :columns="selectCostSurveyColumns"
        :show-selection="true"
        :show-pagination="true"
        :pagination="selectCostSurveyPagination"
        @pagination-change="selectCostSurveyPaginationChange"
        @selection-change="selectCostSurveySelectionChange"
      >
        <!-- 创建时间自定义单元格 -->
        <template #createTime="{ row }">
          <div>{{ row.createTime ? row.createTime.split(' ')[0] : '-' }}</div>
          <div>{{ row.createTime ? row.createTime.split(' ')[1] : '-' }}</div>
        </template>
      </cost-audit-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="costSurveyDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitCostSurveyForm('costSurveyForm')"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import TemplatePreviewEdit from '@/components/costAudit/TemplatePreviewEdit.vue'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import UploadComponent from '@/components/costAudit/UploadComponent.vue'
  import { dictMixin } from '@/mixins/useDict'
  import {
    getDocList,
    addDocumentTemplate,
    updateDocumentTemplate,
    batchDeleteDocumentTemplates,
    deleteDocumentTemplateById,
    queryByDocumentId,
  } from '@/api/auditReviewDocManage.js'
  import { getallCurrentCostSurveyList } from '@/api/catalogManage.js'
  export default {
    name: 'AuditReviewDocManage',
    components: {
      TemplatePreviewEdit,
      CostAuditTable,
      UploadComponent,
    },
    mixins: [dictMixin],
    data() {
      return {
        dictData: {
          documentType: [], //文书类型
        },
        loading: false,
        // 视图控制
        activeView: 'list', // list: 列表视图, detail: 详情视图, edit: 修改视图
        view: 'add',
        activeDetailTab: 'basic', // 详情页标签页
        isDisabled: false,
        // 搜索表单数据
        searchForm: {
          documentName: '',
          status: '',
        },
        // 表格数据
        tableData: [],
        // 当前页码
        currentPage: 1,
        // 每页显示条数
        pageSize: 50,
        // 总记录数
        total: 0,
        // 选中的行数据
        selectedRows: [],
        costSurveyDialogVisible: false,
        selectCostSurveyData: [],
        selectCostSurveyRow: [],
        selectCostSurveyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 表单验证规则
        formRules: {
          documentName: [
            { required: true, message: '请输入监审文书名称', trigger: 'blur' },
            {
              max: 30,
              message: '监审文书名称不能超过30个字符',
              trigger: 'blur',
            },
          ],
          alias: [
            { required: true, message: '请输入监审文书别名', trigger: 'blur' },
            {
              max: 30,
              message: '监审文书别名不能超过30个字符',
              trigger: 'blur',
            },
          ],
          // dataSourceType: [
          //   { required: true, message: '请选择数据来源', trigger: 'change' },
          // ],
          // tableId: [
          //   { required: true, message: '请选择数据表', trigger: 'change' },
          // ],
          isWh: [
            { required: true, message: '请选择是否文号', trigger: 'change' },
          ],
          type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        },

        // 修改模板相关数据
        activeStep: 0, // 当前步骤，0:基础信息填写，1:模板内容配置
        activeTab: 'preview', // 当前标签页，preview:预览，edit:修改
        uploadDialogVisible: false, // 上传模板对话框显示状态
        selectedFile: null, // 选中的上传文件
        uploadedFile: null, // 已上传的文件信息
        fileContent: null, // 文件内容
        tablePreviewData: [], // 表格预览数据（前几行）
        tableColumns: [], // 表格列名
        // fileUrl:
        //   window.context.form +
        //   '/profile/upload/20251014/卷宗封面_20251014173930_349.docx',
        // 表单数据
        formData: {
          documentName: '',
          alias: '',
          description: '',
          isWh: '1',
          type: '',
          fileUrl: '',
        },

        // 数据项列表
        costDocumentTemplateFiles: [],

        // 详情页数据
        detailData: {},
        detailUploadedFile: null,
        detailDataFields: [],
        fileUrl: '',
      }
    },

    computed: {
      // 表格列配置
      selectCostSurveyColumns() {
        return [
          // {
          //   prop: 'catalogId',
          //   label: '监审类别',
          // },
          {
            prop: 'surveyTemplateName',
            label: '调查表名称',
          },
          {
            prop: 'templateType',
            label: '模版类型',
            width: '100px',
            formatter: (row) => {
              return row.templateType == '1'
                ? '单记录'
                : row.templateType == '2'
                ? '固定表'
                : '动态表'
            },
          },
          {
            prop: 'storageTable',
            label: '调查表数据存储表',
          },
          {
            prop: 'status',
            label: '状态',
            width: '100px',
            formatter: (row) => {
              return row.status == '-1'
                ? '草稿'
                : row.status == '0'
                ? '启用'
                : '停用'
            },
          },
          {
            prop: 'createTime',
            label: '创建时间',
            slotName: 'createTime',
            width: '100px',
          },
        ]
      },
    },

    created() {
      // 组件创建时加载数据
      this.handleSearch()
    },

    methods: {
      handleTabChange(tabName) {
        this.activeTab = tabName
      },

      // 搜索按钮点击事件
      async handleSearch() {
        this.loading = true
        try {
          const params = {
            ...this.searchForm,
            page: this.currentPage,
            pageSize: this.pageSize,
          }
          const response = await getDocList(params)
          this.tableData = response.value.records || []
          this.total = response.value.total || 0
        } catch (error) {
          console.log(error)
        } finally {
          this.loading = false
        }
      },

      // 重置按钮点击事件
      handleReset() {
        this.searchForm = {
          documentName: '',
          status: '',
        }
        this.currentPage = 1
        this.handleSearch()
      },
      handleAddCostSurvey() {
        this.getCostSurveyOptions()
        this.costSurveyDialogVisible = true
      },
      // 获取成本调查表选项
      getCostSurveyOptions() {
        getallCurrentCostSurveyList({}).then((res) => {
          this.selectCostSurveyData = res.value.records
          this.selectCostSurveyPagination.total = res.value.total
        })
      },
      selectCostSurveyPaginationChange({ currentPage, pageSize }) {
        this.selectCostSurveyPagination.currentPage = currentPage
        this.selectCostSurveyPagination.pageSize = pageSize
        this.getCostSurveyOptions()
      },
      selectCostSurveySelectionChange(val) {
        if (val.length > 1) {
          this.$message.warning('只能选择一个成本调查表')
          return
        }
        this.selectCostSurveyRow = val
      },
      submitCostSurveyForm() {
        if (this.selectCostSurveyRow.length == 1) {
          this.formData.tableId = this.selectCostSurveyRow[0].surveyTemplateId
          this.formData.surveyTemplateName =
            this.selectCostSurveyRow[0].surveyTemplateName
          this.costSurveyDialogVisible = false
        } else {
          this.$message.warning('请选择一个成本调查表')
        }
      },

      // 添加按钮点击事件
      handleAdd() {
        this.resetForm()
        this.activeView = 'edit'
        this.view = 'add'
        this.isDisabled = false
      },

      // 修改按钮点击事件
      async handleEdit(row) {
        this.initEditData(row)
        this.activeView = 'edit'
        this.view = 'edit'
        this.isDisabled = false
      },
      getDocumentData() {
        if (this.formData.id) {
          queryByDocumentId({ documentId: this.formData.id }).then((res) => {
            this.costDocumentTemplateFiles = res.value || []
          })
        }
      },

      // 详情按钮点击事件
      async handleDetail(row) {
        this.initEditData(row)
        this.activeView = 'edit'
        this.view = 'detail'
        this.isDisabled = true
      },

      // 返回列表
      backToList() {
        this.activeView = 'list'
        this.handleSearch()
      },

      // 初始化修改数据
      initEditData(data) {
        // 重置表单
        this.resetForm()
        // 设置表单数据
        this.formData = {}
        this.formData = {
          ...data,
          surveyTemplateName: data.tableId,
          fileUrl: data.fileUrl ? [data.fileUrl] : [],
        }
        this.fileUrl = data.fileUrl
        this.activeStep = 0
      },

      // 选中行变化事件
      handleSelectionChange(val) {
        this.selectedRows = val
      },

      // 开关状态改变事件
      async handleSwitchChange(row) {
        try {
          const response = await updateDocumentTemplate({
            ...row,
            status: row.status,
          })
          if (response.code !== 200) {
            // 回滚状态
            row.status = !row.status
          } else {
            this.$message.success('修改成功')
            this.handleSearch()
          }
        } catch (error) {
          // 回滚状态
          row.status = !row.status
        }
      },

      // 单个删除按钮点击事件
      async handleDeleteRow(row) {
        this.$confirm('确定要删除该记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const response = await deleteDocumentTemplateById(row.id)
            this.$message.success('删除成功')
            // 重新加载数据
            this.handleSearch()
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },

      // 分页大小改变事件
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.handleSearch()
      },

      // 当前页改变事件
      handleCurrentChange(val) {
        this.currentPage = val
        this.handleSearch()
      },

      // 删除按钮点击事件
      async handleDelete() {
        if (this.selectedRows.length === 0) {
          this.$message.warning('请先选择要删除的记录')
          return
        }
        this.$confirm('确定要删除选中的记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const ids = this.selectedRows.map((row) => row.id)
            const response = await batchDeleteDocumentTemplates({ ids })
            if (response.code === 200) {
              this.$message.success('删除成功')
              // 重新加载数据
              this.handleSearch()
              // 清空选中状态
              this.selectedRows = []
            }
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },

      // 复制标签到剪贴板
      copyToClipboard(tag) {
        const textarea = document.createElement('textarea')
        textarea.value = tag
        document.body.appendChild(textarea)
        textarea.select()
        document.execCommand('copy')
        document.body.removeChild(textarea)
        this.$message.success('标签已复制到剪贴板')
      },

      // 修改模板相关方法
      // 重置表单
      resetForm() {
        this.activeStep = 0
        this.formData = {
          documentName: '',
          alias: '',
          description: '',
          dataSourceType: 'database_table',
          tableId: 1,
          isWh: '1',
          type: '',
        }
        this.uploadedFile = null
        this.selectedFile = null
        this.fileContent = null
        this.tablePreviewData = []
        this.tableColumns = []
        this.costDocumentTemplateFiles = []
        // 重置表单验证
        if (this.$refs.basicForm) {
          this.$refs.basicForm.resetFields()
        }
      },

      // 处理下一步
      handleNextStep() {
        this.$refs.basicForm.validate((valid) => {
          if (valid) {
            if (this.view == 'detail' || this.view == 'edit') {
              this.getDocumentData()
              this.activeStep = 1
            } else {
              this.handleSave()
            }
          } else {
            this.$message.error('请填写完整的基础信息')
            return false
          }
        })
      },

      // 处理上一步
      handlePrevStep() {
        this.activeStep = 0
        this.$message.info('返回基础信息填写')
      },

      // 处理保存
      async handleSave() {
        // 准备保存数据
        const saveData = {
          ...this.formData,
          fileUrl: this.formData.fileUrl ? this.formData.fileUrl.join(',') : '',
          costDocumentTemplateFiles:
            this.costDocumentTemplateFiles.map((item) => {
              return {
                ...item,
                documentId: this.formData.id,
              }
            }) || [],
        }
        if (this.activeStep == 1) {
          if (!this.formData.fileUrl) {
            this.$message.error('请上传文件')
          }
        }

        let response
        if (!this.formData.id) {
          // 新增
          response = await addDocumentTemplate({
            ...saveData,
          })
          this.formData.id = response.value
        } else {
          // 修改
          response = await updateDocumentTemplate({
            ...saveData,
            id: this.formData.id,
          })
        }

        if (response.code === 200) {
          this.$message.success('保存成功')
          if (this.activeStep == 1) {
            // 保存成功后返回列表
            this.backToList()
            // 重新加载数据
            this.handleSearch()
          } else {
            this.activeStep = 1
          }
        } else {
          this.$message.error(response.msg || '保存失败')
        }
      },
      //  saveFiles 方法
      saveFiles(data) {
        this.formData.fileUrl = [data[0].savePath]
        this.fileUrl = data[0].savePath
        this.costDocumentTemplateFiles = data[0].bracketContentInfos.map(
          (item) => {
            return {
              ...item,
              labelValue: `{${item.pinyin}}`,
            }
          }
        )
      },

      //  removeFile 方法
      removeFile(index, removedFile, currentFiles) {
        this.formData.fileUrl = []
        this.fileUrl = ''
      },
      // 下载文件
      downloadFile() {
        // 在实际项目中，这里应该调用下载API或使用文件URL直接下载
        this.$message.info('文件下载功能已触发')
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';
  /* 标题样式 */
  .supervision-review-doc-manage h2 {
    margin-bottom: 20px;
    font-size: 18px;
    color: #333;
  }

  /* 操作按钮区域样式 */
  .action-buttons {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  /* 表格容器样式 */
  .table-container {
    margin-bottom: 20px;
  }

  /* 分页样式 */
  .pagination {
    text-align: right;
    margin-top: 20px;
  }

  /* 操作列按钮样式调整 */
  .el-table .cell {
    white-space: normal;
    word-break: break-all;
  }

  /* 修改视图样式 */
  .edit-view,
  .detail-view {
    max-width: 100%;
    overflow-x: auto;
  }

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

  .back-button {
    margin-right: 20px;
  }

  .steps-container {
    margin-bottom: 20px;
  }

  .step-content {
    overflow-y: auto;
    margin-bottom: 20px;

    .form-container {
      padding: 0 10px;
    }

    .template-config-container {
      .layout-wrapper {
        display: flex;
        gap: 20px;
      }

      .left-panel {
        flex: 1;
        height: 100%;
      }

      .right-panel {
        width: 50%;
        display: flex;
        flex-direction: column;
      }

      .upload-template-btn {
        margin-bottom: 20px;
        background-color: #409eff;
        border-color: #409eff;
      }

      .data-fields-section {
        flex: 1;
        display: flex;
        flex-direction: column;

        .data-fields-title {
          margin-bottom: 15px;
          padding: 10px;
          background-color: #f5f7fa;
          border-radius: 4px;
          font-size: 14px;
          color: #666;
        }

        .el-table {
          flex: 1;
          min-height: 0;
        }

        .tag-item {
          display: inline-block;
          padding: 4px 8px;
          background-color: #ecf5ff;
          color: #409eff;
          border-radius: 4px;
          font-size: 12px;
        }
      }
    }
  }

  /* 修改操作按钮区域居中显示 */
  .edit-actions {
    padding: 15px 0;
    border-top: 1px solid #e4e7ed;
    text-align: center;
  }

  .file-upload-tips {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f0f9ff;
    border: 1px solid #bae7ff;
    border-radius: 4px;
    color: #096dd9;
    font-size: 14px;
  }

  /* 修改已完成步骤的样式 */
  .el-step.is-finish {
    .el-step__head {
      /* 更改已完成步骤圆圈的背景色为白色 */
      background-color: #ffffff;
      border-color: #409eff;

      /* 修改已完成步骤的数字为√ */
      .el-step__icon-inner {
        /* 隐藏默认的数字 */
        opacity: 0;
        position: relative;

        /* 使用伪元素添加√符号 */
        &::before {
          content: '√';
          opacity: 1;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          color: #409eff;
          font-weight: bold;
        }
      }
    }
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .edit-header,
    .detail-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .back-button {
      margin-bottom: 10px;
    }

    .template-config-container .layout-wrapper {
      flex-direction: column;
    }

    .template-config-container .right-panel {
      width: 100%;
    }
  }
  ::v-deep .el-button.is-disabled {
    background-color: #f9f9f9 !important;
    border-color: #f3f3f4 !important;
    color: #cccccc !important;
  }
  /* 文字按钮样式 */
  .el-button--text.delete-btn {
    color: #f56c6c;
  }
</style>
