<template>
  <!-- 告警记录功能 -->
  <div class="app-container alarm-record">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="68px"
    >
      <el-form-item label="文件名" prop="docName">
        <el-input
          v-model="queryParams.docName"
          clearable
          placeholder="请输入文件名"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>

        <el-button
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
<!--        <el-button-->
<!--          icon="el-icon-download"-->
<!--          plain-->
<!--          size="mini"-->
<!--          type="warning"-->
<!--          @click="handleExport"-->
<!--          >导出</el-button-->
<!--        >-->
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['iot:document:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="openAddDocumentModel"
        >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordList"
      :default-sort="{ prop: 'alarmTime', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column
        :index="indexFormatter"
        align="center"
        label="序号"
        type="index"
        width="80px"
      ></el-table-column>
      <el-table-column
        align="left"
        label="文件名"
        prop="docName"
      />
      <el-table-column align="left" label="文件类型" prop="docType" />
      <el-table-column align="left" label="文件大小" prop="docSize" >
        <template slot-scope="scope">
          {{formatFileSize(scope.row.docSize)}}
        </template>
      </el-table-column>
      <el-table-column align="left" label="文件信息" prop="docInfo" />
      <el-table-column align="left" label="更新时间" prop="updateTime" width="150" />
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            v-if="judgeLook(scope.row.docType)"
            icon="el-icon-view"
            size="mini"
            type="text"
            @click="handleLook(scope.row)"
          >查看</el-button>
          <el-button
            icon="el-icon-download"
            size="mini"
            type="text"
            @click="handleDownload(scope.row)"
          >下载</el-button>
          <el-button
            v-hasPermi="['iot:document:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >编辑</el-button>
          <el-button
            v-hasPermi="['iot:document:remove']"
            icon="el-icon-delete"
            size="mini"
            style="color: #f56c6c"
            type="text"
            @click="handleDelete(scope.row)"
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      class="eldialog-wrap"
      width="600px"
    >
      <el-form
        ref="dialogForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="文件:">
          <el-upload
            ref="upload"
            :http-request="upload"
            :show-file-list="false"
            action
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <div v-if="form.docUrl">
          <el-form-item label="文件名称:" prop="docName">
            <el-input v-model="form.docName" placeholder="请输入文件名称" />
          </el-form-item>
          <el-form-item label="文件类型:">
            {{form.docType}}
          </el-form-item>
          <el-form-item label="文件大小:">
            {{formatFileSize(form.docSize)}}
          </el-form-item>
          <el-form-item label="文件信息:" prop="docInfo">
            <el-input v-model="form.docInfo" placeholder="请输入文件信息" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button size="mini" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button size="mini" @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  exportRecord,
  updateRecord,
  delRecord,
  addAlarmRecord,
} from "@/api/alarm/tenantAlarm";
import { handlerRecord } from "@/api/alarm/record";

import Editor from "@/components/Editor";
import { addDocument, delDocument, editDocument, getDocumentList } from "@/api/document";
import { uploadFile } from "@/api/file";

export default {
  name: "DocumentList",
  components: {
    Editor,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报警记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        docName: null,
        // typeCode: null,
        // beginTime: null,
        // endTime: null,
        // alarmDivide: "ALARM",
        // isAsc: 'desc',
        // orderByColumn: 'alarmTime'
      },
      // 表单参数
      form: {
        docId:null,
        docSize:null,
        docUrl:null,
        docType:null,
        docInfo:null,
        docName:null,
      },
      // 表单校验
      rules: {
        docName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" },
        ],
      },
      time: [],

    };
  },
  created() {
    // this.newTime();
    this.getList();
  },
  methods: {
    // 处理告警
    handleUpdate(row) {
      this.form = row;
      this.open = true;
      this.title = `编辑文件`;
    },
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    upload(file) {
      var formData = new FormData();
      formData.append("file", file.file);
      console.log("formData",formData)
      console.log("file",file)
      uploadFile(formData)
        .then((response) => {
          console.log("response",response)
          if (response.code === 200) {
            this.form.docSize = file.file.size;
            this.form.docName = this.getFileName(file.file.name) || '';
            this.form.docType = this.getFileType(file.file.name) || '';
            this.form.docUrl = response.url;
          }else{
            this.msgError(response.msg);
          }
        })
        .catch((e) => {
          console.log(e);
          this.msgError(e.msg);
        });
    },
    getFileName(fileName) {
      const parts = fileName.split('.');
      if (parts.length > 1) {
        parts.pop(); // 移除文件扩展名
        return parts.join('.'); // 重新组合文件名
      }
      return fileName;
    },
    getFileType(fileName) {
      const parts = fileName.split('.');
      if (parts.length > 1) {
        return parts.pop().toLowerCase();
      }
      return '';
    },
    formatFileSize(size) {
      if (size === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordId = row.docId;
      this.$confirm("是否删除该文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(function () {
          return delDocument(recordId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    submitForm() {
      this.$refs["dialogForm"].validate((v) => {
        if (v) {
          if(this.form.docId){
            editDocument(this.form).then((response) => {
              this.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
            });
          }else{
            addDocument(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleLook(row) {
      const link = document.createElement('a');
      link.href = row.docUrl;
      link.setAttribute('download', `${row.docName}.${row.docType}`);
      link.target = "_blank";
      // 添加到 DOM 中
      document.body.appendChild(link);
      // 触发点击事件
      link.click();
      // 清理
      document.body.removeChild(link);

    },
    judgeLook(docType) {
      return docType === 'pdf' || docType === 'png' || docType === 'jpg' || docType === 'jpeg' || docType === 'gif' || docType === 'txt'
      // return true
    },
    handleDownload(row) {
      fetch(row.docUrl)
        .then(response => response.blob())
        .then(blob => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = `${row.docName}.${row.docType}`;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        })
        .catch(error => {
          console.error('下载失败:', error);
        });
    },
    // 转工单处理
    handleWork(row) {
      console.log("addWork:", row);
      this.$confirm("是否创建告警工单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return addAlarmRecord({
            recordId: row.recordId, //告警记录id
            deviceId: row.deviceId,
            deviceName: row.deviceName,
            faultType: "3", //固定
            maintenanceStatus: "-1", //固定（工单已生成）
            tenantId: null,
            faultTypeName: "告警工单", //固定
          });
        })
        .then(() => {
          this.msgSuccess("报警工单已创建！");
          this.$router.push("/power/maintenancet");
        });
    },
    resetFomr() {
      this.form = {
        processResult: "",
        processStatus: "",
        processTime: "",
        recordId: "",
      };
    },
    stateFormatter(val) {
      switch (val.processStatus) {
        case "1":
          return "已处理";

        case "0":
          return "未处理";

        case "2":
          return "误报";

        default:
          return "未处理";
      }
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    /** 查询报警记录列表 */
    getList() {
      this.loading = true;
      getDocumentList(this.queryParams).then((response) => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 打开新增文件
    openAddDocumentModel() {
      this.form = {
        docSize:null,
        docUrl:null,
        docType:null,
        docInfo:null,
        docName:null,
      };
      this.open = true;
      this.title = `新增文件`;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.time = [];
      this.queryParams.docName = null;
      this.handleQuery();
    },
  },
};
</script>
