<template>
  <div class="template-list">
    <div
      style="
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      "
    >
      <p class="title">{{ folderName }}</p
      ><router-link
        v-if="isFolderList"
        :to="{ name: 'Add', query: { folderId: id } }"
        tag="p"
        style="color: #3f79fe;white-space:nowrap;"
        > <common-svg name="xuanzemoban-tianjia1" width="11px" style="margin-right:5px"></common-svg>添加模板</router-link
      >
    </div>
    <empty
      v-if="!list"
      name="moban"
      tip="您还未添加模板"
      style="margin-top: 30vh"
    ></empty>
    <template-item
      v-for="{ id, s_image_url, name, info } of list"
      :key="id"
      @click.native="goProofDetail(id)"
      @show-more-action="showMoreAction"
      :id="id"
      :thumb="s_image_url"
      :title="name"
      :desc="info"
    ></template-item>
    <more-action
      :show.sync="show"
      :title="currentTem.name"
      :date="currentTem.update_time"
      :iconSrc="currentTem.s_image_url"
      :menuList="actionList"
      @cb="callbackAction"
    ></more-action>
    <van-dialog
      title="重命名"
      v-model="isShowRename"
      show-cancel-button
      @confirm="onConfirm"
    >
      <van-field v-model="currentTem.name" ref="rename"/>
    </van-dialog>
    <base-pop-up
      :show.sync="folderMoveingPopupVisible"
      title="移动至"
      class="base-pop-up"
      @closed="handlePopupClose"
    >
      <folder-list
        v-if="movingStep === EMovingStep.FOLDER"
        :handleClickFolder="handleClickFolder"
        :mode="EFolderListMode.SHOW"
      />
      <template-item
        v-else-if="movingStep === EMovingStep.TEMPLATE"
        v-for="{ id, s_image_url, name, info } of templateList"
        :key="id"
        :id="id"
        :thumb="s_image_url"
        :title="name"
        :desc="info"
        :showActionIcon="false"
      ></template-item>
      <div
        class="btn-move-confirm"
        :style="getBtnMoveConfirmStyle"
        @click="handleClickMove"
      >
        移动至当前位置
      </div>
    </base-pop-up>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch, Mixins } from 'vue-property-decorator';
import TemplateMixin from '@/mixins/template';
import TemplateItem from './components/TemplateItem.vue';
import basePopup from '@/components/basePopup/index.vue';
import FolderList from '@/views/components/FolderList.vue';
import { Toast } from 'vant';
import { Mutation, State } from 'vuex-class';
import { EFolderListMode } from '../components/types';
import { EMovingStep } from './types';

@Component({
  components: {
    TemplateItem,
    BasePopUp: basePopup,
    FolderList,
  },
})
export default class List extends Mixins(TemplateMixin) {
  private EMovingStep = EMovingStep;
  private EFolderListMode = EFolderListMode;
  private movingStep = EMovingStep.FOLDER;
  private list: any[] = [];
  private show: boolean = false;
  private isShowRename: boolean = false;
  private currentTem: object = {};
  @Prop() private id!: number;
  @Prop({})
  private templList!: string;
  @Prop()
  private folderName!: string;
  @State('movedTemplateId') public movedTemplateId!: number;

  private folderIdPreparedToMoveIn = -1;

  private templateList = [];

  get isFolderList() {
    return this.id !== undefined;
  }

  private mounted() {
    this.fetchTemplList();
  }

  private fetchTemplList() {
    if (this.id === null || this.id === undefined) {
      const folderName = this.folderName;
      this.$api.template.systemList().then((ret: any) => {
        const results = ret.results;
        const folder = results.find(
          (item: any) => item.folder_name === folderName
        );
        const list = folder.detail;
        this.list = list;
      });
    } else {
      this.getTemplateListToList(+this.id);
    }
  }

  private isSystemCategory() {
    if (this.id === null || this.id === undefined) {
      return true;
    } else return false;
  }

  private goProofDetail(templateId: string) {
    this.$router.push({ name: 'ProofDetail', query: { templateId } });
  }

  get actionList() {
    const isSystemCategory = this.isSystemCategory();
    const { rename, move, copy, del, edit } = this.ActionList;
    if (isSystemCategory) {
      return [edit];
    } else {
      return [edit, rename, move, copy, del];
    }
  }

  private async callbackAction(cb: any) {
    // cb是什么东西？
    this.isShowRename = await cb.call(this, this.currentTem, this.isSystemCategory());
    if(this.isShowRename){
      this.$nextTick(()=>{
        (this.$refs.rename as any).focus()
      })
    }
    this.getTemplateListToList(+this.id);
  }

  private getTemplateById(id: number) {
    return this.list.find((item: any) => item.id === id);
  }

  private showMoreAction(data: any) {
    const template = {
      ...this.getTemplateById(data.id),
      folderId: this.id,
    };
    this.currentTem = template;
    this.show = true;
  }
  private async onConfirm() {
    const params = this.currentTem;
    await this.$api.template.updateCustomize(params);
    this.getTemplateListToList(+this.id);
  }

  private getTemplateListToList(folderId: number) {
    return this.$api.template.list({ id: [folderId] }).then((ret: any) => {
      const result = ret.results;
      const list = result[0].detail;
      this.list = list;
    });
  }

  private getTemplateListToPopup(folderId: number) {
    return this.$api.template.list({ id: [folderId] }).then((ret: any) => {
      const result = ret.results;
      const templateList = result[0].detail;
      this.templateList = templateList;
    });
  }

  private handleClickFolder(folder: any) {
    this.movingStep = EMovingStep.TEMPLATE;
    this.folderIdPreparedToMoveIn = folder.id;
    this.getTemplateListToPopup(folder.id);
  }

  private handlePopupClose() {
    this.movingStep = EMovingStep.FOLDER;
  }

  get getBtnMoveConfirmStyle() {
    return {
      color: this.movingStep === EMovingStep.TEMPLATE && '#FFFFFF',
      background:
        this.movingStep === EMovingStep.TEMPLATE &&
        'linear-gradient(270deg, #6C7AFE 0%, #5D7BF6 100%)',
    };
  }

  private handleClickMove() {
    if (this.movingStep === EMovingStep.TEMPLATE) {
      const folderId = this.folderIdPreparedToMoveIn;
      const id = this.focusedTemplateId;
      this.$api.template
        .updateCustomize({
          id: id, // 模板id
          folder_id: folderId, //要移动到的文件id
        })
        .then(async () => {
          await this.getTemplateListToList(+this.id);
          this.folderMoveingPopupVisible = false;
          Toast.success({
            message: '移动成功',
          });
        });
    }
  }
}
</script>
<style scoped lang="scss">
.template-list {
  box-sizing: border-box;
  min-height: 100vh;
  padding: 11px 14px;
  background: #f9fbff;
  .title{
    flex-grow: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #353535;
  }
  a {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 20px;
    margin-bottom: 20px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 2px 10px 0px rgba(240, 242, 246, 1);
    border-radius: 27px;
    border: 1px solid rgba(220, 231, 255, 1);
    .left span {
      font-size: 14px;
      font-weight: 500;
      color: rgba(53, 53, 53, 1);
    }
  }
  .system-template {
    text-align: left;
    ul {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      font-size: 12px;
      text-align: center;
    }
  }
  .placeholder-when-switch-template {
    margin-bottom: 76px;
  }

  .base-pop-up {
    padding-bottom: 76px;
    .btn-move-confirm {
      position: absolute;
      bottom: 0;
      left: 20px;
      right: 20px;
      bottom: 18px;
      width: 335px;
      height: 40px;
      background: #b2c9ff;
      border-radius: 4px;

      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ffffff;
      line-height: 40px;
    }
  }
}
</style>
