<template>
  <div class="layoutsMain">

    <Loading :loading="!pageLoading" />

    <div v-show="pageLoading">
      <div v-show="vshowList">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list v-model="loading" :finished="finished" @load="onLoad">
            <div v-for="item in list" :key="item.id" :title="item" class="item-box" @click="goView(item)">
              <div class="remind">
                <van-image :src="require('../../../static/images/icon_pdf.png')" />
              </div>
              <div class="detail">
                <div class="notice-header">
                  <div class="notice-title">{{ item.name }}</div>
                </div>
                <div class="notice-content">
                  {{ item.fileSize}}
                </div>
              </div>

              <div class="line"></div>
              <div class="arrow">
                <van-image class="imgview" :src="require('../../../static/images/icon_view.png')" />
                查看
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
        <van-empty v-if="list.length == 0" description="暂无数据" />
      </div>

      <div v-show="!vshowList" class="jurisdiction">
        <van-image :src="require('../../../static/images/icon_jurisdiction.png')" />
        <div>{{nomessage}}</div>
      </div>

    </div>

  </div>
</template>

<script>
  import Loading from '@/components/Loading';

  import * as dd from 'dingtalk-jsapi';
  export default {
    data() {
      return {
        list: [],
        pageLoading: false,
        vshowList: true,
        loading: false,
        finished: false,
        refreshing: false,
        nomessage: '暂无访问权限',
        watermark: 'HSAY',
        pageInfo: {
          pageIndex: 1,
          pageSize: 10
        },
      }
    },
    components: {
      Loading
    },
    created() {
      this.getAuthconfig();
    },
    methods: {
      goView(item) {
        this.$router.push({
          name: 'page',
          query: {
            id: item.id,
            title: item.name
          }
        })
      },
      onLoad() {

        let self = this
        //判断获取到分类id
        if (this.$route.query.typeId) {
          if (this.refreshing) {
            this.list = []
            this.refreshing = false
            this.pageInfo.pageIndex = 1
          }

          const params = {
            typeId: this.$route.query.typeId || '',
            page: this.pageInfo.pageIndex,
            pageSize: this.pageInfo.pageSize
          }
          this.$api.user.getDocList(params).then((response) => {
            self.pageLoading = true;

            const res = response.data;

            if (res.code == 0 && res.data.list) {
              if (res.data.list.length == 1 && this.pageInfo.pageIndex == 1) {
                self.loading = false
                self.finished = true
                let item = res.data.list[0];
                this.$router.replace({
                  name: 'page',
                  query: {
                    id: item.id,
                    title: item.name
                  }
                })
              } else {
                self.list.push(...res.data.list)
                self.watermark = res.data.watermark;
                self.pageInfo.pageIndex += 1
                self.loading = false
                if (self.list.length >= res.data.totalCount) {
                  self.finished = true
                }
                this.ChangePageTitle(self.list[0].typeName)
              }
            } else if (res.code == 1000) { //没有查看权限
              this.vshowList = false;
              this.nomessage = res.message
            }
          }).catch(err => {
            console.log(err);
            self.pageLoading = true;
          });
        } else if (this.$route.query.docId) { //直接获取到分件Id 打开文件, title: '阅读'  
          this.$api.user.getDetail(this.$route.query.docId, localStorage.userId || '').then((response) => {
            self.pageLoading = true;
            const res = response.data.data;
            if (res.code == 0 && res.data) {
              let path = res.data.path || ''
              this.$router.replace({
                name: 'page',
                query: {
                  path: path,
                  title: res.data.fileName
                }
              })
            } else if (res.code == 1000) { //没有查看权限
              this.vshowList = false;
              this.nomessage = res.message
            }
          }).catch(err => {
            console.log(err);
            self.pageLoading = true;
          });
        }
      },
      onRefresh() {
        // 清空列表数据
        this.finished = false
        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        this.loading = true
        this.onLoad()
      },
      //钉钉授权
      getAuthconfig() {

        this.$api.user.authconfig({
          url: location.origin + '/'
        }).then((response) => {
          if (response.data.code == 0) {
            if (dd.env.platform != 'notInDingTalk') {
              //该方法必须带上，用来捕获鉴权出现的异常信息，否则不方便排查出现的问题
              dd.ready(() => {
                dd.runtime.permission.requestAuthCode({
                  corpId: response.data.data.corpId, // 企业id
                  onSuccess: (info) => {
                    localStorage.setItem('hsayi-token', info.code);
                    this.getUserInfo();
                  },
                  onFail: function (err) {
                    console.log(err);
                    this.pageLoading = true;
                    this.vshowList = false;
                    alert('dd error: ' + JSON.stringify(err));
                  }
                });
              });

              dd.biz.navigation.setRight({
                show: false, //控制按钮显示， true 显示， false 隐藏， 默认true
                control: false, //是否控制点击事件，true 控制，false 不控制， 默认false
                showIcon: false, //是否显示icon，true 显示， false 不显示，默认true； 注：具体UI以客户端为准
                onSuccess: () => {},
                onFail: function (err) {
                  console.log(err);
                  alert('dd error: ' + JSON.stringify(err));
                }
              });

            } else {
              //本地调试不在钉钉上
              this.vshowList = false;
              localStorage.setItem('hsayi-token', '5c976f38445339f6b302390a61653b69');
              this.getUserInfo();
            }
          }
        }).catch(err => {
          console.log(err);
          this.pageLoading = true;
        });
      },
      // 获取用户信息
      getUserInfo() {
        this.$api.user.userinfo().then((res) => {
          if (res.data.code == 0) {
            localStorage.setItem('userId', res.data.data.userId);
            this.vshowList = true;
            this.onLoad();
          }
        }).catch(err => {
          console.log(err);
          this.pageLoading = true;
        });
      },
      ChangePageTitle(title) {
        if (dd.env.platform != 'notInDingTalk') {
          dd.ready(function () {
            dd.biz.navigation.setTitle({
              title: title, //控制标题文本，空字符串表示显示默认文本
              onSuccess: function (result) {
                console.log(result);
              },
              onFail: function (err) {
                console.log(err);
              }
            });
          });
        } else {
          document.title = title
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  @import "index.less";
</style>