<template>
  <div class="teampk_box">
    <van-nav-bar :title="title" left-text="返回" @click-left="$route_back" left-arrow style="font-size:0.32rem;"></van-nav-bar>
    <div class="body_com has_header">
      <van-tabbar class="tabbar_list" v-model="active1" :fixed="false" @change="onChange">
        <van-tabbar-item name="running" class="list">进行中</van-tabbar-item>
        <van-tabbar-item name="noStart" class="list">未开始</van-tabbar-item>
        <van-tabbar-item name="over" class="list">已结束</van-tabbar-item>
      </van-tabbar>
      <div ref="pkNoticeRef" style="clear: both;">
        <van-notice-bar v-if="novice" wrapable mode="closeable" @close="closeNotice">团队PK的积分是独立的，不计入A、B分排名和统计</van-notice-bar>
      </div>
      <van-search placeholder="请输入搜索团队名称" v-model="filter.keyword" />

      <div class="pk-list-block" :style="{ height: novice ? noviceHeight : 'calc(100% - 2.85rem)' }">
        <scroller ref="my_scroller" :on-refresh="refresh" :on-infinite="infinite">
          <noData :detail_text="tips" :list="list" />
          <van-panel class="pk_list" v-for="(item, index) in list" :key="index" :title="item.name">
            <div class="teams_list_time">时间：{{ item.start_time }} 至 {{ item.end_time }}</div>
            <div class="teams_btn">
              <van-button v-if="item.creator_id == employee_id && filter.status == 'waiting'" type="danger" @click="del_pk(item)" size="small">删除</van-button>

              <van-button
                v-if="(item.creator_id == employee_id || returnEm(item.managers)) && (filter.status == 'waiting' || filter.status == 'running')"
                class="set"
                plain
                hairline
                type="info"
                @click="set_pk(item)"
                size="small"
              >
                设置
              </van-button>
              <span><van-button class="see" type="info" @click="read_pk(item)" size="small">查看</van-button></span>

              <!-- <span v-if="is_creator == 1 || item.creator_id == employee_id"><van-button class="see" type="info" @click="read_pk(item)" size="small">查看</van-button></span> -->
<!--              <span v-else>
                <van-button
                  v-for="(d, i) in item.employees"
                  :key="i"
                  v-if="d.id == employee_id || item.managers[0].id == employee_id"
                  class="see"
                  type="info"
                  @click="read_pk(item)"
                  size="small"
                >
                  查看
                </van-button>
              </span> -->
            </div>
          </van-panel>
        </scroller>
      </div>
      <div class="create_pk_box" :class="{ isIos: isIos }" v-if="this.getRole_noe"><van-button class="create_pk" type="info" block @click="create_pk">创建PK</van-button></div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import Vue from 'vue'
import { getRole_noe, _debounce } from '@/utils/auth'
import { Tab, Tabs, Search, List, Tabbar, TabbarItem, panel, NoticeBar } from 'vant'
Vue.use(Tab)
  .use(Tabs)
  .use(Search)
  .use(List)
  .use(Tabbar)
  .use(TabbarItem)
  .use(panel)
  .use(NoticeBar)

export default {
  comments: {},
  data () {
    return {
      getRole_noe: '', // 权限判断
      tips: '暂无数据',
      active: 0,
      title: '团队PK',
      list: null,
      loading: false,
      finished: false,
      active1: 'running',
      filter: {
        page: 1,
        type: 'all',
        status: 'running',
        keyword: ''
      },
      create_pk_show: false,
      employee_id: this.$store.getters.user_info.id,
      is_creator: this.$store.getters.user_info.is_creator,
      novice: false,
      noviceHeight: null,
      isIos: false
    }
  },
  watch: {
    'filter.keyword': {
      deep: true,
      handler: _debounce(function () {
        this.$toast.loading({
          message: '正在加载'
        })
        this.refresh(function () {
          self.$toast.clear()
        })
      })
    }
  },
  mounted () {
    // 有管理权限的人才可以设置PK
    // if (this.$store.getters.user_info.employee_detail.manage_scope.length > 0) {
    //   this.create_pk_show = true
    // }
    this.getLocalStorage()
    this.$nextTick(() => {
      setTimeout(() => {
        if (this.novice) {
          this.noviceHeight = 'calc(100% - 2.85rem - ' + this.$refs.pkNoticeRef.offsetHeight + 'px )'
        }
      }, 100)
    })
    if (window.plus) {
      this.isIos = plus.storage.getItem('iPhone')
    }
  },
  methods: {
    returnEm: function (item) {
      var is = false
      item.forEach(d => {
        if (d.id == this.employee_id) {
          is = true
        }
      })
      return is
    },
    getLocalStorage () {
      if (!localStorage.getItem('pkNovice') || (window.plus && !plus.storage.getItem('pkNovice'))) {
        this.novice = true
      } else {
        this.novice = false
      }
    },
    closeNotice () {
      window.plus ? plus.storage.setItem('pkNovice') : localStorage.setItem('pkNovice', true)
      this.getLocalStorage()
    },
    // 删除
    del_pk (d) {
      let self = this
      this.$dialog
        .confirm({
          title: '删除',
          message: '确认删除此团队PK?'
        })
        .then(() => {
          self.showLoading()
          request('delete', '/api/integral/pk', { pk_id: d.id })
            .then(res => {
              if (res.data.code == 1) {
                self.$toast(res.data.msg)
                self.get_pk_list()
              } else {
                self.$toast(res.data.msg)
                Toast.clear()
              }
            })
            .finally(() => this.$toast.clear())
        })
    },
    read_pk (d) {
      let status = this.filter.status
      const managers = d.managers.map(o => o.id).join(',')
      const creator_id = d.creator_id
      const enbale_leader_record = d.leader_can_record

      this.$router.push({ name: 'read_pk', query: { id: d.id, managers, creator_id, pk_status: status, enbale_leader_record } })
    },
    // 加载
    showLoading () {
      this.$toast.loading({
        loadingType: 'spinner',
        message: '正在处理'
      })
    },
    // 监听切换
    onChange (index) {
      let self = this
      this.list = null
      this.$toast.loading({
        loadingType: 'spinner',
        message: '正在处理'
      })
      switch (index) {
        case 'noStart':
          this.filter.status = 'waiting'
          this.refresh(function () {
            self.$toast.clear()
          })
          break
        case 'over':
          this.filter.status = 'end'
          this.refresh(function () {
            self.$toast.clear()
          })
          break
        default:
          this.filter.status = 'running'
          this.refresh(function () {
            self.$toast.clear()
          })
      }
    },
    // 设置PK
    set_pk (item) {
      this.$router.push({ name: 'edit_pk', query: { id: item.id } })
    },
    // 创建PK
    create_pk () {
      this.$router.push({ name: 'create_pk' })
    },
    // 获取列表
    get_pk_list (done) {
      let self = this
      if (!self.is_creator) {
        self.filter.type = 'myself'
      }
      request('get', '/api/integral/pk/list', self.filter).then(res => {
        done()
        if (res.data.code == 1) {
          self.$refs.my_scroller.finishInfinite(!res.data.data.list.length != '10') // 停止上滚加载下一页，由于服务器端没有统一空数据和正常数据的格式，所以通过total字段来判定数据是否存在下一页
          if (res.data.data.list.total) {
            for (let i in res.data.data.list.list) {
              self.list.push(res.data.data.list.list[i])
            }
          }
          self.filter.page++
        } else {
          self.$refs.my_scroller.finishInfinite(true)
        }
      })
    },
    refresh (done) {
      let self = this
      setTimeout(() => {
        this.filter.page = 1
        this.get_pk_list(function () {
          self.list = []
          done()
        })
      }, 100)
    },
    infinite (done) {
      this.get_pk_list(done)
    }
  },
  created () {
    this.getRole_noe = getRole_noe()
    this.$nextTick(() => {
      this.$refs.my_scroller.finishInfinite(false)
    })
  },
  keep_alive_update: {
    add_pk_rules_list: function (vm, data) {
      vm.refresh(function () {})
    },
    // 运用缓存更新方法来完成返回后的更新
    update_list_pk: function (vm, data) {
      for (let i in vm.list) {
        if (vm.list[i].id == data.pk_id) {
          vm.list[i].name = data.name
          vm.list[i].end_time = data.end_time
          vm.list[i].start_time = data.start_time
        }
      }
    }
  }
}
</script>

<style scoped>
.body_com {
  position: relative;
  height: calc(100% - 1.2rem);
}
.pk-list-block {
  background-color: #f5f7fa;
  padding: 0;
  position: relative;
  height: calc(100% - 2.85rem);
}

/* 顶部分类列表 */
.teampk_box .tabbar_list {
  height: 1rem;
}
.teampk_box .tabbar_list .list {
  font-size: 0.28rem;
  line-height: 0.88rem;
  padding-bottom: 0.1rem;
}
.teampk_box /deep/ .van-tabbar-item {
  border-bottom: 0.04rem solid transparent;
}
.teampk_box /deep/ .van-tabbar-item--active {
  color: #26a2ff;
  border-bottom: 0.04rem solid #26a2ff;
}

/* 搜索 */
.teampk_box /deep/ .scroller-blur {
  background: transparent;
}
.teampk_box /deep/ .scroller-blur .van-search__content {
  padding: 0.05rem 0.1rem;
  background: #fff;
  border-radius: 0.08rem;
}
.teampk_box /deep/ .scroller-blur .van-icon {
  color: #909399;
  padding-left: 0.1rem;
}
.teampk_box /deep/ .scroller-blur input::-webkit-input-placeholder {
  color: #909399;
  font-size: 0.28rem;
}

/* PK列表 */
.teampk_box /deep/ .pk_list {
  margin: 0.2rem 0.32rem 0.2rem;
  padding: 0.2rem 0.32rem 0.4rem;
  background: #fff;
  border-radius: 0.08rem;
}
.teampk_box /deep/ .pk_list .van-cell {
  padding: 0;
}
.teampk_box /deep/ .pk_list .van-cell .van-cell__title span {
  font-size: 0.32rem;
  font-weight: 500;
  line-height: 0.72rem;
}
.teampk_box /deep/ .van-cell:not(:last-child)::after {
  padding-left: 0;
  left: 0;
}
.teampk_box /deep/ .pk_list .teams_list_time {
  font-size: 0.28rem;
  color: #909399;
  padding: 0.2rem 0 0.3rem;
}
.teampk_box /deep/ .pk_list .teams_btn {
  text-align: right;
}

.teampk_box /deep/ .pk_list .teams_btn .set:active {
  color: #fff;
  background: #1989fa;
}

.teampk_box /deep/ .pk_list .teams_btn .see:active {
  color: #fff;
  background: #1276db;
}

.teampk_box .create_pk_box {
  display: block;
  text-align: center;
  background: #e4e7eb;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding-bottom: 0.2rem;
}

.teampk_box .create_pk_box .create_pk {
  display: inline-block;
  width: calc(100vw - 0.64rem);
  margin-top: 0.2rem;
}
.isIos {
  padding-bottom: 0.4rem !important;
}
</style>
