<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="装置" prop="plant">
        <el-input
          v-model="queryParams.plant"
          placeholder="请输入装置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="位置" prop="devLoc">
        <el-input
          v-model="queryParams.devLoc"
          placeholder="请输入位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备位号" prop="devTag">
        <el-input
          v-model="queryParams.devTag"
          placeholder="请输入设备位号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部件名称" prop="compoName">
        <el-input
          v-model="queryParams.compoName"
          placeholder="请输入部件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部件型号" prop="compoModel">
        <el-input
          v-model="queryParams.compoModel"
          placeholder="请输入部件型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部件描述" prop="compoDesc">
        <el-input
          v-model="queryParams.compoDesc"
          placeholder="请输入部件描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="queryParams.remarks"
          placeholder="请输入备注"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['reliability:rel_compo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['reliability:rel_compo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['reliability:rel_compo:remove']"
        >删除</el-button>
      </el-col>
        <el-col :span="1.5">
            <el-button
                    type="info"
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-hasPermi="['reliability:rel_compo:edit']"
            >导入</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['reliability:rel_compo:list']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rel_compoList" @selection-change="handleSelectionChange" :height="clientHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="装置" align="center" prop="plant" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="位置" align="center" prop="devLoc" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="设备位号" align="center" prop="devTag" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="部件名称" align="center" prop="compoName" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="部件型号" align="center" prop="compoModel" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="测厚点" align="center" prop="thicknessPt" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="部件描述" align="center" prop="compoDesc" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="部件照片" align="center" prop="compoPhoto" width="100">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.compoPhoto"
            size="mini"
            type="text"
            icon="el-icon-picture"
            @click="handleViewPhoto(scope.row.compoPhoto)">
            查看
          </el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="检查人" align="center" prop="inspector" width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.inspectorName || getStaffName(scope.row.inspector) }}
        </template>
      </el-table-column>
      <el-table-column label="维修更换人" align="center" prop="fixer" width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.fixerName || getStaffName(scope.row.fixer) }}
        </template>
      </el-table-column>
      <el-table-column label="检查频率" align="center" prop="inspFreq" width="110" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ translateFrequency(scope.row.inspFreq) }}
        </template>
      </el-table-column>
      <el-table-column label="检查内容" align="center" prop="inspContent" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="上次检查日期" align="center" prop="lastInspDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastInspDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修频率" align="center" prop="fixFreq" width="110" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ translateFrequency(scope.row.fixFreq) }}
        </template>
      </el-table-column>
      <el-table-column label="维修内容" align="center" prop="fixContent" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="上次维修日期" align="center" prop="lastFixDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastFixDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更换频率" align="center" prop="replaceFreq" width="110" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ translateFrequency(scope.row.replaceFreq) }}
        </template>
      </el-table-column>
      <el-table-column label="更换内容" align="center" prop="replaceContent" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="上次更换日期" align="center" prop="lastReplaceDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastReplaceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="下次维护日期" align="center" prop="nextMaintDate" width="120">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.nextMaintDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="维护类型" align="center" prop="nextMaintType" width="120" :show-overflow-tooltip="true"/>-->
      <el-table-column label="备注" align="center" prop="remarks" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['reliability:rel_compo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['reliability:rel_compo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改可靠性部件清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body class="compo-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基础数据 -->
        <div class="form-section">
          <div class="section-header">
            <i class="el-icon-document"></i>
            <span class="section-title">基础数据</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="装置" prop="plant">
                <el-input v-model="form.plant" placeholder="请输入装置" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置" prop="devLoc">
                <el-input v-model="form.devLoc" placeholder="请输入位置" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备位号" prop="devTag">
                <el-input v-model="form.devTag" placeholder="请输入设备位号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部件名称" prop="compoName">
                <el-input v-model="form.compoName" placeholder="请输入部件名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部件型号" prop="compoModel">
                <el-input v-model="form.compoModel" placeholder="请输入部件型号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="测厚点" prop="thicknessPt">
                <el-input v-model="form.thicknessPt" placeholder="请输入测厚点" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="部件描述" prop="compoDesc">
                <el-input v-model="form.compoDesc" type="textarea" :rows="1" placeholder="请输入部件描述" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="部件照片" prop="compoPhoto">
                <el-upload
                  class="upload-demo"
                  :action="uploadPhoto.url"
                  :headers="uploadPhoto.headers"
                  :data="uploadPhoto.data"
                  :on-success="handlePhotoSuccess"
                  :on-remove="handleRemovePhoto"
                  :before-upload="beforePhotoUpload"
                  :file-list="photoFileList"
                  :limit="1"
                  list-type="picture-card"
                  :on-exceed="handleExceedPhoto"
                  accept="image/*">
                  <i class="el-icon-plus"></i>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过15MB</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="form.remarks" type="textarea" :rows="1" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 维修策略 -->
        <div class="form-section">
          <div class="section-header">
            <i class="el-icon-setting"></i>
            <span class="section-title">维修策略</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="检查人" prop="inspector">
                <el-select v-model="form.inspector" placeholder="请选择检查人" clearable filterable style="width: 100%">
                  <el-option
                    v-for="staff in staffOptions"
                    :key="staff.id"
                    :label="staff.name"
                    :value="staff.staffid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="维修更换人" prop="fixer">
                <el-select v-model="form.fixer" placeholder="请选择维修更换人" clearable filterable style="width: 100%">
                  <el-option
                    v-for="staff in staffOptions"
                    :key="staff.id + '_fixer'"
                    :label="staff.name"
                    :value="staff.staffid">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="检查频率" prop="inspFreq">
                <div style="display: flex; gap: 8px; align-items: center; width: 300px;">
                  <el-input-number
                    v-model="inspFreqNumber"
                    :min="1"
                    :max="100"
                    controls-position="right"
                    style="width: 130px; flex-shrink: 0;"
                    placeholder="次数"
                    @change="updateInspFreq" />
                  <el-select v-model="inspFreqUnit" placeholder="单位" style="width: 130px; flex-shrink: 0;" @change="updateInspFreq" popper-append-to-body>
                    <el-option label="年(y)" value="y"></el-option>
                    <el-option label="月(m)" value="m"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="检查内容" prop="inspContent">
                <el-input v-model="form.inspContent" type="textarea" :rows="1" placeholder="请输入检查内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="维修频率" prop="fixFreq">
                <div style="display: flex; gap: 8px; align-items: center; width: 300px;">
                  <el-input-number
                    v-model="fixFreqNumber"
                    :min="1"
                    :max="100"
                    controls-position="right"
                    style="width: 130px; flex-shrink: 0;"
                    placeholder="次数"
                    @change="updateFixFreq" />
                  <el-select v-model="fixFreqUnit" placeholder="单位" style="width: 130px; flex-shrink: 0;" @change="updateFixFreq" popper-append-to-body>
                    <el-option label="年(y)" value="y"></el-option>
                    <el-option label="月(m)" value="m"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="维修内容" prop="fixContent">
                <el-input v-model="form.fixContent" type="textarea" :rows="1" placeholder="请输入维修内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="更换频率" prop="replaceFreq">
                <div style="display: flex; gap: 8px; align-items: center; width: 300px;">
                  <el-input-number
                    v-model="replaceFreqNumber"
                    :min="1"
                    :max="100"
                    controls-position="right"
                    style="width: 130px; flex-shrink: 0;"
                    placeholder="次数"
                    @change="updateReplaceFreq" />
                  <el-select v-model="replaceFreqUnit" placeholder="单位" style="width: 130px; flex-shrink: 0;" @change="updateReplaceFreq" popper-append-to-body>
                    <el-option label="年(y)" value="y"></el-option>
                    <el-option label="月(m)" value="m"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="更换内容" prop="replaceContent">
                <el-input v-model="form.replaceContent" type="textarea" :rows="1" placeholder="请输入更换内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
                  ref="upload"
                  :limit="1"
                  accept=".xlsx, .xls"
                  :headers="upload.headers"
                  :action="upload.url + '?updateSupport=1'"
                  :disabled="upload.isUploading"
                  :on-progress="handleFileUploadProgress"
                  :on-success="handleFileSuccess"
                  :auto-upload="false"
                  drag
          >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                  <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
                  <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
                    <input name="type" :value="upload.type" hidden/>
                  </form>
              </div>
              <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
          </div>
      </el-dialog>

      <!-- 图片预览对话框 -->
      <el-dialog title="查看照片" :visible.sync="photoPreviewVisible" width="800px" append-to-body>
        <div class="photo-preview-container">
          <img :src="previewPhotoUrl" alt="部件照片" style="width: 100%; height: auto;">
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { listRel_compo, getRel_compo, delRel_compo, addRel_compo, updateRel_compo, exportRel_compo, importTemplate} from "@/api/reliability/rel_compo";
import { treeselect } from "@/api/system/dept";
import { listStaffmgrAll } from "@/api/plant/staffmgr";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Rel_compo",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 可靠性部件清单表格数据
      rel_compoList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 人员列表选项
      staffOptions: [],
      clientHeight:300,
      // 是否显示弹出层
      open: false,
        // 用户导入参数
        upload: {
          //下载模板请求地址
          downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
          //下载模板类型
          type: 'rel_compo',
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/reliability/rel_compo/importData"
        },
      // 部件照片上传参数
      uploadPhoto: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址（使用支持自定义路径的接口）
        url: process.env.VUE_APP_BASE_API + "/common/uploadWithPath",
        // 上传路径参数
        data: { path: "/rel/compo" }
      },
      // 部件照片文件列表
      photoFileList: [],
      // 图片预览相关
      photoPreviewVisible: false,
      previewPhotoUrl: '',
      // 频率拆分数据
      inspFreqNumber: null,
      inspFreqUnit: 'y',
      fixFreqNumber: null,
      fixFreqUnit: 'y',
      replaceFreqNumber: null,
      replaceFreqUnit: 'y',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        plant: null,
        devLoc: null,
        devTag: null,
        compoName: null,
        compoModel: null,
        thicknessPt: null,
        compoDesc: null,
        compoPhoto: null,
        inspector: null,
        fixer: null,
        inspFreq: null,
        inspContent: null,
        lastInspDate: null,
        fixFreq: null,
        fixContent: null,
        lastFixDate: null,
        replaceFreq: null,
        replaceContent: null,
        lastReplaceDate: null,
        nextMaintDate: null,
        nextMaintType: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        compoName: [
          { required: true, message: "部件名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
   },
  created() {
      //设置表格高度对应屏幕高度
      this.$nextTick(() => {
          this.clientHeight = document.body.clientHeight -250
      })
    this.getList();
    this.getTreeselect();
    this.getStaffList();
  },
  methods: {
    /** 查询可靠性部件清单列表 */
    getList() {
      this.loading = true;
      listRel_compo(this.queryParams).then(response => {
        this.rel_compoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
          treeselect().then(response => {
              this.deptOptions = response.data;
          });
     },
     /** 查询人员列表 */
     getStaffList() {
          listStaffmgrAll().then(response => {
              this.staffOptions = response.rows || response.data || [];
          });
     },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        compoId: null,
        plant: null,
        devLoc: null,
        devTag: null,
        compoName: null,
        compoModel: null,
        thicknessPt: null,
        compoDesc: null,
        compoPhoto: null,
        inspector: null,
        fixer: null,
        inspFreq: null,
        inspContent: null,
        lastInspDate: null,
        fixFreq: null,
        fixContent: null,
        lastFixDate: null,
        replaceFreq: null,
        replaceContent: null,
        lastReplaceDate: null,
        nextMaintDate: null,
        nextMaintType: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      };
      this.photoFileList = [];
      // 重置频率拆分字段
      this.inspFreqNumber = null;
      this.inspFreqUnit = 'y';
      this.fixFreqNumber = null;
      this.fixFreqUnit = 'y';
      this.replaceFreqNumber = null;
      this.replaceFreqUnit = 'y';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.compoId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 设置频率默认值
      this.updateInspFreq();
      this.updateFixFreq();
      this.updateReplaceFreq();
      this.open = true;
      this.title = "添加可靠性部件清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const compoId = row.compoId || this.ids
      getRel_compo(compoId).then(response => {
        this.form = response.data;
        // 如果有照片，加载到文件列表
        if (this.form.compoPhoto) {
          // 如果是相对路径，需要拼接完整URL
          let imageUrl = this.form.compoPhoto;
          if (imageUrl && !imageUrl.startsWith('http')) {
            imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
          }
          this.photoFileList = [{
            name: '部件照片',
            url: imageUrl
          }];
          console.log('加载图片URL:', imageUrl);
        }
        // 解析频率字段
        this.parseFrequency(this.form.inspFreq, 'insp');
        this.parseFrequency(this.form.fixFreq, 'fix');
        this.parseFrequency(this.form.replaceFreq, 'replace');
        this.open = true;
        this.title = "修改可靠性部件清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.compoId != null) {
            updateRel_compo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRel_compo(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const compoIds = row.compoId || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRel_compo(compoIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有可靠性部件清单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportRel_compo(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
      /** 导入按钮操作 */
      handleImport() {
          this.upload.title = "用户导入";
          this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.$refs['downloadFileForm'].submit()
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
      },
      // 提交上传文件
      submitFileForm() {
          this.$refs.upload.submit();
      },

      /** 上传前的校验 */
      beforePhotoUpload(file) {
        const isImage = file.type.startsWith('image/');
        const isLt15M = file.size / 1024 / 1024 < 15;

        if (!isImage) {
          this.$message.error('只能上传图片文件!');
          return false;
        }
        if (!isLt15M) {
          this.$message.error('上传图片大小不能超过 15MB!');
          return false;
        }
        return true;
      },

      /** 图片上传成功回调 */
      handlePhotoSuccess(response, file, fileList) {
        console.log('上传接口返回数据:', response);

        // 若依框架上传接口返回格式
        if (response && response.fileName) {
          // 保存文件路径到表单（相对路径）
          this.form.compoPhoto = response.fileName;

          // 构建完整URL用于预览
          let imageUrl = response.url || response.fileName;
          if (imageUrl && !imageUrl.startsWith('http')) {
            imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
          }

          this.photoFileList = [{
            name: file.name,
            url: imageUrl
          }];
          console.log('图片路径已保存到 form.compoPhoto:', this.form.compoPhoto);
          console.log('预览URL:', imageUrl);
          this.$message.success('上传成功');
        } else {
          console.error('上传返回数据格式不正确:', response);
          this.$message.error(response.msg || '上传失败');
        }
      },

      /** 删除图片 */
      handleRemovePhoto(file, fileList) {
        this.form.compoPhoto = null;
        this.photoFileList = [];
      },

      /** 超出文件个数限制 */
      handleExceedPhoto(files, fileList) {
        this.$message.warning('只能上传1张图片');
      },

      /** 查看图片 */
      handleViewPhoto(photoPath) {
        if (photoPath) {
          // 如果是相对路径，拼接完整URL
          let imageUrl = photoPath;
          if (imageUrl && !imageUrl.startsWith('http')) {
            imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
          }
          this.previewPhotoUrl = imageUrl;
          this.photoPreviewVisible = true;
        }
      },

      /** 根据人员ID获取人员姓名 */
      getStaffName(staffId) {
        if (!staffId) return '-';
        const staff = this.staffOptions.find(s => s.staffid === staffId);
        return staff ? staff.name : staffId;
      },

      /** 更新检查频率 */
      updateInspFreq() {
        if (this.inspFreqNumber && this.inspFreqUnit) {
          this.form.inspFreq = this.inspFreqNumber + this.inspFreqUnit;
        } else if (this.inspFreqUnit) {
          // 如果只有单位没有数字，使用默认值1
          this.form.inspFreq = '1' + this.inspFreqUnit;
        } else {
          this.form.inspFreq = null;
        }
      },

      /** 更新维修频率 */
      updateFixFreq() {
        if (this.fixFreqNumber && this.fixFreqUnit) {
          this.form.fixFreq = this.fixFreqNumber + this.fixFreqUnit;
        } else if (this.fixFreqUnit) {
          // 如果只有单位没有数字，使用默认值1
          this.form.fixFreq = '1' + this.fixFreqUnit;
        } else {
          this.form.fixFreq = null;
        }
      },

      /** 更新更换频率 */
      updateReplaceFreq() {
        if (this.replaceFreqNumber && this.replaceFreqUnit) {
          this.form.replaceFreq = this.replaceFreqNumber + this.replaceFreqUnit;
        } else if (this.replaceFreqUnit) {
          // 如果只有单位没有数字，使用默认值1
          this.form.replaceFreq = '1' + this.replaceFreqUnit;
        } else {
          this.form.replaceFreq = null;
        }
      },

      /** 解析频率字符串 */
      parseFrequency(freqStr, type) {
        // 匹配数字和单位，如 "12y", "6m"
        const match = freqStr ? freqStr.match(/^(\d+)([ym])$/) : null;
        if (match) {
          const number = parseInt(match[1]);
          const unit = match[2];
          if (type === 'insp') {
            this.inspFreqNumber = number;
            this.inspFreqUnit = unit;
          } else if (type === 'fix') {
            this.fixFreqNumber = number;
            this.fixFreqUnit = unit;
          } else if (type === 'replace') {
            this.replaceFreqNumber = number;
            this.replaceFreqUnit = unit;
          }
        } else {
          // 没有值时设置默认值
          if (type === 'insp') {
            this.inspFreqNumber = 1;
            this.inspFreqUnit = 'y';
          } else if (type === 'fix') {
            this.fixFreqNumber = 1;
            this.fixFreqUnit = 'y';
          } else if (type === 'replace') {
            this.replaceFreqNumber = 1;
            this.replaceFreqUnit = 'y';
          }
        }
      },

      /** 翻译频率字段 */
      translateFrequency(frequency) {
        if (!frequency) return '';

        // 匹配数字和单位
        const match = frequency.match(/^(\d+)([ym])$/);
        if (match) {
          const number = match[1];
          const unit = match[2];

          switch (unit) {
            case 'y':
              return `${number}年一次`;
            case 'm':
              return `${number}月一次`;
            default:
              return frequency;
          }
        }

        return frequency;
      }
  }
};
</script>

<style scoped>
/* 表单分区样式 */
.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.form-section:last-of-type {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #409eff;
}

.section-header i {
  font-size: 20px;
  color: #409eff;
  margin-right: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 对话框样式 */
.compo-dialog >>> .el-dialog__body {
  padding: 20px 30px;
  max-height: 70vh;
  overflow-y: auto;
}

.compo-dialog >>> .el-form-item {
  margin-bottom: 18px;
}

.compo-dialog >>> .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 上传组件样式 */
.upload-demo >>> .el-upload--picture-card {
  width: 148px;
  height: 148px;
  line-height: 148px;
}

.upload-demo >>> .el-upload-list--picture-card .el-upload-list__item {
  width: 148px;
  height: 148px;
}

/* Textarea 样式优化 */
.form-section >>> .el-textarea__inner {
  resize: vertical;
  font-family: inherit;
}

/* 底部按钮样式 */
.dialog-footer {
  padding: 15px 20px;
  text-align: right;
  border-top: 1px solid #e9ecef;
}

.dialog-footer .el-button {
  min-width: 80px;
}
</style>
