<template>
  <div style="height: 100%">
    <div class="pk_team_scroller">
      <scroller>
        <div class="pk-team__wrap" v-for="(item, i) in teams_list" :key="i">
          <div class="pk-team__headedr">
            <div class="pk-team__title">
              <span>{{ item.name }}</span>
            </div>
            <div class="pk-team__toolbar">
              <van-button
                hairline
                type="info"
                v-if="hasPermission && pkStatus !== 'end'"
                @click="edit_team_btn(item)"
                size="mini"
                round
              >设置</van-button>
              <van-button
                hairline
                type="danger"
                v-if="hasPermission && pkStatus !== 'end'"
                @click="del_team(get_id,item)"
                size="mini"
                round
              >删除</van-button>
            </div>
          </div>
          <div class="team-member__list">
            <div class="team-member__item">
              <icon name="team_pk_leader" height="0.4rem" width="0.44rem" />
              <span class="team-member__name"><Wxopendata type="userName" :openid="item.leader.name"></Wxopendata>(队长)</span>
            </div>
            <div
              class="team-member__item"
              v-for="(m, j) in item.members"
              :key="j"
              v-show="m.id !== item.leader.id"
            >
              <icon name="team_pk_member" height="0.4rem" width="0.44rem" />
              <span class="team-member__name"><Wxopendata type="userName" :openid="m.name"></Wxopendata></span>
            </div>
          </div>
        </div>
        <noData :list="teams_list" />
        <div style="height: 1.5rem;"></div>
      </scroller>
    </div>
    <div style="padding: 0 0.32rem;" v-if="hasPermission  && pkStatus !== 'end' ">
      <van-button class="create_pk" type="info" block @click="add_team_btn">新增团队</van-button>
    </div>
    <div
      style="padding: 0 0.32rem;"
      v-else
      v-for="(item,index) in pk_info.manager_ids"
      :key="index"
    >
      <van-button
        v-if="$store.getters.user_info.id == item  && pkStatus !== 'end'"
        class="create_pk"
        type="info"
        block
        @click="add_team_btn"
      >新增团队</van-button>
    </div>

    <!-- 团队弹窗 -->
    <van-dialog
      v-model="show_team_popup"
      :closeOnClickOverlay="false"
      @cancel="team_cancel"
      :before-close="checkTeamForm"
      show-cancel-button
      class="team_popup"
    >
      <van-field
        required
        type="text"
        label="团队名称"
        name="团队名称"
        maxlength="15"
        v-model="popup_teams_name"
        v-validate="'required'"
        placeholder="请输入团队名称"
      />
      <van-cell
        required
        title="成员"
        name="成员"
        @click="onOpenEmployee"
        is-link
      >
        <template slot="default">
          <span v-for="(item,index) in select_employee_name" :key="index">
            <Wxopendata type="userName" :openid="item.name"></Wxopendata><span v-if="(select_employee_name.length-index)>1">,</span>
          </span>
        </template>
      </van-cell>
      <van-cell
        required
        title="队长"
        @click="open_captain"
        name="队长"
        :value="formData.leader.name"
        is-link
      >
        <template slot="default" v-if="formData.leader.name">
            <Wxopendata type="userName" :openid="formData.leader.name"></Wxopendata>
        </template>
      </van-cell>
    </van-dialog>

    <!-- 选择成员 -->
    <EmployeeSelector
      :can_select_employee="true"
      :can_select_dept="false"
      :selected.sync="selected"
      :dept_multi="false"
      @confirm="move_confirm"
      :visible.sync="show_employee_selector"
      @cancel="move_cancel"
    ></EmployeeSelector>

    <!-- 队长选择 -->
    <van-popup v-model="showCaptain" position="bottom">
        <!-- :columns="team_employee_list" -->
      <!-- <van-picker
        show-toolbar
        title="选择队长"
        value-key="name"
        @cancel="captainCancel"
        @confirm="captainConfirm"
      >
        <template #columns-top>
          <span v-for="(item,index) in team_employee_list" :key="index">
            {{item.name}}
          </span>
        </template>
      </van-picker> -->

      <div class="van-picker">
        <div class="van-hairline--top-bottom van-picker__toolbar">
          <div class="van-picker__cancel" @click="captainCancel">取消</div>
          <div class="van-picker__confirm" @click="captainConfirm(team_employee_list[picker_active])">确认</div>
        </div>
        <div class="van-picker__columns" style="height: 220px">
          <div class="van-picker-column"
                @scroll="change_picker_scroll"
                style="height: 220px;overflow-y: auto;">
            <ul class="transition: all 0ms ease 0s; transform: translate3d(0px, 88px, 0px)" style="line-height: 44px">
              <!-- "van-picker-column__item--selected":picker_active==index -->
              <!-- picker_active==index?"":"" -->
              <li :class='picker_active==index?"clickColor":""'
                  class="van-ellipsis van-picker-column__item"
                  style="height: 44px"
                  @click="change_picker(item,index)"
                  v-for="(item,index) in team_employee_list" :key="index">
                  <Wxopendata type="userName" :openid="item.name"></Wxopendata>
              </li>
            </ul>

          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>

import request from '@/utils/request'
import EmployeeSelector from '@/components/common/EmployeeSelector'
import Vue from 'vue'
import { Dialog, CellGroup, Toast } from 'vant'
Vue.use(Dialog).use(CellGroup).use(Toast)
export default {
  comments: {},
  props: {
    createInfo: {
      type: Object,
      default: {}
    },
    pkStatus: {
      type: String,
      default: ''
    }
  },
  // 数据
  data () {
    return {
      picker_active:1,
      get_id: this.$route.query.id,
      page: 1,
      teams_list: null,
      team_popup_type: 'add',
      show_team_popup: false,
      employee_list: [],
      team_employee_list: [],
      formData: {
        name: '',
        leader: {
          name: ''
        },
        members: []
      },
      popup_teams_name: '',
      show_employee_selector: false,
      selected: {},
      showCaptain: false,
      select_employee_name: null,
      pk_info: {}
    }
  },
  computed: {
    hasPermission () {
      const { createInfo } = this
      const { is_creator, id } = this.$store.getters.user_info
      return is_creator === 1 || id == createInfo.creatorId || createInfo.manages.has(id.toString())
    }
  },
  // 组件
  components: {
    EmployeeSelector
  },
  // 方法
  methods: {
    onOpenEmployee () {
      this.selected = {
        employee: this.team_employee_list,
        dept: []
      }
      this.show_employee_selector = true
    },
    // 查询团队列表
    get_teams_list (id, page) {
      let self = this
      request('get', '/api/integral/pk/teams', { pk_id: id, page: page, page_size: 100 }).then((res) => {
        if (res.data.code == '1') {
          self.teams_list = res.data.data.list.list
          self.$toast.clear()
        } else {
          self.$toast.clear()
          self.$toast(res.data.msg)
        }
      }).catch((e) => {
        self.$toast.clear()
      })
    },
    // 查询人员列表
    get_employee_list (id) {
      this.showLoading()
      request('get', '/api/integral/pk/members', { pk_id: id }).then((res) => {
        if (res.data.code == '1') {
          this.employee_list = res.data.data
        }
      }).finally(() => this.$toast.clear())
    },

    // 删除团队
    del_team (id, d) {
      Dialog.confirm({ title: '提示', message: '确定删除此项?' }).then(() => {
        this.showLoading()
        const data = { pk_id: id, team_id: d.id }
        request('delete', '/api/integral/pk/teams', data).then((res) => {
          if (res.data.code == 1) {
            this.$toast(res.data.msg)
            this.get_teams_list(this.get_id, 1)
          } else {
            this.$toast(res.data.msg)
          }
        }).catch((e) => {
          this.$toast(res.data.msg)
        }).finally(() => this.$toast.clear())
      }).catch(() => {
      })
    },
    // 新增团队
    add_team_btn () {
      this.team_popup_type = 'add'
      this.popup_teams_name = null
      this.select_employee_name = null
      this.formData.leader.name = null
      this.team_employee_list = []
      this.show_team_popup = true
    },
    // 修改团队按钮
    edit_team_btn (item) {
      this.team_popup_type = 'edit'
      this.formData = item
      this.get_team_employee_list(item)
      this.popup_teams_name = this.formData.name
      // let employee_arr = []
      // this.team_employee_list.forEach(v => {
      //   employee_arr.push(v.name)
      // })
      // this.select_employee_name = employee_arr.join(',')
      this.$nextTick(()=>{
        this.select_employee_name = this.team_employee_list
        this.show_team_popup = true
      })
    },
    checkTeamForm (action, done) {
      if (action === 'confirm') {
        var teamName = this.popup_teams_name
        var selectedEmployees = this.team_employee_list
        if (!teamName) {
          this.$notify({ type: 'danger', message: '团队名字不能为空' })
          done(false)
        } else if (!Array.isArray(selectedEmployees) || selectedEmployees.length === 0) {
          this.$notify({ type: 'danger', message: '团队成员至少要有一名' })
          done(false)
        } else if (!this.formData.leader.id) {
          this.$notify({ type: 'danger', message: '请选择队长' })
          done(false)
        } else {
          this.team_confirm(done)
        }
      } else {
        done()
      }
    },
    // 获取团队人员列表
    get_team_employee_list (item) {
      this.team_employee_list = []
      item.members.forEach(v => {
        this.employee_list.list.forEach(d => {
          if (v.id == d.id) {
            this.team_employee_list.push(d)
          }
        })
      })
    },
    // 加载
    showLoading () {
      this.$toast.loading({
        loadingType: 'spinner',
        message: '正在处理'
      })
    },
    // 修改团队
    team_confirm (done) {
      let self = this, team_member = []
      self.team_employee_list.forEach(v => {
        team_member.push(v.id)
      })
      self.showLoading()
      let data = {
        team: {
          pk_id: self.get_id,
          team_id: self.formData.id,
          team_name: self.popup_teams_name,
          team_member: team_member,
          team_leader: self.formData.leader.id
        }
      }
      if (self.team_popup_type == 'add') {
        data.team.team_id = '0'
      }
      request('post', '/api/integral/pk/teams', data).then((res) => {
        if (res.data.code == 1) {
          self.get_teams_list(self.get_id, self.page)

          self.$toast.clear()
          done(false)
        } else {
          done(false)
          self.$toast.clear()
          self.$toast({
            message: res.data.msg,
            duration: 1000
          })
        }
      }).finally(() => {
        self.show_team_popup = false
        self.$toast.clear()
      })
    },
    // 取消关闭弹窗
    team_cancel () {
      self.show_team_popup = false
    },
    // 打开弹窗
    open_captain () {
      this.team_employee_list.forEach((item,index)=>{
        if(item.name == this.formData.leader.name){
          this.picker_active = index
        }
      })
      this.showCaptain = true
    },
    // 选择队长
    captainConfirm (data) {
      this.formData.leader = data
      this.showCaptain = false
    },
    change_picker(item,index){
      this.picker_active=index;
    },
    change_picker_scroll(v){
      let scrollTop = v.srcElement.scrollTop;
      this.picker_active = Math.ceil(scrollTop/44)+1;//向上取整，并加上第一个空格
    },
    // 队长弹窗 取消
    captainCancel () {
      this.showCaptain = false
    },
    // 关闭选择部门弹窗
    move_cancel () {
      this.select_mode = false
    },
    // 选择人员 完成
    move_confirm (data) {
      this.team_employee_list = []
      if (data.employee.length) {
        let name_arr = []
        let captain_arr = []
        let hasCaptain = false
        for (let i = 0; i < data.employee.length; i++) {
          const employee = data.employee[i]
          name_arr.push(employee.name)
          this.team_employee_list.push(employee)
          if (hasCaptain === false && employee.id === this.formData.leader.id) {
            hasCaptain = true
          }
        }
        if (!hasCaptain) {
          this.formData.leader.id = false
          this.formData.leader.name = null
        }
        this.selected.employee = this.team_employee_list
        this.formData.leader = this.team_employee_list[0]
        // this.select_employee_name = name_arr.join(',')
        this.select_employee_name = data.employee
      } else {
        this.formData.leader.id = false
        this.formData.leader.name = null
        this.select_employee_name = null
      }
      this.move_cancel()
    },
    get_pk_info () {
      let self = this
      let data = {
        pk_id: self.$route.query.id
      }
      request('get', '/api/integral/pk/info', data).then((res) => {
        if (res.data.code == 1) {
          self.pk_info = res.data.data
        } else {
          self.$toast(res.data.msg)
        }
      })
    }
  },
  // 生命周期 --- 创建完成
  created () {
    // created 创建完毕状态
    this.get_employee_list(this.get_id)
    this.get_teams_list(this.get_id, this.page)
    this.get_pk_info()
  }
}
</script>
<style scoped lang="less">
.pk-team__wrap {
  position: relative;
  margin-top: 0.16rem;
  font-size: 0.32rem;
  color: #333;
  background: #fff;

  & .pk-team__headedr {
    position: relative;
    display: flex;
    align-items: center;
    flex-direction: row;
    &:after {
      position: absolute;
      box-sizing: border-box;
      content: ' ';
      pointer-events: none;
      right: 0;
      bottom: 0;
      left: 0;
      border-bottom: 1px solid #ebedf0;
      transform: scaleY(0.5);
    }
    & .pk-team__title {
      display: flex;
      flex: 1;
      padding: 0.24rem 0.32rem;
    }
    & .pk-team__toolbar {
      position: relative;
      padding-right: 0.32rem;
    }
  }

  & .team-member__item {
    display: flex;
    position: relative;
    padding: 0 0.32rem;
    height: 0.88rem;
    align-items: center;
    touch-action: none;

    &:not(:last-child):after {
      position: absolute;
      box-sizing: border-box;
      content: ' ';
      pointer-events: none;
      right: 0;
      bottom: 0;
      left: 0.32rem;
      border-bottom: 1px solid #ebedf0;
      transform: scaleY(0.5);
    }
  }

  & .team-member__name {
    position: relative;
    padding-left: 0.2rem;
  }
}

.pk_team_scroller {
  height: calc(100% - 1rem);
}
.clickColor{
  background-color: #f3f3f3;
  transition: .5s;
  border: #ececec;
}
</style>
