<template>
  <v-container class="grey lighten-5">
    <v-row justify="space-between">
      <v-col>
        <v-row dense>
          <v-col>
            <v-card
              color="#385F73"
              dark
            >
              <v-row dense>
                <v-textarea
                  v-model="statusPost.content"
                  solo
                  falt
                  filled
                  auto-grow
                  label="说点什么呢?"
                  rows="3"
                />
              </v-row>
              <v-row>
                <v-col>
                  <!-- 接收 filepond-image 中 this.$emit('resp', resp) 的数据 -->
                  <!--<FilePondUploadImage @resp="uploadCallback" />-->
                  <div>
                    <file-pond
                      ref="pond"
                      name="file"
                      label-idle="选择图片或拖动图片到此处"
                      label-file-processing="图片正在上传，请稍后"
                      label-file-processing-aborted="图片上传被取消"
                      label-tap-to-retry="尝试重试"
                      label-file-processing-complete="图片上传成功！"
                      label-max-file-size="上传的图片大小不能超过 10MB"
                      label-max-file-size-exceeded="上传的图片大小不能超过 10MB"
                      allow-file-size-validation="true"
                      max-file-size="10MB"
                      accepted-file-types="image/png, image/jpeg, image/jpg, image/gif"
                      :allow-multiple="true"
                      :max-files="9"
                      :server="server"
                      :instant-upload="true"
                      @init="handleFilePondInit"
                      @processfile="success"
                      @removefile="removeFile"
                    />
                  </div>
                </v-col>
              </v-row>
              <v-row dense>
                <v-col>
                  <v-card-actions>
                    <v-btn text @click="publish">
                      发布
                    </v-btn>
                  </v-card-actions>
                </v-col>
              </v-row>
            </v-card>
          </v-col>
          <v-col>
            <v-sheet
              class="mx-auto"
              max-width="720"
            />
          </v-col>
          <v-col>
            <div v-infinite-scroll="loadMore" infinite-scroll-disabled="true" infinite-scroll-distance="10">
              <v-col cols="12">
                <v-tabs>
                  <v-tab @click="setType(0)">状态</v-tab>
                  <v-tab @click="setType(1)">视频</v-tab>
                  <v-tab @click="setType(2)">回答</v-tab>
                </v-tabs>

                <v-row
                  v-for="item in cardList"
                  :key="item.statusId"
                  dense
                >
                  <status-card v-if="cardType === 'status'" :item="item" />
                  <item-card v-if="cardType === 'video'" :video="item" />
                  <status-card v-if="cardType === 'answer'" :item="item" />
                </v-row>
              </v-col>
            </div>
          </v-col>
        </v-row>
      </v-col>
      <v-col md="4">
        <v-row dense>
          <v-col cols="12">
            <v-card
              class="mx-auto"
              color="#26c6da"
              dark
            >
              <v-card-title>
                <v-avatar size="32">
                  <v-img
                    :src="this.$store.state.user.userInfo.avatarUrl"
                    :alt="this.$store.state.user.userInfo.username"
                    :title="this.$store.state.user.userInfo.username"
                  />
                </v-avatar>
                <span class="text-h6 font-weight-light">{{ this.$store.state.user.userInfo.username }}</span>
              </v-card-title>
              <v-card-text class="text-h5 font-weight-light">
                {{ this.$store.state.user.userInfo.intro }}
              </v-card-text>
              <v-card-text class="text-h5 font-weight-light">
                关注 {{ this.$store.state.user.userInfo.followingCount }} | 被关注 {{ this.$store.state.user.userInfo.followerCount }}
              </v-card-text>
            </v-card>
          </v-col>
          <v-col cols="12">
            <v-card
              color="#385F73"
              light
            >
              <v-card-title class="text-h5">
                热门问题
              </v-card-title>
              <v-card-text>
                <p class="text-body-1 text--primary">
                  1.第1条
                </p>
                <p class="text-body-1 text--primary">
                  2.第2条
                </p>
              </v-card-text>
            </v-card>
          </v-col>
          <v-col cols="12">
            <v-card
              color="#385F73"
              light
            >
              <v-card-title class="text-h5">
                热门视频
              </v-card-title>
              <v-card-text>
                <p class="text-body-1 text--primary">
                  1.第1条
                </p>
                <p class="text-body-1 text--primary">
                  2.第2条
                </p>
              </v-card-text>
            </v-card>
          </v-col>
        </v-row>
      </v-col>
    </v-row>

    <v-snackbar
      v-model="showMessage"
      :top="true"
      :timeout="3000"
    >
      {{ message }}
      <template v-slot:action="{ attrs }">
        <v-btn
          color="pink"
          text
          v-bind="attrs"
          @click="showMessage = false"
        >
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { pubStatus, statusRecommend } from '@/api/mblog/status'
import { videoTimeline } from '@/api/media/video'
import StatusCard from '@/components/card/status-card'
import ItemCard from '@/components/card/item-card'

import VueFilePond from 'vue-filepond'
import FilePondPluginImagePreview from 'filepond-plugin-image-preview'
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type'
import FilePondPluginFileValidateSize from 'filepond-plugin-file-validate-size'
import 'filepond/dist/filepond.min.css'
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css'

const FilePond = VueFilePond(
  FilePondPluginFileValidateType,
  FilePondPluginImagePreview,
  FilePondPluginFileValidateSize
)
var imgFileIds = []

export default {
  name: 'Home',
  components: {
    FilePond,
    StatusCard,
    ItemCard
  },
  data() {
    return {
      server: {
        url: '//api.reghao.cn/api/file/upload/image',
        revert: null,
        process: {
          headers: {
            'Authorization': this.$store.getters.token
          },
          ondata(formData) {
            return formData
          },
          onload(response) {
            const resp = JSON.parse(response)
            if (resp.code === 0) {
              imgFileIds.push(resp.data.imageFileId)
            } else {
              if (resp.msg != null) {
                this.message = '上传文件出现异常，请重新上传！' + resp.msg
              } else {
                this.message = '上传文件出现异常，请重新上传！'
              }
              this.showMessage = true
            }
          }
        }
      },
      statusPost: {
        imageFileIds: [],
        content: '',
        location: ''
      },
      cardType: null,
      cardList: [],
      busy: false,
      page: 1,
      followingUser: [
        { username: 'haha', avatar: '', userId: 10000 },
        { username: 'haha', avatar: '', userId: 10001 },
        { username: 'haha', avatar: '', userId: 10002 }
      ],
      showMessage: false,
      message: ''
    }
  },
  computed: {
    ...mapGetters({
      statuses: 'my_content',
      option: 'my_content_option',
      showImage: 'image_zoom_show'
    })
  },
  watch: {
    option: {
      handler: function(val, oldVal) {
        if (val && val.page === 1) {
          this.cardList = []
        }
      },
      deep: true
    },
    statuses: function(val, oldVal) {
      if (val) {
        if (this.option.page === 1) {
          this.cardList = val
        } else {
          this.cardList = [...this.cardList, ...val]
        }
      }
    }
  },
  created() {
    this.getFollowingStatus(this.page)
  },
  mounted() {
  },
  methods: {
    ...mapActions([
      'getMyContent'
    ]),
    handleFilePondInit() {
      // FilePond instance methods are available on `this.$refs.pond`
    },
    success(error, metadata) {
      if (error === null) {
        return
      }
    },
    removeFile(error, metadata) {
      if (error === null) {
        const file = metadata.file
        const uploadId = this.imgMap[file.name]
        fetch('//file.reghao.cn/api/file/rm/' + uploadId, {
          headers: {
            'Authorization': this.$store.getters.token
          },
          method: 'DELETE'
        }).then(response => response.json())
          .then(json => {
            console.log('删除 this.statusPost.imageFileIds 中相应的图片')
          })
          .catch(e => {
            return null
          })
      }
    },
    setType(type) {
      if (type === this.type) {
        return
      }

      this.type = type
      this.page = 1
      if (type === 0) {
        this.getFollowingStatus(this.page)
        this.$vuetify.goTo(type)
      } else if (type === 1) {
        this.getFollowingVideos(this.page)
        this.$vuetify.goTo(type)
      } else if (type === 2) {
        this.getFollowingAnswers(this.page)
        this.$vuetify.goTo(type)
      }
    },
    loadMore: function() {
      this.busy = true
      setTimeout(() => {
        if (this.cardType === 'status') {
          this.getFollowingStatus(this.page)
        } else if (this.cardType === 'video') {
          this.getFollowingVideos(this.page)
        } else if (this.cardType === 'answer') {
          this.getFollowingAnswers(this.page)
        }
      }, 1000)
    },
    getFollowingStatus(page) {
      statusRecommend(page)
        .then(res => {
          if (res.code === 0) {
            this.cardType = 'status'

            if (page === 1) {
              this.cardList = []
            }

            for (const item of res.data.list) {
              this.cardList.push(item)
            }
            this.page += 1
            this.busy = false
          } else {
            this.message = res.msg
            this.showMessage = true
          }
        })
        .catch(error => {
          this.message = error.message
          this.showMessage = true
        })
    },
    getFollowingVideos(page) {
      videoTimeline(page)
        .then(res => {
          if (res.code === 0) {
            this.cardType = 'video'

            if (page === 1) {
              this.cardList = []
            }

            for (const item of res.data.list) {
              this.cardList.push(item)
            }
            this.page += 1
            this.busy = false
          } else {
            this.message = res.msg
            this.showMessage = true
          }
        })
        .catch(error => {
          this.message = error.message
          this.showMessage = true
        })
    },
    getFollowingAnswers(page) {
      this.cardType = 'answer'
      console.log('获取关注的用户回答')
    },
    selectFollowingUser() {
      console.log('加载选中用户的状态...')
    },
    publish() {
      if (this.statusPost.content === '') {
        this.message = '内容不能为空'
        this.showMessage = true
        return
      }
      this.statusPost.imageFileIds = imgFileIds

      pubStatus(this.statusPost)
        .then(res => {
          if (res.code === 0) {
            this.message = '状态已发布'
            this.showMessage = true
            this.statusPost.content = ''
            this.statusPost.imageFileIds = []
          } else {
            this.message = res.msg
            this.showMessage = true
          }
        }).catch(error => {
          this.message = error.message
          this.showMessage = true
        })
    }
  }
}
</script>

<style>
</style>
