<template>
  <div class="app-container" v-loading="loading">
    <SearchBar
      :config="searchConfig"
      @search="search"
      @reset="reset"
      class="search-bar"
    />
    <div class="tools">
      <div class="tools-item">
        <el-dropdown @command="handleCommand">
          <PermissionButton
            button
            perms="bizMattingImages:add"
            type="primary"
            size="mini"
            icon="el-icon-upload2"
          >
            上传<i class="el-icon-arrow-down el-icon--right"></i>
          </PermissionButton>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="TYPE_IMG">上传图片</el-dropdown-item>
            <el-dropdown-item :command="TYPE_ZIP">上传压缩包</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="tools-item">
        <PermissionButton
          button
          perms="bizMattingImages:download"
          type="primary"
          size="mini"
          icon="el-icon-download"
          style="margin-right: 10px"
          :disabled="multiDisabled"
          plain
          @click="handleMultiDownload"
        >
          批量下载
        </PermissionButton>
        <PermissionButton
          button
          perms="bizMattingImages:delete"
          type="danger"
          plain
          size="mini"
          icon="el-icon-delete"
          :disabled="multiDisabled"
          @click="handleMultiDelete"
        >
          批量删除
        </PermissionButton>
      </div>
    </div>
    <div class="list">
      <TablePage
        :data="list.records"
        :tableTitle="tableTitle"
        :operates="operates"
        hasMultiSelection
        @handleSelectionChange="handleSelectionChange"
      >
        <template v-slot:status="{ scope }">
          <el-tag
            :type="
              $constantsTool.getTagTypeByValue('mattingStatus', scope.status)
            "
          >
            {{ $constantsTool.getLabelByValue("mattingStatus", scope.status) }}
          </el-tag>
        </template>
        <template v-slot:operates="{ scope }">
          <TableOperation
            :operations="getOperations(scope.status)"
            :rawData="scope"
            @handleOperation="handleOperation"
          ></TableOperation>
        </template>
      </TablePage>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="Number(list.current)"
        :page-sizes="[10, 20, 40, 50]"
        :page-size="Number(list.size)"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(list.total)"
        class="pagination"
      >
      </el-pagination>
      <UploadDialog
        ref="UploadDialog"
        @update="loadData"
        :options="uploadOptions"
      />
      <PreviewDialog ref="PreviewDialog" :detail="previewInfo" />
    </div>

    <el-image-viewer
      v-if="imgViewerVisible"
      :on-close="closeImgViewer"
      :url-list="imgList"
    />
  </div>
</template>

<script>
import {
  operates,
  viewButton,
  downloadButton,
  deleteButton,
  tableTitle,
  searchConfig,
} from "./configs/list";
import { records } from "./mock";
import UploadDialog from "@/components/UploadDialog";
import PreviewDialog from "./components/PreviewDialog";
import { Debounce } from "@/utils/index";
import {
  getMattingList,
  getMattingDetail,
  downFileByMattingIds,
  deleteMattingRecord,
} from "@/api/matting";
export default {
  components: {
    UploadDialog,
    PreviewDialog,
  },
  data() {
    return {
      list: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      searchConfig,
      loading: false,
      imgViewerVisible: false,
      importRecordVisible: false, //上传记录
      imgList: [],
      operates,
      tableTitle,
      currentUploadType: ".zip", //当前上传的文件类型
      previewInfo: {}, //当前点击预览的表格项目
      TYPE_IMG: "0", //单个图片文件
      TYPE_ZIP: "1", //zip文件
      uploadOptions: {
        uploadUrl:
          process.env.VUE_APP_BASE_API + "/bizMattingRecords/mattingImage", //上传的地址，必填
        compressFlag: "0", //上传方式：0-单个图片文件；1-zip文件。抠图时需要，非必填
        uploadFileKey: "file",
        uploadTitleKey: "title",
      },
      searchParams: {},
      multiSelection: [],
    };
  },
  computed: {
    multiDisabled() {
      return this.multiSelection.length == 0;
    },
    getOperations(status) {
      return (status) => {
        if (status == 1) {
          return [viewButton, downloadButton, deleteButton];
        } else {
          const newViewButton = {
            ...viewButton,
            disabled: true,
          };
          const newDownloadButton = {
            ...downloadButton,
            disabled: true,
          };
          return [newViewButton, newDownloadButton, deleteButton];
        }
      };
    },
  },
  created() {
    this.loadData();
  },
  methods: {
    async search(form) {
      this.searchParams = form;
      this.resetPage();
      this.loadData(form);
    },

    resetPage() {
      this.list.current = 1;
    },
    reset() {
      this.searchParams = {};
      this.loadData();
    },

    async loadData(form) {
      const { current, size } = this.list;
      var params = {
        page: current,
        limit: size,
      };
      const queryParams = form || this.searchParams;
      if (Object.keys(queryParams)) {
        params = { ...params, ...queryParams };
      }
      const res = await getMattingList(params);
      if (res.code == 0) {
        this.list = res.data;
      }
    },
    handleCommand(type) {
      this.uploadOptions.compressFlag = type;
      this.$appCommon.openDialog(this, "UploadDialog");
    },

    async handleOperation(value, row) {
      switch (value.type) {
        case "view":
          this.handleView(row);
          break;
        case "download":
          const { title, mattingId } = row;
          const ids = [mattingId];
          this.downloadByRecordId(ids, title);
          break;
        case "delete":
          this.handleDeleteRow(row);
          break;
      }
    },

    async handleView(row) {
      const { mattingId } = row;
      const params = {
        mattingId,
      };
      const res = await getMattingDetail(params);
      if (res.code == 0) {
        this.previewInfo = res.data;
        this.$appCommon.openDialog(this, "PreviewDialog");
      }
    },

    handleDeleteRow(row) {
      const ids = [row.mattingId];
      this.deleteByRecordsId(ids);
    },

    handleMultiDelete() {
      const ids = this.multiSelection.map((item) => {
        return item.mattingId;
      });
      this.deleteByRecordsId(ids);
    },

    handleMultiDownload() {
      const ids = this.multiSelection.map((item) => {
        return item.mattingId;
      });
      this.downloadByRecordId(ids);
    },

    deleteByRecordsId: Debounce(async function (ids) {
      const res = await deleteMattingRecord(ids);
      if (res.code == 0) {
        this.$message.success("删除成功！");
        this.loadData();
      }
    }, 600),

    downloadByRecordId: Debounce(async function (ids, name = "") {
      const params = ids;
      const url =
        process.env.VUE_APP_BASE_API +
        "/bizMattingRecords/downFileByMattingIds";
      const method = "post";
      const fileName = name + "_智能抠图处理后文件";
      const suffix = "zip";
      const opitons = {
        url,
        method,
        fileName,
        suffix,
        data: params,
      };
      await this.$file.downloadBlob(opitons);
    }, 600),

    // 关闭预览图片
    closeImgViewer() {
      this.imgViewerVisible = false;
    },
    // 预览图片
    handelPreviewImages(images) {
      this.imgViewerVisible = true;
      this.imgList = [images];
    },

    // 多选
    handleSelectionChange(val) {
      this.multiSelection = val;
    },

    // 改变页容量
    handleSizeChange(value) {
      this.list.size = value;
      this.loadData();
    },

    // 改变当前显示页
    handleCurrentChange(value) {
      this.list.current = value;
      this.loadData();
    },

    // 关闭导入记录弹窗
    handleImportRecordClose() {
      this.importRecordVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}
.search-bar {
  margin-bottom: 16px;
}

.tools {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;
  .tools-item {
    display: flex;
    &:last-child {
      justify-content: flex-end;
    }
  }
  .upload-button {
    margin: 0 10px;
  }
}
.pagination {
  margin: 16px;
  display: flex;
  justify-content: right;
}
</style>
