<template>
  <div class="card-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="题卡名称：">
            <el-input
              v-model.trim="filter.title"
              placeholder="名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="创建方式：" label-width="90px">
            <el-select
              v-model="filter.createMethod"
              style="width: 120px;"
              placeholder="创建方式"
              clearable
            >
              <el-option
                v-for="(val, key) in CARD_CREATE_METHOD_TYPE"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间：">
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="创建开始时间"
              end-placeholder="创建结束时间"
              value-format="timestamp"
              align="right"
              unlink-panels
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          v-if="checkPrivilege('button', 'add')"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="toAdd"
          >添加题卡</el-button
        >
      </div>
    </div>
    <div class="part-box part-box-pad">
      <el-table ref="TableList" :data="cardList">
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="title"
          label="题卡名称"
          min-width="120"
        ></el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <span slot-scope="scope">{{ scope.row.type | cardTypeFilter }}</span>
        </el-table-column>
        <el-table-column prop="createMethod" label="创建方式" width="100">
          <span slot-scope="scope">{{
            scope.row.createMethod | cardCreateMethodTypeFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <span
            :class="{ 'color-danger': scope.row.status !== 'SUBMIT' }"
            slot-scope="scope"
            >{{ scope.row.status === "SUBMIT" ? "提交" : "暂存" }}</span
          >
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="80">
          <span slot-scope="scope">{{
            scope.row.remark | defaultFieldFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="160"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'preview')"
              class="btn-primary"
              type="text"
              @click="toPreview(scope.row)"
              >查看</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'ConvertImage') && !scope.row.imageUrls
              "
              class="btn-primary"
              type="text"
              @click="toConvertImage(scope.row)"
              >生成图片</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'ConvertImage') && scope.row.imageUrls
              "
              class="btn-primary"
              type="text"
              @click="toPreviewImage(scope.row)"
              >预览图片</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'delete')"
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'edit') &&
                  scope.row.createMethod !== 'UPLOAD'
              "
              class="btn-primary"
              type="text"
              @click="toEditCard(scope.row)"
              >编辑题卡</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'edit') && scope.row.type !== 'CUSTOM'
              "
              class="btn-primary"
              type="text"
              @click="toEditInfo(scope.row)"
              >编辑信息</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <!-- ModifyCardInfo -->
    <modify-card-info
      ref="ModifyCardInfo"
      :instance="curCard"
      @new-card="toNewCard"
      @modified="getList"
    ></modify-card-info>
    <!-- ModifyCard -->
    <modify-card ref="ModifyCard" @modified="getList"></modify-card>
    <!-- image-preview -->
    <simple-image-preview
      :cur-image="curImage"
      @on-prev="toPrevImage"
      @on-next="toNextImage"
      ref="SimpleImagePreview"
    ></simple-image-preview>
  </div>
</template>

<script>
import { CARD_CREATE_METHOD_TYPE } from "../../../constants/enumerate";
import { cardListPage, deleteCard, convertCardImage } from "../api";
import ModifyCardInfo from "../components/ModifyCardInfo";
import pickerOptions from "@/constants/datePickerOptions";
import ModifyCard from "../../card/components/ModifyCard";
import SimpleImagePreview from "@/components/SimpleImagePreview";

export default {
  name: "card-manage",
  components: { ModifyCardInfo, ModifyCard, SimpleImagePreview },
  data() {
    return {
      filter: {
        title: "",
        createMethod: "",
        createStartTime: "",
        createEndTime: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      CARD_CREATE_METHOD_TYPE,
      cardList: [],
      curCard: {},
      // date-picker
      createTime: [],
      pickerOptions,
      // image-preview
      imageList: [],
      curImage: {},
      curImageIndex: 0
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      if (this.createTime) {
        datas.createStartTime = this.createTime[0];
        datas.createEndTime = this.createTime[1];
      }
      const data = await cardListPage(datas);
      this.cardList = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    toAdd() {
      this.curCard = {};
      this.$refs.ModifyCardInfo.open();
    },
    toPreview(row) {
      window.open(
        this.getRouterPath({
          name: "CardPreview",
          params: {
            cardId: row.id,
            viewType: "view"
          }
        })
      );
    },
    toNewCard(data) {
      this.$ls.set("prepareTcPCard", data);
      this.$refs.ModifyCard.open();
    },
    toEditCard(row) {
      this.curCard = row;
      this.$ls.set("prepareTcPCard", {
        id: row.id,
        title: row.title,
        type: row.type,
        createMethod: row.createMethod,
        remark: row.remark,
        cardRuleId: row.cardRuleId,
        attachmentId: row.attachmentId
      });
      this.$refs.ModifyCard.open();
    },
    toEditInfo(row) {
      this.curCard = row;
      this.$refs.ModifyCardInfo.open();
    },
    toDelete(row) {
      this.$confirm(`确定要删除题卡【${row.title}】吗?`, "提示", {
        type: "warning"
      })
        .then(async () => {
          await deleteCard(row.id);
          this.$message.success("删除成功！");
          this.deletePageLastItem();
        })
        .catch(() => {});
    },
    async toConvertImage(row) {
      await convertCardImage(row.id);
      this.$message.success("操作成功！");
    },
    // image-preview
    toPreviewImage(row) {
      this.imageList = row.imageUrls;
      this.curImageIndex = 0;
      this.selectImage(0);
      this.$refs.SimpleImagePreview.open();
    },
    selectImage(index) {
      this.curImage = {
        url: this.imageList[index],
        filename: Math.floor(index / 2) + 1 + "-" + ((index % 2) + 1)
      };
    },
    toPrevImage() {
      if (this.curImageIndex === 0) {
        this.curImageIndex = this.imageList.length - 1;
      } else {
        this.curImageIndex--;
      }

      this.selectImage(this.curImageIndex);
    },
    toNextImage() {
      if (this.curImageIndex === this.imageList.length - 1) {
        this.curImageIndex = 0;
      } else {
        this.curImageIndex++;
      }

      this.selectImage(this.curImageIndex);
    }
  }
};
</script>
