<template>
  <van-popup :duration="0.2" :overlay="false" class="employee_selector_popup" v-model="visible_" position="bottom" :style="'height:'+com_height">
    <van-nav-bar :title="dept_name" left-text="取消" @click-left="close" right-text="确定" @click-right="confirm"></van-nav-bar>
    <van-search v-model="keyword" placeholder="请输入搜索关键词" />
    <div class="dept_path" v-show="pid_list_arr.length > 0">
      <a href="javascript:void(0);" @click="back_by_index(0)">全部</a>
      <a v-for="(item, index) in pid_list_arr" :key="index" href="javascript:void(0);" @click="back_by_index(index + 1)"> <van-icon name="arrow" /> {{item.name}}</a>
    </div>
    <div class="body_com" :class="{show_dept_path:pid_list_arr.length > 0}">
      <scroller :on-refresh="get_category_list">
        <van-cell-group>
        <van-cell :is-link="!can_select_category" v-for="(item,index) in category_list" :key="index" :title="item.name" v-show="item.pid == pid && item.name.indexOf(keyword) >= 0 && category_not_select.indexOf(item.id) < 0" class="employee_cell" @click="select_dept(item)">
          <template slot="icon">
            <van-checkbox v-if="can_select_category" v-model="item.checked"></van-checkbox>
            <img v-if="can_select_category" src="static/images/e66f.jpg" class="employee_cell_head_img"/>
          </template>
          <template slot="right-icon" v-if="can_select_category">
            <a href="javascript:void(0);" class="child_btn" @click.stop="show_child(item)">
              | 下级
            </a>
          </template>
        </van-cell>
        </van-cell-group>
        <van-cell-group>
        <van-cell  v-if="can_select_rule" v-for="(item,index) in list" :key="index" :title="types_list[item.pt_id]+'（'+(item.range_type == 1 ? item.min_point : item.min_point+'—'+item.max_point)+'）'" class="employee_cell rule_list_item" @click="select_employee(item)" v-show="rule_not_select.indexOf(item.id) < 0" :label="item.remark">
          <template slot="icon">
            <van-checkbox v-model="item.checked" style="margin-right:0.16rem;"></van-checkbox>
          </template>
        </van-cell>
        </van-cell-group>


        <slot name="append"></slot>
      </scroller>
    </div>
    <div class="bottom_menu" style="display: none;">
      <div class="selected_box" ref="selected_box">
        <ul :style="'width:'+selected_box_width">
          <li v-for="(item,index) in rule_selected_list"><img @click="employee_cancel(item)" :src="item.img_url"/><div class="name_mini">{{item.name}}</div></li>
          <li v-for="(item,index) in category_selected_list"><img @click="dept_cancel(item)" src="static/images/e66f.jpg"/><div class="name_mini">{{item.name}}</div></li>
        </ul>
      </div>
      <div class="selected_btn" ref="selected_btn"><van-button ref="selected_button" style="height: 0.7rem; line-height: 0.7rem; margin-top:0.1rem;" type="primary" @click="confirm">确定<template v-show="max > 0" v-if="multi"></template></van-button></div>
    </div>
  </van-popup>
</template>

<script>
  import Vue from 'vue';
  import { ActionSheet, Popup, Checkbox } from 'vant';
  Vue.use(Popup);
  Vue.use(Checkbox);
  Vue.use(ActionSheet);
  import { Search } from 'vant';

  Vue.use(Search);
  import request from '@/utils/request'
  export default {
    props:{
      append_body: {
        type: Boolean,
        default: false
      },
      visible: {
        type: Boolean,
        default: false
      },
      can_select_category: {
        type: Boolean,
        default: true
      },
      can_select_rule: {
        type: Boolean,
        default: true
      },
      rule_not_select: {
        type: Array,
        default: () => {return []}
      },
      category_not_select: {
        type: Array,
        default: () => {return []}
      },
      selected:{
        type: Object,
        default: () => {
          return {rule:[], cate: []}
        }
      },
      multi:{
        type: Boolean,
        default: true
      },
      cate_multi:{
        type: Boolean,
        default: true
      },
      rule_list:{
        type: Array,
        default: () => {return []}
      },
      close_clear_data:{
        type: Boolean,
        default: true
      },
      max: {
        type: Number,
        default: 0
      },
      cycle_type:{
        type: Number,
        default: 1
      },
      pt_code: {
        type: String,
        default: ''
      }
    },
    name: "RuleCategorySelector",
    data () {
      let selected = JSON.parse(JSON.stringify(this.selected))
      return {
        types_list: {},
        rule_selected_list:selected.rule,
        category_selected_list:selected.cate,
        rule_selected:[],
        category_selected:[],
        com_height:'100%',
        company_info:{},
        actions_show:false,
        dept_name: '',
        dept_id: 0,
        list: [],
        category_list: [],
        keyword: '',
        owner_id: 0,
        user_info: this.$store.getters.user_info,
        pid: 0,
        pid_list:[],
        selected_box_width: '0',
        pid_list_arr: [],
        item_list: [],
        cur_item_list: [],
        rule_tree: [],
        visible_: false
      }
    },
    watch: {
      pid(val){
        if(val == 0){
          this.list = []
          for(let i in this.item_list){
            for(let k in this.item_list[i]){
              this.list.push(this.item_list[i][k])
            }
          }
        }else{
          this.category_list = []
          this.parse_tree(this.rule_tree, val)
          this.list = this.cur_item_list
        }
        for(let i in this.list){
          this.list[i]['checked'] = false
          if(this.rule_selected.indexOf(this.list[i].id) >= 0){
            this.list[i]['checked'] = true
          }
        }
      },
      max(val){
        this.set_button_width()
      },
      selected(val){
        let selected = JSON.parse(JSON.stringify(val))
        this.rule_selected = []
        this.category_selected = []
        this.rule_selected_list = selected.rule
        this.category_selected_list = selected.cate
        for(let i in selected.rule){
          this.rule_selected.push(selected.rule[i].id)
        }
        for(let i in selected.cate){
          this.category_selected.push(selected.cate[i].id)
        }
        if(this.cate_multi == false && this.category_selected_list.length > 0){
          this.parse_tree(this.rule_tree, this.category_selected_list[0].id)
        }
        this.$emit('get_items', this.cur_item_list)
        this.set_button_width()
      },
      visible(val){
        this.visible_ = JSON.parse(JSON.stringify(val))
        if(val){
          this.get_category_list(function () {

          })

          for(let i in this.list){
            this.list[i]['checked'] = false
            if(this.rule_selected.indexOf(this.list[i].id) >= 0){
              this.list[i]['checked'] = true
            }
          }
        }
        this.set_button_width()
      },
      rule_selected_list(){
        let l = this.rule_selected_list.length + this.category_selected_list.length
        let width = 0.9*l;
        this.selected_box_width = width + 'rem'
        this.set_button_width()
      },
      category_selected_list(){
        let l = this.rule_selected_list.length + this.category_selected_list.length
        let width = 0.9*l;
        this.selected_box_width = width + 'rem'
        this.set_button_width()
      },
      keyword(){

      }
    },
    beforeDestroy() {
      if (this.append_body) {
        document.body.removeChild(this.$el)
      }
      this.close();
    },
    methods: {
      get_item_list(trees){
        if(this.item_list['rule_'+trees.id]){
          for(let i in this.item_list['rule_'+trees.id]){
            this.cur_item_list.push(this.item_list['rule_'+trees.id][i])
          }
        }
        for(let i in trees.child){
          this.get_item_list(trees.child[i])
        }
      },
      get_point_types() {
        let self = this
        request('get','/api/integral/types').then(res => {
          if (res.data.code == 1) {
            for (let i in res.data.data.list) {
              self.types_list[res.data.data.list[i].id] = res.data.data.list[i].name
            }
          }
        })
      },
      set_button_width(){
        this.$nextTick(() => {
          if(this.$refs['selected_button']){
            this.$refs['selected_btn'].style.width = (this.$refs['selected_button'].offsetWidth+10)+'px'
            this.$refs['selected_box'].style.width = (window.innerWidth - (this.$refs['selected_button'].offsetWidth+10))+'px'
          }
        })
      },
      back(){
        this.pid = this.pid_list[this.pid_list.length - 1]
        this.pid_list.splice(this.pid_list.length - 1)
        this.pid_list_arr.splice(this.pid_list_arr.length - 1)
      },
      back_by_index(index){

        if(index == this.pid_list.length){
          return false
        }
        this.pid = this.pid_list[index]
        this.pid_list.splice(index, 100)
        this.pid_list_arr.splice(index, 100)
      },
      show_child(item){
        this.pid_list.push(this.pid)
        this.pid_list_arr.push(item)
        this.pid = item.id
      },
      employee_cancel(item){
        this.rule_selected.splice(this.rule_selected.indexOf(item.id), 1)
        let delete_index = -1
        for(let i in this.rule_selected_list){
          if(this.rule_selected.indexOf(this.rule_selected_list[i].id) < 0){
            delete_index = i
          }
        }
        if(delete_index >= 0){
          this.rule_selected_list.splice(delete_index, 1)
          for(let i in this.list){
            if(this.list[i].id == item.id){
              this.$set(this.list[i], 'checked', false)
            }
          }
        }
      },
      dept_cancel(item){
        this.category_selected.splice(this.category_selected.indexOf(item.id), 1)
        let delete_index = -1
        for(let i in this.category_selected_list){
          if(this.category_selected.indexOf(this.category_selected_list[i].id) < 0){
            delete_index = i
          }
        }
        if(delete_index >= 0){
          this.category_selected_list.splice(delete_index, 1)
          for(let i in this.category_list){
            if(this.category_list[i].id == item.id){
              this.$set(this.category_list[i], 'checked', false)
            }
          }
        }
      },
      select_employee(item){
        if(item.checked){
          item.checked = false
          this.employee_cancel(item)
        }else{
          if(!this.multi){
            this.rule_selected = []
            this.rule_selected_list = []
            for(let i in this.list){
              this.$set(this.list[i], 'checked', false)
            }
          }
          if(this.max > 0 && this.rule_selected.length == this.max && this.multi){
            this.$toast('最多只能选择'+this.max+'条规则')
            return false
          }
          this.rule_selected.push(item.id)
          this.rule_selected_list.push(item)
          item.checked = true
        }
      },
      select_dept(item){
        if(!this.can_select_category){
          this.show_child(item)
          return false
        }
        if(item.checked){
          item.checked = false
          this.dept_cancel(item)
        }else{
          if(!this.cate_multi) {
            this.category_selected = []
            this.category_selected_list = []
            for (let i in this.category_list) {
              this.$set(this.category_list[i], 'checked', false)
            }
          }
          this.category_selected.push(item.id)
          this.category_selected_list.push({id:item.id,name:item.name})
          item.checked = true
        }

      },
      close(){
        //this.visible = false
        this.$emit('update:visible', false)
        this.$emit('cancel')
        if(this.close_clear_data){
          this.rule_selected = []
          this.rule_selected_list = []
          this.category_selected = []
          this.category_selected_list = []
          for(let i in this.list){
            this.$set(this.list[i], 'checked', false)
          }
          for (let i in this.category_list) {
            this.$set(this.category_list[i], 'checked', false)
          }
        }

      },
      confirm(){
        this.$emit('confirm', {
          rule: this.rule_selected_list,
          cate: this.category_selected_list
        })
        if(this.cate_multi == false && this.category_selected_list.length > 0){
          this.parse_tree(this.rule_tree, this.category_selected_list[0].id)
        }
        this.$emit('get_items', this.cur_item_list)
        this.close()
      },
      parse_tree(trees, rule_id){
        for(let i in trees){
          if(rule_id == trees[i].id){
            this.cur_item_list = []
            this.get_item_list(trees[i])
          }
          this.category_list.push(trees[i])
          this.parse_tree(trees[i].child, rule_id)
        }
      },
      get_category_list(done){
        this.category_list = []
        let params = {}

        if(this.pt_code != '' && this.point_type_map[this.pt_code]){
          params['pt_id'] = this.point_type_map[this.pt_code]
        }
        if (this.cycle_type != '') {
          params['cycle_type'] = this.cycle_type
        }
        request('get','/api/integral/rule/trees',params).then((res) => {
          this.category_list = []
          this.item_list = res.data.data.item_list
          this.rule_tree = res.data.data.rule_tree
          this.parse_tree(res.data.data.rule_tree, this.pid)
          for(let i in this.category_list){
            this.category_list[i]['checked'] = false
            if(this.category_selected.indexOf(this.category_list[i].id) >= 0){
              this.category_list[i]['checked'] = true
              if(this.cate_multi == false){
                this.parse_tree(this.rule_tree, this.category_list[i].id)
              }
              this.$emit('get_items', this.cur_item_list)
              this.category_list = []
              this.parse_tree(res.data.data.rule_tree, this.pid)
            }
          }

          if(this.pid == 0){
            this.list = []
            for(let i in this.item_list){
              for(let k in this.item_list[i]){
                this.list.push(this.item_list[i][k])
              }
            }
          }else{
            this.list = this.cur_item_list
          }
          for(let i in this.list){
            this.list[i]['checked'] = false
            if(this.rule_selected.indexOf(this.list[i].id) >= 0){
              this.list[i]['checked'] = true
            }
          }


          done()
          this.$toast.clear()
        }).catch((e) => {
          done()
          this.$toast.clear()
        })
      },
      get_user_list (done) {
        if(this.rule_list.length > 0){
          this.list = this.rule_list
          done()
          return false
        }
        this.list = []
        request('get','/api/employee/index',{dept_id: this.pid, keywords:this.keyword, page: 0, page_size: 2000}).then((res) => {
          for(let i in res.data.data.list){
            res.data.data.list[i]['checked'] = false
            if(this.rule_selected.indexOf(res.data.data.list[i].id) >= 0){
              res.data.data.list[i]['checked'] = true
            }
            if(res.data.data.list[i].img_url == ''){
              res.data.data.list[i].img_url = 'static/images/logo.png'
            }
          }
          this.list = res.data.data.list
          done()
          this.$toast.clear()
        }).catch((e) => {
          done()
          this.$toast.clear()
        })
      }
    },
    created () {
      if(document.documentElement.style.height){
        this.com_height = document.documentElement.style.height
      }
      this.get_category_list(function () {

      })
      this.get_point_types()
      this.$nextTick(() => {
        if(this.append_body){
          document.body.appendChild(this.$el)
        }
      })
    }
  }
</script>

<style scoped>
  .body_com{height: calc(100% - 2rem); position: relative;}
  .body_com.show_dept_path{height: calc(100% - 2.6rem);}
  .bottom_menu{
    height: 0.8rem; text-align: center; line-height: 0.8rem; position: relative; display: table;}
  .bottom_menu:before{content:" "; height: 1px;/*no*/  background-color: #eee;width:100%; top:0;left:0;position: absolute;}
  .bottom_menu a{color: #1989fa; font-size:0.32rem;}

  .employee_cell_head_img {
    width: 0.8rem;
    height: 0.8rem;
    margin-left:0.16rem;
    -webkit-border-radius: 0.1rem;
    -moz-border-radius: 0.1rem;
    border-radius: 0.1rem;
    margin-right: 0.15rem;
  }
  .employee_cell a:active{
    opacity:0.5;
  }

  .employee_cell {
    padding: 0.16rem 0.32rem;
  }
  .employee_cell .Points_classification{
    width:0.8rem;
    height:0.8rem;
    margin:0 0.16rem;
  }
  .employee_cell .van-checkbox{
    overflow: visible;
  }
  .employee_cell .van-cell__title {
    line-height: 0.8rem;
  }
  .rule_list_item.employee_cell .van-cell__title {
     line-height: 1;
   }
  .employee_cell .van-cell__right-icon{margin-top:0.2rem;}
  .employee_cell .van-icon{color:#999; margin-top:0.2rem;}

  .employee_selector_popup{
    background-color: rgb(245, 245, 245);
    height: 100%;
  }
  .child_btn{color:#1989fa; display: block; height:1.14rem;position: absolute;right:0; top:0; padding:0 0.32rem;line-height: 1.1rem;font-size:0.28rem;}
  .bottom_menu{ width:100%; height: 0.9rem;}
  .selected_box,.selected_btn{vertical-align: top; text-align: left;}
  .selected_btn{text-align: center; float:right;}

  .selected_box{overflow-x: scroll; width:5rem; float:left;min-height: 0.5rem;}
  .selected_box ul,.selected_box li{margin:0; padding:0; text-align: left;}
  .selected_box li{display: block; text-align: left; float: left; position: relative;}
  .selected_box li img{width:0.8rem; vertical-align: top;
    height: 0.8rem; padding:0.05rem;
    -webkit-border-radius: 0.1rem;
    -moz-border-radius: 0.1rem;
    border-radius: 0.1rem;}
  .name_mini{font-size:0.2rem; position: absolute; bottom:0.05rem;left:0.05rem;right:0.05rem;padding:0.02rem 0; text-align: center; background-color: rgba(0,0,0,0.4); height: 0.2rem; color:#fff; line-height: 0.2rem;}
  .dept_path a{color:#238dfa;font-size:0.28rem;}
  .dept_path a:nth-last-child(1){
    color: #999;
  }
  .dept_path a *{vertical-align: middle;}
  .dept_path{height: 0.6rem; position: relative; font-size:0.32rem; line-height: 0.4rem; overflow-x: scroll; padding:0 0.32rem; background-color: #fff;}
  .dept_path:after{content: " "; bottom:0; left:0; right:0; background-color: #ccc; height: 1px; position: absolute; transform: scaleY(0.5)}
  /deep/ .van-hairline--top-bottom:after{border:none;}
  /deep/ .van-hairline-unset--top-bottom:after{border:none;}
</style>

