<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="devName">
        <el-input
          v-model="queryParams.devName"
          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="devType">
        <el-select v-model="queryParams.devType" placeholder="请选择设备类型" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备描述" prop="devDesc">
        <el-input
          v-model="queryParams.devDesc"
          placeholder="请输入设备描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区域" prop="devArea">
        <el-input
          v-model="queryParams.devArea"
          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_device: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_device: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_device: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_device: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_device:list']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rel_deviceList" @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="devName" width="150" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="text" @click="handleDeviceDetail(scope.row)">
            {{ scope.row.devName }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="设备位号" align="center" prop="devTag" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="设备类型" align="center" prop="devType" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="设备描述" align="center" prop="devDesc" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="区域" align="center" prop="devArea" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="区域负责人" align="center" prop="areaResponsible" width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.areaResponsibleName || getStaffName(scope.row.areaResponsible) }}
        </template>
      </el-table-column>
      <el-table-column label="设备照片" align="center" prop="devPhoto" width="100">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.devPhoto"
            size="mini"
            type="text"
            icon="el-icon-picture"
            @click="handleViewPhoto(scope.row.devPhoto)">
            查看
          </el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddPlan(scope.row)"
            v-hasPermi="['reliability:rel_maint_plan:add']"
          >新计划</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['reliability:rel_device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['reliability:rel_device: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="装置" prop="plant">
          <el-input v-model="form.plant" placeholder="请输入装置" />
        </el-form-item>
        <el-form-item label="位置" prop="devLoc">
          <el-input v-model="form.devLoc" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item label="设备名称" prop="devName">
          <el-input v-model="form.devName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备位号" prop="devTag">
          <el-input v-model="form.devTag" placeholder="请输入设备位号" />
        </el-form-item>
        <el-form-item label="设备类型" prop="devType">
          <el-input v-model="form.devType" placeholder="请输入设备类型" />
        </el-form-item>
        <el-form-item label="设备描述" prop="devDesc">
          <el-input v-model="form.devDesc" placeholder="请输入设备描述" />
        </el-form-item>
        <el-form-item label="区域" prop="devArea">
          <el-input v-model="form.devArea" placeholder="请输入区域" />
        </el-form-item>
        <el-form-item label="区域负责人" prop="areaResponsible">
          <el-select v-model="form.areaResponsible" placeholder="请选择区域负责人" clearable filterable>
            <el-option
              v-for="staff in staffOptions"
              :key="staff.id"
              :label="staff.name"
              :value="staff.staffid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备照片" prop="devPhoto">
          <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-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>

      <!-- 维修计划表单对话框 -->
      <maint-plan-form
        :visible.sync="maintPlanFormOpen"
        :title="maintPlanFormTitle"
        :form="maintPlanFormData"
        @submit="handleMaintPlanFormSubmit"
        @cancel="handleMaintPlanFormCancel"
      />
  </div>
</template>

<script>
import { listRel_device, getRel_device, delRel_device, addRel_device, updateRel_device, exportRel_device, importTemplate} from "@/api/reliability/rel_device";
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";
import MaintPlanForm from "@/views/reliability/rel_maint_plan/MaintPlanForm.vue";

export default {
  name: "Rel_device",
  components: { Treeselect, MaintPlanForm },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 可靠性设备清单表格数据
      rel_deviceList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 人员列表选项
      staffOptions: [],
      clientHeight:300,
      // 是否显示弹出层
      open: false,
        // 用户导入参数
        upload: {
          //下载模板请求地址
          downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
          //下载模板类型
          type: 'rel_device',
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/reliability/rel_device/importData"
        },
      // 设备照片上传参数
      uploadPhoto: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址（使用支持自定义路径的接口）
        url: process.env.VUE_APP_BASE_API + "/common/uploadWithPath",
        // 上传路径参数
        data: { path: "/rel/dev" }
      },
      // 设备照片文件列表
      photoFileList: [],
      // 图片预览相关
      photoPreviewVisible: false,
      previewPhotoUrl: '',
      // 维修计划表单相关
      maintPlanFormOpen: false,
      maintPlanFormTitle: "",
      maintPlanFormData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        plant: null,
        devLoc: null,
        devName: null,
        devTag: null,
        devType: null,
        devDesc: null,
        devArea: null,
        areaResponsible: null,
        devPhoto: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        devTag: [
          { 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_device(this.queryParams).then(response => {
        this.rel_deviceList = 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 = {
        devId: null,
        plant: null,
        devLoc: null,
        devName: null,
        devTag: null,
        devType: null,
        devDesc: null,
        devArea: null,
        areaResponsible: null,
        devPhoto: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      };
      this.photoFileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.devId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加可靠性设备清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const devId = row.devId || this.ids
      getRel_device(devId).then(response => {
        this.form = response.data;
        // 如果有照片，加载到文件列表
        if (this.form.devPhoto) {
          // 如果是相对路径，需要拼接完整URL
          let imageUrl = this.form.devPhoto;
          if (imageUrl && !imageUrl.startsWith('http')) {
            imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
          }
          this.photoFileList = [{
            name: '设备照片',
            url: imageUrl
          }];
          console.log('加载图片URL:', imageUrl);
        }
        this.open = true;
        this.title = "修改可靠性设备清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 调试：打印表单数据
          console.log('提交表单数据:', this.form);
          console.log('设备照片路径:', this.form.devPhoto);

          if (this.form.devId != null) {
            updateRel_device(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRel_device(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const devIds = row.devId || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRel_device(devIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有可靠性设备清单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportRel_device(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();
      },

      /** 设备详情按钮操作 */
      handleDeviceDetail(row) {
        // 跳转到设备详情页面
        this.$router.push({
          path: '/reliability/rel_device/detail',
          query: { deviceId: row.devId }
        });
      },

      /** 上传前的校验 */
      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.devPhoto = 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.devPhoto:', this.form.devPhoto);
          console.log('预览URL:', imageUrl);
          this.$message.success('上传成功');
        } else {
          console.error('上传返回数据格式不正确:', response);
          this.$message.error(response.msg || '上传失败');
        }
      },

      /** 删除图片 */
      handleRemovePhoto(file, fileList) {
        this.form.devPhoto = 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;
        }
      },

      /** 新增维修计划按钮操作 */
      handleAddPlan(row) {
        // 初始化维修计划表单数据，预填设备信息
        this.maintPlanFormData = {
          planId: null,
          devId: row.devId,
          plant: row.plant,
          devName: row.devName,
          devTag: row.devTag,
          planTime: null,
          approvalStatus: "0",
          responsible: null,
          completionStatus: "0",
          processId: null,
          approver: null,
          delFlag: null,
          createrCode: null,
          createdate: null,
          updaterCode: null,
          updatedate: null,
          deptId: null,
          remarks: null,
          maintComponents: []
        };
        this.maintPlanFormTitle = "添加设备维修计划";
        this.maintPlanFormOpen = true;
      },

      /** 维修计划表单提交 */
      handleMaintPlanFormSubmit(formData) {
        // 这里可以处理维修计划表单提交后的逻辑
        // 例如刷新列表等
        this.getList();
      },

      /** 维修计划表单取消 */
      handleMaintPlanFormCancel() {
        this.maintPlanFormOpen = false;
        this.maintPlanFormData = {};
      },

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

<style scoped>
.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;
}
</style>
