<template>
  <div style=" background-color: #fff;">
    <el-row :gutter="15" style="border:1px solid #eee;">
      <el-col :span="24" style="margin-bottom:0; border-bottom:1px solid #eee;">
        <div style="margin-bottom:0; padding:15px;" class="inline-block-btn-list">
          <div class="gap-right-8" style="display:inline-block; width:100%; margin-bottom:0;">
            <el-input
              placeholder="输入关键词查找"
              ref="search-bar"
              v-model="filter.keywords"
              class="input-with-select"
              @keyup.enter.native="onFilterChanged"
            >
              <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
            </el-input>
          </div>
        </div>
      </el-col>

      <el-col :span="6" style="margin-bottom:0;">
        <div style="padding:15px; padding-left:0; padding-right:0;">
          <el-scrollbar
            wrap-class="column-wrapper scrollable-items-container check-item-box dept_tree"
            :native="false"
            style="height: 350px;"
          >
            <a
              @click="handleNodeClick({value:0})"
              v-show="profile.manager_type > 2"
              :class="{on:filter.dept_id.length == 0}"
              style="display: block; padding:7px;"
            >
            <img src="static/images/two.png" style="width: 16px;height: 16px;vertical-align: text-bottom;margin-right: 8px;" />
            所有部门
            </a>
            <!-- <el-tree
              ref="dept_tree_com"
              highlight-current
              :default-expand-all="true"
              :expand-on-click-node="false"
              :data="deptTree"
              img="static/images/one.jpg"
              @node-click="handleNodeClick"
            ></el-tree> -->


            <el-tree :data="deptTree"   highlight-current  :expand-on-click-node="false"   node-key="id" default-expand-all  @node-click="handleNodeClick">
              <span class="custom-tree-node" slot-scope="{ node, data }">
               
                  <span >
                      <img v-if="data.children.length!=0" src="static/images/one.png" style="width: 16px;height: 216x;vertical-align: text-bottom;margin-right: 8px;" />
                     
                      {{data.label}}
                  </span>              
              </span>
              </el-tree>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="9" style="border-left:1px solid #eee; margin-bottom:0; padding-right:0;">
        <div style="padding:15px; padding-right:0;">
          <el-scrollbar
            wrap-class="column-wrapper scrollable-items-container dept_tree"
            :native="false"
            style="height: 350px;"
          >
            <div style="padding-right:15px;">
              <el-table
                v-loading="loading"
                ref="multipleTable"
                :data="tableData"
                :border="false"
                tooltip-effect="dark"
                @row-click="rowClick"
                @selection-change="handleSelectionChange"
                @select-all="select_all"
                style="width: 100%"
              >
                <el-table-column type="selection" width="42" :selectable="isSelectable"></el-table-column>

                <el-table-column prop="name" label="选择人员">
                  <template slot-scope="scope">
                    <div class="rank_head" style="cursor: pointer;">
                      <img
                        v-if="scope.row.img_url != null"
                        v-bind:src="scope.row.img_url"
                        width="42px"ss
                        height="42px"
                      >
                      <img
                        v-if="scope.row.img_url == null"
                        src="static/images/head_default.png"
                        width="42px"
                        height="42px"
                      >
                      
                       <span>
                         {{scope.row.name}}
                       </span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-scrollbar>
        </div>
      </el-col>

      <el-col :span="9" style="border-left:1px solid #eee; margin-bottom:0; padding-right:0;">
        <div style="padding:15px; padding-right:0;">
          <el-scrollbar
            wrap-class="column-wrapper scrollable-items-container check-item-box dept_tree"
            :native="false"
            style="height: 350px;"
          >
            <div style="padding-right:15px;">
              <el-table
                @header-click="clearEmployee"
                :data="multipleSelection"
                :border="false"
                tooltip-effect="dark"
                style="width: 100%"
              >
                <el-table-column prop="name" :label="'已选择人员（'+(multipleSelection.length)+'人）'">
                  <template slot-scope="scope">
                    <div class="rank_head" style="cursor: pointer;">
                      <img
                        v-if="scope.row.img_url != null"
                        v-bind:src="scope.row.img_url"
                        width="42px"
                        height="42px"
                      >
                      <img
                        v-if="scope.row.img_url == null"
                        src="static/images/head_default.png"
                        width="42px"
                        height="42px"
                      >
                     

                        {{scope.row.name}}
                      
                      
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  label="清空"
                  width="50"
                  column-key="clear"
                  label-class-name="clearEmployeeBtn"
                >
                  <template slot-scope="scope">
                    <div class="rank_head" style="cursor: pointer; text-align: center;">
                      <a
                        @click="removeEmployee(scope.row.id)"
                        class="el-icon-circle-close"
                        style="color:#ff7d79;"
                      ></a>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-scrollbar>
        </div>
      </el-col>

      <el-col :span="24" style="border-top:1px solid #eee; margin-bottom:0;">
        <el-pagination
          background
          style="margin-top:0;"
          :page-sizes="[10, 20, 50, 100]"
          layout="sizes, prev, pager, next"
          @size-change="handleSizeChange"
          :page-size="pageLimit"
          :total="totalCount"
          :current-page.sync="currentPage"
          @current-change="changePage"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  // multipleSelectionId
  props: {
    employeeSelectorIds: {
      type: Array,
      default: () => {return []}
    },
    include_admin: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    tableData(val) {
      this.$nextTick(() => {
        this.pageSelectedId = []
        val.forEach(item => {
          if (this.employeeSelectorIds.indexOf(item.id) >= 0) {
            this.$refs['multipleTable'].toggleRowSelection(item, true)
            this.pageSelectedId.push(item.id)
          }
        })
      })
    },
    employeeSelectorIds(val) {
      this.$nextTick(() => {
        if (!this.tableData) { return }
        this.pageSelectedId = []
        this.tableData.forEach(item => {
          this.$refs['multipleTable'].toggleRowSelection(item, false)
          if (val.indexOf(item.id) >= 0) {
            this.$refs['multipleTable'].toggleRowSelection(item, true)
            this.pageSelectedId.push(item.id)
          }
        })
      })
    }
  },
  data() {
    return {
      loading: false,
      profile: this.$store.getters.user_info,
      accessEnabled: false,
      dialogTableVisible: false,
      filter: {
        dept_id: [],
        status: 1,
        keywords: ''
      },
      totalCount: 0,
      pageLimit: 6,
      currentPage: 1,
      tableData: null,
      multipleSelection: [],
      multipleSelectionId: [],
      multipleSelectionJson: {},

      pageSelectedId: [],
      dialogExcelVisible: false,
      deptTree: [],
      creatorId: '',
      department_list: []
    }
  },
  methods: {
     clearChild(column, event) {

      const self = this
      if (column == 'clear') {
        console.log("jinlail")
        for (const i in this.tableData) {
          self.$refs['multipleTable'].toggleRowSelection(
            self.tableData[i],
            false
          )
        }
        this.multipleSelectionId = []
        this.multipleSelectionJson = {}
        this.multipleSelection = []
        this.pageSelectedId = []
      }
    },
    clearEmployee(column, event) {

      const self = this
      if (column.columnKey == 'clear') {
        console.log("jinlail")
        for (const i in this.tableData) {
          self.$refs['multipleTable'].toggleRowSelection(
            self.tableData[i],
            false
          )
        }
        this.multipleSelectionId = []
        this.multipleSelectionJson = {}
        this.multipleSelection = []
        this.pageSelectedId = []
      }
    },

    removeEmployee(id) {
      console.log("kkkkkkkkkkkkkkkkkkkkkkk")
      let self = this
      const multipleSelectionId = []
      const multipleSelectionJson = {}
      const multipleSelection = []
      const pageSelectedId = []
      for (const i in this.tableData) {
        if (this.tableData[i].id == id) {
          this.$refs['multipleTable'].toggleRowSelection(
            this.tableData[i],
            false
          )
        }
      }
      for (const i in this.multipleSelection) {
        if (this.multipleSelection[i].id != id) {
          multipleSelection.push(this.multipleSelection[i])
          multipleSelectionJson[
            this.multipleSelection[i].id
          ] = this.multipleSelection[i]
          multipleSelectionId.push(this.multipleSelection[i].id)
        }
      }

      this.multipleSelectionId = multipleSelectionId
      this.multipleSelectionJson = multipleSelectionJson
      this.multipleSelection = multipleSelection


      self.$nextTick(() => {
        self.$emit('check', self.multipleSelection)
        // self.$parent.$parent.$parent.$parent.set_target_ids(self.multipleSelection)
      })

    },

    handleNodeClick(data) {
      if (data.value == 0) {
        this.loadBaseData()
        this.filter.dept_id = []
      } else {
        this.filter.dept_id = [data.value]
      }
      this.onFilterChanged()
    },
    handleSizeChange(val) {
      this.pageLimit = val
      this.onFilterChanged()
    },
    onFilterChanged: function() {
      this.currentPage = 1
      this.loadEmployeeList()
    },
    toggleSelection: function(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    select_all(all) {
      const ids = []

      for (const i in all) {
        ids.push(all[i].id)
      }
    },
    handleSelectionChange: function(val) {
      // console.log(this.multipleSelectionId)
      const ids = []
      for (const i in val) {
        ids.push(val[i].id)
      }
      for (const i in val) {
        if (this.multipleSelectionId.indexOf(val[i].id) < 0) {
          this.multipleSelectionId.push(val[i].id)
          this.multipleSelectionJson[val[i].id] = val[i]
          this.multipleSelection.push(val[i])
        }
        if (this.pageSelectedId.indexOf(val[i].id) < 0) {
          this.pageSelectedId.push(val[i].id)
        }
      }
      const ids_cancel = []
      if (this.pageSelectedId.length > ids.length) {
        // 之前被选择的数量比现在的数量多，说明有一些被取消了选择
        // 求出这些被取消的选择id

        for (const i in this.pageSelectedId) {
          if (ids.indexOf(this.pageSelectedId[i]) < 0) {
            ids_cancel.push(this.pageSelectedId[i])
          }
        }
        this.pageSelectedId = ids
      }

      if (ids_cancel.length > 0) {
        const multipleSelectionId = []
        const multipleSelection = []
        const multipleSelectionJson = {}

        for (const i in this.multipleSelectionId) {
          if (ids_cancel.indexOf(this.multipleSelectionId[i]) < 0) {
            multipleSelectionId.push(this.multipleSelectionId[i])
          }
        }
        this.multipleSelectionId = multipleSelectionId

        for (const i in this.multipleSelection) {
          if (ids_cancel.indexOf(this.multipleSelection[i].id) < 0) {
            multipleSelection.push(this.multipleSelection[i])
          }
        }
        this.multipleSelection = multipleSelection

        for (const i in this.multipleSelection) {
          multipleSelectionJson[i] = this.multipleSelection[i]
        }
        this.multipleSelectionJson = multipleSelectionJson
      }

      const self = this
      self.$nextTick(() => {
        self.$emit('check', self.multipleSelection)
        // self.$parent.$parent.$parent.$parent.set_target_ids(self.multipleSelection)
      })
    },
    rowClick(row, event, column) {
      this.$refs['multipleTable'].toggleRowSelection(row)
    },
    isSelectable: function(row, index) {
      return true
    },
    toSexName: function(row, column, cellValue) {
      return cellValue == '1' ? '女' : '男'
    },
    dateFormatter: function(row, column, cellValue) {
      return this.$moment(cellValue * 1000).format('YYYY年MM月DD日')
    },
    // 获取基本数据
    loadBaseData: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/prepare_integral_options', {
            id: this.profile.id,
            category_tree: 1,
            dept_tree: 1})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.deptTree = jsonData.dept_tree
              self.creatorId = jsonData.creator_id

              if (self.profile.manager_type < 2) {
                self.filter.dept_id = [self.deptTree[0].value]
                self.loadEmployeeList()
              }
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 获取员工列表
    loadEmployeeList: function() {
      var self = this
      self.loading = true
      const params = {
        site_id: this.$store.getters.site_id,
        page: this.currentPage,
        interval: this.pageLimit
      }

      for (const item in this.filter) {
        const value = this.filter[item]
        if (item == 'dept_id') {
          if (!value || value.length == 0) {
            continue
          }
          params[item] = value[value.length - 1]
        } else {
          const valueStr = value.toString()
          if (valueStr && valueStr.length > 0) {
            params[item] = valueStr
          }
        }
      }
      if(self.include_admin){
        params['include_admin'] = 1
      }
      this.$http('get','/integral.php/ajax_request_common/get_employee_list',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              self.department_list = jsonData.filter_list.department
              self.totalCount = jsonData.total_count
              self.tableData = jsonData.list_data
              self.pageSelectedId = []
              const pageSelectedId = []
              self.$nextTick(() => {
                // console.log(self.multipleSelectionId)
                for (const i in jsonData.list_data) {
                  // console.log(self.multipleSelectionId.indexOf(jsonData.list_data[i].id),jsonData.list_data[i].id,self.multipleSelectionJson[jsonData.list_data[i].id])
                  if (
                    self.multipleSelectionId.indexOf(
                      jsonData.list_data[i].id
                    ) >= 0
                  ) {
                    self.$refs['multipleTable'].toggleRowSelection(
                      self.tableData[i],
                      true
                    )

                    pageSelectedId.push(self.tableData[i].id)
                  }
                }

                self.pageSelectedId = pageSelectedId
              })
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false
      }
      this.loadEmployeeList()
    }
  },
  created() {
    console.log(this.profile)
    this.loadBaseData()
    if (this.profile.manager_type > 1) {
      this.loadEmployeeList()
    }
  }
}
</script>
<style scoped>
.el-pagination {
  text-align: center;
  margin-top: 15px;
}
.dept_tree a.on {
  background-color: #f0f7ff;
}
.clearEmployeeBtn {
  cursor: pointer;
  color: #409eff;
  font-weight: normal;
}
.clearEmployeeBtn:hover {
  color: #66b1ff;
}
.rank_head img {
  width: 30px;
  height: 30px;
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  border-radius: 20px;
  margin-right: 5px;
}
.rank_head * {
  vertical-align: middle;
}
</style>
