<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="档案编号" prop="filesCode">
        <el-input
          v-model="queryParams.filesCode"
          placeholder="请输入档案编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="档案名称" prop="filesName">-->
<!--        <el-input-->
<!--          v-model="queryParams.filesName"-->
<!--          placeholder="请输入档案名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="档案路径" prop="filesPath">-->
<!--        <el-input-->
<!--          v-model="queryParams.filesPath"-->
<!--          placeholder="请输入档案路径"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="是否标识：1-是；2-否" prop="isFlag">-->
<!--        <el-input-->
<!--          v-model="queryParams.isFlag"-->
<!--          placeholder="请输入是否标识：1-是；2-否"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" 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"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dms:dmsFiles:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dms:dmsFiles:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dms:dmsFiles:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dms:dmsFiles:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dmsFilesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键标识" align="center" prop="deviceFilesId" />-->
      <el-table-column label="设备ID" align="center" prop="deviceId" />
      <el-table-column label="设备名称" align="center" prop="deviceId" >
        <template slot-scope="scope">
            <span
              v-for="(item, index) in ledgerList"
              :key="index"
              :value="item.ledgerList"
              v-if="scope.row.deviceId == item.deviceId"
            >
              {{ item.deviceName }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="档案编号" align="center" prop="filesCode" />
      <el-table-column label="档案名称" align="center" prop="filesName" />
      <el-table-column label="档案路径" align="center" prop="filesPath" >
        <template slot-scope="scope">
          <router-link to=""  @click.native="jumpTo(scope.row.filesPath)" class="link-type">
            <span>{{ scope.row.filesPath }}</span>
          </router-link>
        </template>
      </el-table-column>
<!--      <el-table-column label="是否标识：1-是；2-否" align="center" prop="isFlag" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" 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="['dms:dmsFiles:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dms:dmsFiles: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="设备ID,关联dms_base_device_ledger的device_id" prop="deviceId">-->
<!--          <el-input v-model="form.deviceId" placeholder="请输入设备ID,关联dms_base_device_ledger的device_id" />-->
<!--        </el-form-item>-->
        <el-form-item label="设备名称" prop="deviceId" >
          <el-select v-model="form.deviceId" placeholder="请选择设备">
            <el-option
              v-for="item in ledgerList"
              :key="item.deviceId"
              :label="item.deviceName"
              :value="item.deviceId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="档案编号" prop="filesCode">
          <el-input v-model="form.filesCode" placeholder="请输入档案编号" />
        </el-form-item>
<!--        <el-form-item label="档案名称" prop="filesName">-->
<!--          <el-input v-model="form.filesName" placeholder="请输入档案名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="档案路径" prop="filesPath">-->
<!--          <el-input v-model="form.filesPath" placeholder="请输入档案路径" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否标识：1-是；2-否" prop="isFlag">-->
<!--          <el-input v-model="form.isFlag" placeholder="请输入是否标识：1-是；2-否" />-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="档案上传" prop="file">
          <template>
            <div class="upload-file">
              <el-upload
                multiple
                :action="uploadFileUrl"
                :before-upload="handleBeforeUpload"
                :file-list="fileList"
                :limit="limit"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                :headers="headers"
                class="upload-file-uploader"
                ref="fileUpload"
              >
                <!-- 上传按钮 -->
                <el-button size="mini" type="primary">选取文件</el-button>
                <!-- 上传提示 -->
                <div class="el-upload__tip" slot="tip" v-if="showTip">
                  请上传
                  <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                  <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                  的文件
                </div>
              </el-upload>

              <!-- 文件列表 -->
              <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
                <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
                  <el-link :href="file.url" :underline="false" target="_blank">
                    <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
                  </el-link>
                  <div class="ele-upload-list__item-content-action">
                    <el-link :underline="false" @click="handleDeleteFile(index)" type="danger">删除</el-link>
                  </div>
                </li>
              </transition-group>
            </div>
          </template>
        </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>

  </div>
</template>

<script>
import { listDmsFiles, getDmsFiles, delDmsFiles, addDmsFiles, updateDmsFiles } from "@/api/dms/dmsFiles";
import { getToken } from '@/utils/auth'
import { listLedger } from '@/api/dms/ledger'

export default {
  name: "DmsFiles",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      ledgerList:[],
      number: 0,
      uploadList: [],
      uploadLists: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传文件服务器地址
      // uploadFileUrl: process.env.VUE_APP_BASE_API + "/dms/dmsFiles/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备档案信息表格数据
      dmsFilesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,


      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        filesCode: null,
        filesName: null,
        filesPath: null,
        isFlag: null,
        deviceName: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // deviceId: [
        //   { required: true, message: "设备ID,关联dms_base_device_ledger的device_id不能为空", trigger: "blur" }
        // ],
        filesName: [
          { required: true, message: "档案名称不能为空", trigger: "blur" }
        ],
        // filesPath: [
        //   { required: true, message: "档案路径不能为空", trigger: "blur" }
        // ],
        // isFlag: [
        //   { required: true, message: "是否标识：1-是；2-否不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeviveLedger();
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },

  methods: {
    jumpTo(url){
    window.open(url,"_blank");
    },
    /** 查询设备台账信息列表 */
    getDeviveLedger() {
      listLedger(this.queryParams).then(response => {
        this.ledgerList = response.rows;
      });
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.data.url, url: res.data.url });
        this.uploadLists.push({ name: res.data.url, url: res.data.url });
        this.uploadedSuccessfully();

      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDeleteFile(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 修改时处理
    uploadedSuccessfullyUpdate() {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        // this.$modal.closeLoading();

    },

    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },

    /** 查询设备档案信息列表 */
    getList() {
      this.loading = true;
      listDmsFiles(this.queryParams).then(response => {
        this.dmsFilesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.handleDeleteFile();
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceFilesId: null,
        deviceId: null,
        filesCode: null,
        filesName: null,
        filesPath: null,
        isFlag: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        params:{
        }
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceFilesId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fileList = [];
      // this.uploadLists = [];
      this.open = true;
      this.title = "添加设备档案信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.fileList = [];
      // console.log(row)
      // if (row.code === 200) {
      // console.log(this.queryParams.params.fileLists)
        this.uploadList.push({ name: row.filesName, url: row.filesPath });
        this.uploadLists.push({ name: row.filesName, url: row.filesPath });
        this.uploadedSuccessfullyUpdate();
      // }
      // console.log(this.fileList)
      const deviceFilesId = row.deviceFilesId || this.ids
      getDmsFiles(deviceFilesId).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.open = true;
        this.title = "修改设备档案信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.params.fileList = this.uploadLists;
          // console.log(this.fileList)
          if (this.form.deviceFilesId != null) {
            this.form.filesPath = this.fileList[0].url;
            this.form.filesName = this.fileList[0].name;
            updateDmsFiles(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(this.fileList[0])
            // this.form.params.filesPath = this.fileList[0].url;
            // this.form.params.filesName = this.fileList[0].name;
            this.form.filesPath = this.fileList[0].url;
            this.form.filesName = this.fileList[0].name;
            addDmsFiles(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceFilesIds = row.deviceFilesId || this.ids;
      this.$modal.confirm('是否确认删除设备档案信息编号为"' + deviceFilesIds + '"的数据项？').then(function() {
        return delDmsFiles(deviceFilesIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dms/dmsFiles/export', {
        ...this.queryParams
      }, `dmsFiles_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
