<template>
  <div>
    <avue-crud :option="option" :data="data" id="out-table" ref="crud" @selection-change="selectionChange">
      <template slot="menuLeft">
        <div style="display: flex">
          <el-upload
            :headers="headers"
            action="/api/blade-resource/oss/endpoint/put-file"
            :on-success="onSuccess"
            :on-error="onError"
            :before-upload="beforeUpload"
          >
            <el-button icon="el-icon-upload" type="primary" size="mini" :disabled="disabled">点击上传</el-button>
          </el-upload>
          <!-- <el-button type="success" size="mini" :disabled="disabled" @click.stop="submit">一键保存</el-button> -->
        </div>
      </template>
      <template slot="fileUrl" slot-scope="{ row, index }">
        <span v-if="row.$cellEdit" @click.stop="rowPick(row, index)">
          <el-upload
            :headers="headers"
            action="/api/blade-resource/oss/endpoint/put-file"
            :on-success="rowonSuccess"
            :on-error="onError"
            :before-upload="beforeUpload"
          >
            <el-input placeholder="请选择上传文件" v-model="row.fileUrl" readonly size="small"></el-input>
          </el-upload>
        </span>
        <span v-else style="color: #1e9fff; cursor: pointer" @click="download(row, index)">
          {{ row.fileUrl }}
        </span>
      </template>
      <template slot="menu" slot-scope="{ row, index }">
        <el-button size="small" type="text" icon="el-icon-edit" :disabled="disabled" @click="rowEdit(row)">{{
          row.$cellEdit ? "保存" : "编辑"
        }}</el-button>
        <el-button size="small" type="text" icon="el-icon-delete" @click="rowDel(row, index)" :disabled="disabled"
          >删 除
        </el-button>
      </template>
    </avue-crud>
    <PreviewImage :visible.sync="innerVisible" :currentIndex="0" :previewImgList="[imgUrl]" />
  </div>
</template>

<script>
// @ts-nocheck
import { getToken } from "@/util/auth";
import { updateListRemove, submitList } from "@/api/uploadFile/upload-file";
import PreviewImage from "@/components/PreviewImage/index.vue";
export default {
  name: "detailsPage",
  components: { PreviewImage },
  data() {
    return {
      innerVisible: false,
      imgUrl: "",
      rowIndex: null,
      headers: { "Blade-Auth": "Bearer " + getToken() },
      option: {
        maxHeight: 340,
        calcHeight: 30,
        menuWidth: 120,
        searchMenuSpan: 18,
        tip: false,
        border: true,
        index: true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        selection: true,
        align: "center",
        menu: true,
        columnBtn: false,
        column: [
          {
            label: "原始文件名",
            prop: "fileName",
            cell: true,
            overHidden: true,
          },
          {
            label: "文件地址",
            prop: "fileUrl",
            // cell: true,
            overHidden: true,
          },
          {
            label: "文件类型",
            prop: "fileType",
            // cell: true,
            overHidden: true,
          },
          {
            label: "备注",
            prop: "remarks",
            cell: true,
            width: 150,
            overHidden: true,
          },
        ],
      },
    };
  },
  props: {
    data: {
      type: Array,
      default: function () {
        return [];
      },
    },
    linkKey: {
      type: String,
      default: "link",
    },
    delUrl: {
      type: String,
      default: "/gubersail-admin/bladeclaimattachment/remove",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    isImage: {
      type: Boolean,
      default: false,
    },
  },
  created() {},
  methods: {
    /**
     * @param {any} list
     */
    selectionChange(list) {
      this.selectionList = list;
    },
    submit() {
      if (this.data.length == 0) {
        return this.$message.error("数据不能为空");
      }
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(255,255,255,0.7)",
      });
      submitList(this.data)
        .then((res) => {
          this.$emit("upDate", res.data.data);
        })
        .finally(() => {
          loading.close();
        });
    },
    /**
     * @param {{ id: any; }} row
     * @param {any} index
     */
    rowEdit(row, index) {
      // @ts-ignore
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
    // /**
    //  * @param {{ id: any; }} row
    //  * @param {any} index
    //  */
    download(row) {
      if (row.fileUrl) {
        const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"];
        const fileExt = row.fileUrl.substring(row.fileUrl.lastIndexOf(".")).toLowerCase();
        if (imageExtensions.includes(fileExt)) {
          this.innerVisible = true;
          this.imgUrl = row.fileUrl;
        } else {
          window.open(row.fileUrl);
        }
      } else {
        this.$message.error("请上传附件");
      }
    },
    /**
     * @param {{ id: any; }} row
     * @param {any} index
     */
    rowDel(row, index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (row.id) {
          updateListRemove(row.id, this.delUrl).then((res) => {
            if (res.data.success) {
              this.$message.success("操作成功!");
              this.data.splice(index, 1);
            }
          });
        } else {
          this.data.splice(index, 1);
        }
      });
    },
    /**
     * @param {string | any[]} filename
     */
    getFileExtension(filename) {
      return filename.slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2);
    },
    /**
     * @param {any} res
     * @param {any} file
     * @param {any} fileList
     */
    onSuccess(res, file, fileList) {
      this.data.push({
        pid: this.pId ? this.pId : null,
        fileName: res.data.originalName,
        fileUrl: res.data[this.linkKey],
        fileType: this.getFileExtension(res.data.originalName),
        $cellEdit: true,
      });
    },
    rowonSuccess(res, file, fileList) {
      this.data[this.rowIndex].fileName = res.data.originalName;
      this.data[this.rowIndex].fileUrl = res.data[this.linkKey];
      this.data[this.rowIndex].fileType = this.getFileExtension(res.data.originalName);
    },
    rowPick(row, index) {
      console.log(row, index);
      this.rowIndex = index;
    },
    /**
     * @param {any} err
     * @param {any} file
     * @param {any} fileList
     */
    onError(err, file, fileList) {
      console.log(err);
      this.$message.error(err);
    },
    beforeUpload(file) {
      if (this.isImage) {
        const isImage = file.type.includes("image/");

        if (!isImage) {
          this.$message.error("只能上传图片文件！");
          return false;
        }
        return isImage;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .avue-crud .el-table .cell {
  padding: 0 2px 0 0 !important;
  .el-form-item {
    margin-bottom: 0px !important;
  }
}

::v-deep .avue-crud .el-table .el-form-item__label {
  left: -1px;
}
::v-deep .el-table--small td,
.el-table--small th {
  padding: 2px !important;
}

::v-deep .el-upload-list {
  display: none;
}
::v-deep .el-upload {
  width: 100%;
}
</style>
