<template>
  <div>
    <van-popup
      v-model="show"
      position="bottom"
      round
      :close-on-click-overlay="false"
      :style="{ height: '80%' }"
      class="base-info"
    >
      <div style="position:relative;margin-bottom:26px;" class="title">
        <common-svg
          @click.native="cancel"
          name="shanchu5"
          style="position:absolute;left:17px;"
        ></common-svg>
        <span>{{ title !== undefined ? title : '创建模板' }}</span>
      </div>
      <van-field v-model="templateName" placeholder="填写模板名称"></van-field>
      <input
        type="file"
        id="thumb"
        style="display:none"
        @change="handleFileChange"
        accept="image/png,image/jpg,image/jpeg,image/gif"
      />
      <label
        for="thumb"
        class="file-input"
        style="padding: 10px 15px;margin:0 10px;"
      >
        <common-svg name="tianjia" style="margin-right:10px;"></common-svg>
        <span>{{ imgUrl ? '已上传' : '添加模板封面' }}</span>
        <van-image
          :src="imgUrl"
          v-if="imgUrl"
          height="24px"
          width="33px"
          fit="contain"
        ></van-image>
        <common-svg name="jinru"></common-svg>
      </label>
      <div class="btn-group">
        <div @click="handleClickFolder" class="van-ellipsis">
          <span>所在文件夹</span>:
          <span class="classify">{{ folder && folder.name }}</span>
        </div>
        <div @click="next" class="slc-btn-common next">下一步</div>
      </div>
    </van-popup>
    <transition name="van-slide-up">
      <div v-if="showSelectFolder" class="slide-up-folder-list">
        <div class="list-container">
          <div class="move-to-text">请选择文件夹</div>
          <folder-list
            class="folder-list"
            :mode="EFolderListMode.SELECT"
            :selectedfolder="selectedFolder"
            :handleClickFolder="handleClickFolderItem"
          />
          <div class="btn-container">
            <div class="btn-confirm" @click="handleClickConfirm">确定</div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script lang="ts">
import { Component, Prop, PropSync, Vue, Emit } from 'vue-property-decorator';
import {
  Collapse,
  CollapseItem,
  Field,
  Button,
  NavBar,
  SwipeCell,
  Popup,
  Uploader,
  Picker,
  Image,
} from 'vant';
import FolderList from '@/views/components/FolderList.vue';
import { EFolderListMode } from '@/views/components/types';
import { TEMPLATETYPE } from '@/const/enum';
import { namespace } from 'vuex-class';
import { IGetUserFoldersPayload } from '@/store/modules/types';
import { nonWhiteSpace } from 'html2canvas/dist/types/css/syntax/parser';

const Template = namespace('template');

@Component({
  components: {
    [Collapse.name]: Collapse,
    [CollapseItem.name]: CollapseItem,
    [Field.name]: Field,
    [Button.name]: Button,
    [NavBar.name]: NavBar,
    [SwipeCell.name]: SwipeCell,
    [Popup.name]: Popup,
    [Uploader.name]: Uploader,
    [Picker.name]: Picker,
    [Image.name]: Image,
    FolderList,
  },
})
export default class BaseInfo extends Vue {
  private EFolderListMode = EFolderListMode;
  @Prop({ required: false }) private defaultFolderId!: number | undefined;
  @Prop({ required: false }) private title!: string;

  @PropSync('showBaseInfo', { type: Boolean, required: true })
  private show!: boolean;

  @Template.Action('getUserFoldersFixed') private getUserFolders!: (
    payload?: IGetUserFoldersPayload
  ) => Promise<boolean>;
  @Template.State('userFolderList') private userFolderList!: any[];
  @Template.State('page') private page!: number;
  @Template.State('isFinished') private isFinished!: boolean;
  @Template.Mutation('setPage') private setPage!: (page: number) => void;

  private folderId: number | null = null;
  private showSelectFolder: boolean = false;
  private folderList: [] = [];
  private templateName: string = '';
  private imgUrl: string = '';
  // 保存当前选中的文件
  private folder: any = {};
  // 弹出页所选文件夹
  private selectedFolder: any = {};

  private defaultFolderIndex: number = 0;
  private defaultFolderName: string = '未分类文件夹';

  private async mounted() {
    this.fetchList();
  }

  private fetchList() {
    if (this.defaultFolderId !== undefined) {
      this.findFolderByIdContinually(this.defaultFolderId);
      this.folderId = this.defaultFolderId;
    } else {
      this.findFolderByIdContinually(undefined);
    }
  }

  /*
  查找指定id的folder，把folder相关数据保存到data中。
  */
  private async findFolderByIdContinually(folderId: number | undefined) {
    const matchedFolderIndex = this.userFolderList.findIndex((folder: any) => {
      if (folderId !== undefined) {
        return folder.id === folderId;
      } else {
        return folder.name === this.defaultFolderName;
      }
    });
    if (matchedFolderIndex !== -1) {
      // ok 找到文件了或者请求完所有的数据后没有对应的文件
      this.folder = this.userFolderList[matchedFolderIndex];
      this.defaultFolderIndex = matchedFolderIndex;
      if (folderId === undefined) {
        this.$router.replace({
          query: { ...this.$route.query, folderId: this.folder.id },
        });
      }
    } else if (this.isFinished) {
      this.$router.push({ name: '' });
      throw new Error('文件夹列表中无法找到指定的文件夹');
    } else {
      // continue request
      this.setPage(this.page + 1);
      this.getUserFolders({ page: this.page }).then(() => {
        this.findFolderByIdContinually(folderId);
      });
    }
  }

  private handleClickFolderItem(folder: any) {
    this.selectedFolder = folder;
  }

  private handleClickFolder() {
    this.selectedFolder = this.folder;
    this.showSelectFolder = true;
  }

  private async getFolders() {
    const { results = [] } = await this.$api.template.folderList({
      template_type: TEMPLATETYPE.USER,
    });
    this.folderList = results;
  }

  private handleClickConfirm() {
    this.folder = this.selectedFolder;
    this.showSelectFolder = false;
    this.$router.replace({
      query: { ...this.$route.query, folderId: this.selectedFolder.id },
    });
  }

  private next() {
    const { templateName, folder, imgUrl } = this;
    if (!templateName) {
      this.$toast('请输入模板名称');
      return;
    }
    // if (!imgUrl ) {
    //   this.$toast('请上传模板封面');
    //   return;
    // }
    this.$emit('next', {
      templateName,
      folder,
      imgUrl,
    });
    this.show = false;
  }
  @Emit('cancel')
  private cancel() {
    this.show = false;
  }
  private onConfirm(value: any, index: number) {
    this.showSelectFolder = false;
    this.folder = value;
  }
  private onPickerChange(picker: any, value: any, index: number) {
    console.log(index);
  }
  private handleFileChange(e: any) {
    const [file] = e.target.files;
    if (file) {
      this.$api.file.upload(file).then((res: any) => {
        this.imgUrl = res.url;
      });
    }
  }
}
</script>
<style scoped lang="scss">
$bottom-block: calc(40px + 2 * 18px);
.base-info {
  padding: 17px 0 0;
  ::v-deep .van-field__control {
    color: #353535;
    font-size: 22px;
  }
  ::-webkit-input-placeholder {
    color: #cdcdcd;
  }
  .van-cell::after{
    border: 0;
  }
  .title{
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #353535;
    line-height: 22px;
  }
  .file-input {
    display: grid;
    grid-template-columns: 20px auto 32px 20px;
    place-items: center;
    padding: 0 17px;
    background: #f9f9fb;
    color: #444444;
    font-size: 14px;
    span {
      place-self: center start;
    }
  }
  .btn-group {
    color: #b6b5ba;
    font-size: 14px;
    .classify {
      color: #3f79fe;
    }
    .next {
      white-space: nowrap;
      padding: 10px 37px;
      font-size: 16px;
    }
  }
}
.slide-up-folder-list {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  z-index: 3000;
  .list-container {
    overflow: auto;
    height: 100vh;
    padding: 0 16px;
  }
  .move-to-text {
    text-align: left;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #353535;
    margin-top: 17px;
    margin-bottom: 12px;
  }
  .folder-list {
    margin-bottom: $bottom-block;
  }
  .btn-container {
    position: fixed;
    bottom: 0px;
    left: 0;
    right: 0;
    height: $bottom-block;
    background: white;
    .btn-confirm {
      margin: 18px 20px;
      width: 335px;
      height: 40px;
      background: linear-gradient(270deg, #6c7afe 0%, #5d7bf6 100%);
      border-radius: 4px;

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