<template>
  <div class="index">
    <van-image
      v-if="banner === 'bannerChainSearch'"
      class="banner"
      src="@/assets/bannerChainSearch.png"
      fit="contain"
      width="100%"
    ></van-image>
    <van-image
      v-else-if="banner === 'bannerHD'"
      class="banner"
      src="@/assets/bannerHD.png"
      fit="contain"
      width="100%"
    ></van-image>
    <van-image
      v-else
      class="banner"
      src="@/assets/indexbanner.png"
      fit="contain"
      width="100%"
    ></van-image>
    <!-- <div class="header">
      <div class="login" v-if="!isLogin">
         <p>~ 欢迎来到{{APP_NAME}}平台</p>
         <div class="button" @click="toLogin">登录/注册</div>
      </div>
      <div class="proof" v-else>
        <div>我的存证数量</div>
        <div class="count">{{proofCount}}</div>
      </div>
    </div> -->
    <div class="template-list">
      <section class="system-template">
        <p style="font-size: 16px; color: #353535; font-weight: 500">
          系统模版
        </p>
        <div class="list">
          <sys-folder-item
            v-for="{ id, folder_simg_url, folder_name, detail } of systemList"
            :key="id"
            :thumb="folder_simg_url"
            :name="folder_name"
            @click="goTemplList(detail, folder_name, id)"
          ></sys-folder-item>
        </div>
      </section>
      <section>
        <div
          style="
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            font-size: 16px;
            color: #353535;
            margin: 16px 0;
          "
        >
          <span style="font-weight: 500; color: #353535">我的模版</span>
          <div>
            <common-svg v-if="isLogin" @click="handleClickAddFolder" name="xuanzemoban-tianjia1" width="11px" style="margin-right:5px"></common-svg>
            <span
              v-if="isLogin"
              style="color: #3f79fe"
              @click="handleClickAddFolder"
              >添加文件夹</span
            >
          </div>
        </div>
        <empty
          class="empty"
          v-if="!loading && list.length === 0"
          name="moban"
          tip="您还未添加模板"
        ></empty>
        <folder-list
          v-if="isLogin"
          :mode="EFolderListMode.ACTION"
          :handleClickFolder="handleClickFolder"
          :clickAction="handleClickAction"
        />
        <more-action
          :show.sync="show"
          :menuList="actionList"
          :title="currentFolder.folder_name"
          :date="currentFolder.update_time"
          :iconSrc="currentFolder.folder_simg_url"
          @cb="callbackAction"
        ></more-action>
      </section>
    </div>
    <van-dialog
      title="重命名"
      v-model="isShowRename"
      show-cancel-button
      @confirm="onConfirm"
    >
      <van-field v-model="currentFolder.folder_name" ref="rename"/>
    </van-dialog>
    <add-folder
      ref="addFolder"
      :show.sync="showAddFolder"
      @cancel="showAddFolder = false"
      @next="addFolder"
    ></add-folder>
  </div>
</template>

<script lang="ts">
import {
  Component,
  Prop,
  Vue,
  Watch,
  Inject,
  Mixins,
} from 'vue-property-decorator';
import { State, Action, namespace } from 'vuex-class';
import IndexMixin from '@/mixins/Index';
import AddFolder from '@/views/template/components/AddFolder.vue';
import SysFolderItem from './components/SysFolderItem.vue';
import UserFolderItem from './components/UserFolderItem.vue';
import FolderList from '@/views/components/FolderList.vue';
import { IGetUserFoldersPayload } from '@/store/modules/types';
import { EFolderListMode } from '../components/types';
import { Toast } from 'vant';

const Proof = namespace('proof');
const Template = namespace('template');
@Component({
  components: {
    AddFolder,
    SysFolderItem,
    UserFolderItem,
    FolderList,
  },
})
export default class IndexSy extends Mixins(IndexMixin) {
  @Inject('APP-NAME') private APP_NAME!: string;
  @State('isLogin2') private isLogin!: boolean;
  @Proof.State('proofCount') private proofCount!: number;
  @Proof.Action('getProofCount') private getProofCount!: any;
  @Template.Action('getUserFoldersFixed') private getUserFolders!: (
    payload?: IGetUserFoldersPayload
  ) => void;
  @Template.Mutation('setPage') private setPage!: (page: number) => void;
  @Template.State('page') private page!: number;
  @Template.State('userFolderList') private list!: any[];
  private currentFolder: object = {};
  private show: boolean = false;
  private isShowRename: boolean = false;
  private loading: boolean = true;
  private showAddFolder: boolean = false;
  private EFolderListMode = EFolderListMode;
  
  @Watch('isLogin', { immediate: true })
  private async onIsLoginChange(newIsLogin: boolean | null, oldVal: boolean) {
    if (newIsLogin === null) {
      // 
    } else if (typeof newIsLogin === 'boolean') {
      if (!newIsLogin) {
        this.loading = false;
      } else {
        this.setPage(1);
        const promises = [this.getProofCount(), this.getUserFolders()];
        await Promise.all(promises);
        this.loading = false;
      }
    }
  }
  private getFolderById(folderId: number) {
    const folder = this.list.find((item: any) => item.id === folderId);
    return folder;
  }

  private async showMoreAction(folderName: any, folderId: number) {
    const folder = this.getFolderById(folderId);
    
    this.currentFolder = {
      folder_name: folderName,
      folder_id: folderId,
      ...folder
    };
    this.show = true;
  }

  private get banner(){
    return process.env.VUE_APP_BANNER
  }

  private async addFolder({ folderName }: any) {
    this.showAddFolder = false;
    await this.$api.template.addFolder(folderName);
    this.setPage(1);
    await this.getUserFolders({ page: this.page });
  }

  private handleClickFolder(folder: any) {
    this.$router.push({
      name: 'TemplList',
      query: { folderName: folder.name, id: folder.id },
    });
  }

  private handleClickAction(folder: any){
    this.showMoreAction(folder.name, folder.id);
  }

  private toLogin() {
    this.$router.push({ name: 'Login' });
  }
  private goTemplList(templList: [] = [], folderName = '', id: any) {
    this.$router.push({ name: 'TemplList', query: { folderName, id } });
  }
  get actionList() {
    const { rename, del } = this.ActionList;
    return [rename, del];
  }
  private async callbackAction(cb: any) {
    this.isShowRename = await cb.call(this, this.currentFolder, this.refreshPage);
    if(this.isShowRename){
      this.$nextTick(()=>{
        (this.$refs.rename as any).focus();
      })
    }
  }

  private async refreshPage(){
    this.setPage(1);
    await this.getUserFolders({
      page: this.page
    });
  }

  private async onConfirm() {
    const params = this.currentFolder;
    await this.$api.template.updateFolder(params);
    await this.refreshPage();    
    Toast.success({
      message: "重命名成功"
    })
  }

  private handleClickAddFolder(){
    this.showAddFolder = true
    this.$nextTick(()=>{
      (this.$refs?.addFolder as any).$refs?.folderName?.focus();
    })
  }
}
</script>
<style scoped lang="scss">
.index {
  margin-bottom: $tabHeight;
  padding: 11px 14px;
  .banner{
    margin-top: 5px;
  }
  .empty{
    margin-top: 70px;
  }
  div.header {
    padding: 36px 21px;
    text-align: left;
    background: url('../../assets/index.png');
    background-size: cover;
    box-shadow: 0px 5px 20px 0px rgba(63, 121, 254, 0.34);
    .login {
      p {
        font-size: 20px;
        font-weight: 500;
        color: rgba(255, 255, 255, 1);
      }
      div.button {
        display: inline-block;
        padding: 10px 20px;
        border-radius: 18px;
        font-size: 12px;
        font-weight: 500;
        color: rgba(13, 88, 227, 1);
        background: #ffffff;
      }
    }
    .proof {
      font-size: 12px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      .count {
        font-size: 40px;
        font-weight: 500;
      }
    }
  }
  .template-list {
    .system-template {
      text-align: left;
      .list {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        font-size: 12px;
        text-align: center;
      }
    }
  }
  .van-dialog {
    border-radius: 6px !important;
  }
}
</style>
