<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="body_com">
      <scroller style="right:5.5rem;width:2rem;" class="selector-leftt _v-container">
        <van-collapse v-model="left_active" accordion>
          <van-collapse-item :is-link="false" :name="item.id" v-for="(item,index) in category_list" :key="index" :title="item.name" v-show="item.pid == 0" :class="{on: left_active, no_child: item.child.length == 0}">
            <ul v-if="item.child.length > 0">
              <li v-for="(child_item,child_index) in item.child" :key="child_index">
                <a @click.stop="show_child(child_item)" href="javascript:void(0);" :class="{on: pid == child_item.id}">{{child_item.name}}</a>
              </li>
            </ul>
          </van-collapse-item>
        </van-collapse>
      </scroller>
      <scroller :on-refresh="get_category_list" style="left:2rem; right:0; width:auto;" class="selector-right _v-container">
        <van-cell-group style="margin-top:0;">
        <van-cell :is-link="!can_select_category" v-for="(item,index) in category_list" :key="index" :title="item.name" v-show="pid > 0 && 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>
        <div style="height: 0.16rem;"></div>
        <van-cell-group style="margin-top:0;">
        <van-cell  v-if="can_select_rule" v-for="(item,index) in list" :key="index" :title="item.remark" class="employee_cell rule_list_item" @click="select_employee(item)" v-show="rule_not_select.indexOf(item.id) < 0  && item.remark.indexOf(keyword) >= 0">
          <template slot="label">
            <span class="record color_red" v-if="item.min_point <= 0">{{(item.range_type == 1 ? item.min_point : item.min_point+'～'+item.max_point)}}</span>
            <span class="record color_green" v-if="item.min_point > 0">+ {{(item.range_type == 1 ? item.min_point : item.min_point+'～'+item.max_point)}}</span>
            <span class="type">{{types_list[item.pt_id]}}</span>
          </template>
          <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>
      <noData v-model="list" class="nodata" ></noData>
    </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, Collapse, CollapseItem, Search } from 'vant'

import request from '@/utils/request'
Vue.use(Popup)
Vue.use(Checkbox)
Vue.use(CollapseItem)
Vue.use(Collapse)
Vue.use(ActionSheet)

Vue.use(Search)
export default {
  props: {
    pt_code: {
      type: String,
      default: ''
    },
    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
    }
  },
  name: 'RuleCategorySelector',
  data () {
    let selected = JSON.parse(JSON.stringify(this.selected))
    return {
      left_active: 0,
      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,
      point_type_map: {}
    }
  },
  beforeDestroy () {
    if (this.append_body) {
      document.body.removeChild(this.$el)
    }
    this.close()
  },
  watch: {
    left_active (val) {
      if (val * 1 == 0) {
        this.back_by_index(0)
      } else {
        let item = null
        for (let i in this.category_list) {
          if (this.category_list[i].id == val) {
            item = this.category_list[i]
            // if (this.category_list[i].child.length > 0) {
            //   item = this.category_list[i].child[0]
            // }
          }
        }
        this.show_child(item)
      }
    },
    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)
      }
      this.set_button_width()
    },
    visible (val) {
      this.visible_ = JSON.parse(JSON.stringify(val))
      if (val) {
        setTimeout(() => {
          this.get_category_list(function () {

          })
        }, 200)
        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 () {

    }
  },
  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
      for (let i in this.$store.getters.point_types) {
        self.types_list[this.$store.getters.point_types[i].id] = this.$store.getters.point_types[i].name
        self.point_type_map[this.$store.getters.point_types[i].code] = this.$store.getters.point_types[i].id
      }
    },
    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_left (item) {
      if (this.pid > 0) {
        this.back_by_index(0)
      }

      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
      }
    },
    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
      })
      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) {
      let params = {}

      if (this.pt_code != '' && this.point_type_map[this.pt_code]) {
        params['pt_id'] = this.point_type_map[this.pt_code]
      }
      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.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
    }
    setTimeout(() => {
      this.get_category_list(function () {

      })
    }, 200)
    this.get_point_types()
  }
}
</script>

<style scoped>
  .body_com{border-top:1px solid #eee;}
  .body_com.show_dept_path{border-top:none;}
  .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.24rem;
  }

  .employee_cell {
    padding: 0.16rem 0.32rem;
  }
  .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: 0.32rem;
   }
  .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;}
  .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;}
  .selector-left{width:2rem !important; background-color: #f5f5f5;}
  .selector-left .van-cell{background-color: #f5f5f5;font-weight:bold;}
  .selector-left .employee_cell {padding:0.08rem; padding-left:0;transition:0.35s ease-in-out;}
  .selector-left .employee_cell.on:before{content:" ";width:0.04rem;height:0.32rem;background:#26A2FF;margin:0.25rem 0.15rem 0;transition:0.35s ease-in-out;}
  .selector-left .employee_cell.on {background-color: #fff;padding-left:0rem;color:#238dfa;transition:0.35s ease-in-out;}
  .selector-left .employee_cell.on::before{border-radius: 0.08rem;width:0.08rem;height:0.08rem;margin-top:0.34rem;transition:0.35s ease-in-out;}
  .selector-left .van-cell:not(:last-child):after {left: 0;display:none;}
  .selector-right{background-color: #fff;}
  .selector-left ._scroller-bar{width:0.02rem;background:#238dfa;}
  .selector-right .rule_list_item .van-cell__title .van-cell__label{padding-top:0.12rem;}
  .no_child /deep/ .van-collapse-item__content{display: none;}
  /deep/ .van-collapse-item__title--expanded:before{content: " "; width:0.06rem; height: 0.3rem; background: #26A2FF; left:0; position: absolute; top:50%; margin-top:-0.16rem; left:0.1rem;}
  /deep/ .van-collapse-item__title--expanded:not(:last-child):after{left:0;}
  .van-collapse-item__content a{color:#606266; display: block; line-height:0.9rem;border-bottom:1px #f8f8f8 solid; position: relative; padding-left:0.16rem;}
  /deep/ .van-collapse-item__content{padding:0.16rem 0.16rem;}
  .van-collapse-item__content a.on{color:#26A2FF;}
  .van-collapse-item__content a.on:before{content: " "; width:0.06rem; height:0.06rem; background: #26A2FF; position: absolute; border-radius: 0.4rem; top:50%; margin-top:-0.03rem; left:0.05rem;}
  .van-collapse-item__content a:before{content: " "; width:0.06rem; height:0.06rem; background: #606266; position: absolute; border-radius: 0.4rem; top:50%; margin-top:-0.03rem; left:0.05rem;}
  /deep/ .van-collapse-item__title{ background:transparent;}
  /deep/ .rule_list_item .van-cell__title span{line-height: 1.5; font-weight: bold;}
  /deep/ .rule_list_item .van-cell__title .van-cell__label span{line-height: 1.5; font-weight: normal;}
  .selector-right{width:auto !important;}
  .nodata /deep/ .c{
    left: 65%;
  }
</style>
