<template>
  <div>
    <el-alert class="diy-tip" title="温馨提示：" :closable="false"  type="success" description show-icon>
      当前组织架构成员通过微信通讯录同步，员工开启积分管理后才能正式启用并进入“功道云积分制”，如果您的微信通讯录有变动，点击
      <span class="blue" style="margin-left: 10px;cursor: pointer;" @click="tb()">
        <i class="el-icon-refresh"></i>
        立即同步
      </span>
    </el-alert>

    <el-row class="architecture">
      <el-col :span="6" class="RuleLeft">
        <div>
          <div v-loading="ruleDeprt">
            <div class="company_name">
              <img src="static/images/two.png" />
              <span>组织架构</span>
            </div>
            <div ref="ruletree" class="department_box">
              <el-tree
                node-key="id"
                :expand-on-click-node="false"
                :data="bmList"
                class="cate-tree"
                :highlight-current="true"
                :props="{ children: 'children', label: 'name', value: 'id' }"
                @node-click="handleNodeClick"
                :accordion="true"
                empty-text="您暂无部门数据,请同步微信通讯录"
              >
                <div
                  content="tree"
                  class="custom-tree-node"
                  slot-scope="{ node, data }"
                  style="font-size: 14px;color: #606266; width:100%; text-align: left;"
                >
                  <img src="static/images/one.png" style="width: 20px;margin-right: 5px;" />
                  <span class="name"><WWOpenData type="departmentName" :openid="data.name"></WWOpenData></span>
                </div>
              </el-tree>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="18" class="RuleRight">
        <el-button @click="participation()" :loading="enable_loading" size="medium" type="primary" style="margin-right: 10px;">批量启用积分管理</el-button>
        <el-input placeholder="输入同事姓名" maxlength="20" size="medium" style="width: 230px;" v-model="keywords" clearable @input="searchUser()"></el-input>
        <div style="color: #303133;font-size: 14px;padding:10px 0 0 0; line-height: 32px; overflow: hidden;"></div>
        <div class="list_box">
          <div style="margin-bottom:10px;margin-top:30px;" class="inline-block-btn-list"><div class="gap-right-8 fr" style="display:inline-block; width:180px;"></div></div>
          <el-table :data="userList" @selection-change="handleSelectionChange" v-loading="tableToading">
            <el-table-column type="selection" width="50" :selectable="isSelectable"></el-table-column>
            <el-table-column label="姓名">
              <template slot-scope="scope">
                <div class="flex-box flex-v-ce">
                  <userImage :user_name="scope.row.name" :img_url="scope.row.img_url" width="44px" height="44px"></userImage>
                  <div style="margin-left: 10px;"><WWOpenData type="userName" :openid="scope.row.name"></WWOpenData></div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="部门">
              <template slot-scope="scope">
                <div class="" style="">
                  <span v-for="(item, index) in scope.row.employee_detail.dept_list" :key="index">
                    <div v-if="item.depart_id !== 1">
                      <WWOpenData type="departmentName" :openid="item.depart_name"></WWOpenData>
                      <span v-if="scope.row.employee_detail.dept_list.length - index > 1">,</span>
                    </div>
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="accedence_time" label="入职时间">
              <template slot-scope="scope">
                <div class="tabaccTIme" v-loading="scope.row.entryIf">
                  <el-date-picker
                    @change="entryclick(scope.row)"
                    clear-icon="el-icon-circle-close"
                    v-model="scope.row.accedence_time"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="timestamp"
                    placeholder="选择日期时间"
                    :clearable="false"
                  ></el-date-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="启用积分管理">
              <template slot="header" slot-scope="scope">
                <el-popover placement="top-start" width="300" trigger="manual" v-model="visible">
                  <div class="el-popover2">
                    <div class="title">
                      提示
                      <i class="el-icon-info" style="margin-left: 5px;"></i>
                    </div>
                    <div style="margin-bottom: 10px;">在这里启用积分管理，即可进入系统</div>
                    <div class="flex-box">
                      <div class="flex-1"></div>
                      <el-button size="small" @click="visible_close()">我知道了</el-button>
                    </div>
                  </div>
                  <div slot="reference" class="popover" @click="visible = !visible">启用积分管理</div>
                </el-popover>
              </template>
              <template slot-scope="scope">
                <div :class="[scope.row.is_official == 1 ? 'switch-box' : '']" @click="changeIs(scope.row.is_official, scope.row.id)"><div class="switch"></div></div>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="操作" >
              <template slot-scope="scope">
                <el-link type="primary" :disabled="scope.row.is_creator == 1 || scope.row.is_official == 0"  @click="moreMessage(scope.row.id)" :underline="false">更多信息</el-link>
              </template>
            </el-table-column>
            <template slot="empty">
              <noData></noData>
            </template>
          </el-table>

          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="perPage"
            layout="total,sizes, prev, pager, next"
            :total="total"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>



    <el-dialog  :close-on-click-modal="false" ref="EditInformation_list" title="员工详情" width="500px" :visible.sync="diaTableVisible">
    	<div style="padding-right:20px;">
    		<el-form ref="detailForm" v-loading="show_loading">
    			<el-form-item label="管理上级" prop="name" :label-width="'100px'">
            <div class="input-box" @click="setSuperior()">
              <div v-if="superior_list.length==0" class="fontColorT">暂无管理上级</div>
              <div v-else>
                <span v-for="(item,index) in superior_list">
                  <WWOpenData type="userName" :openid="item.name"></WWOpenData>,
                </span>
              </div>
            </div>
    			</el-form-item>
    			<el-form-item label="直属上级" prop="name" :label-width="'100px'">
    				<div class="input-box" @click="dirSuperior()">
              <div v-if="dirSupervisor.id"><WWOpenData type="userName" :openid="dirSupervisor.name"></WWOpenData></div>
              <div v-else class="fontColorT">暂无直属上级</div>
            </div>
    			</el-form-item>
    		</el-form>
    	</div>
    </el-dialog>

    <!-- 设置管理上级 -->

<!--    :employee_list="manageListData"
    :user_employee_list="true" -->

    <EmployeeSelector
      title="管理上级"
      :visible.sync="manageScope_show"
      :is_filtration_creator="false"
      :multi="true"
      :selected="selected_manage"
      @confirm="manage_confirm"
    />
    <!-- 直属上级 -->
    <EmployeeSelector
      title="直属上级"
      :visible.sync="scope_loading"
      :is_filtration_creator="false"
      :isChecKedAll="false"
      :multi="false"
      :employee_list="superior_list"
      :user_employee_list="true"
      :selected="selected_manage"
      @confirm="dirSup_confirm"
    />
  </div>
</template>
<script>
import noData from '@/components/noData';
import EmployeeSelector from '@/views/common/EmployeeSelector'
import { _debounce } from '@/api/auth';
export default {
  components: {noData,EmployeeSelector},
  data() {
    return {
      is: 1,
      no: 0,
      page: 1,
      perPage: 10,
      total: 0,
      info: {}, //公司信息
      bmList: [],
      userList: [],
      keywords: '',
      dept_id: 0,
      tableToading: false,
      selectIds: [],
      enable_loading: false,
      visible: false,
      ruleDeprt: false,

      // 设置上级
      newId: 0,
      diaTableVisible: false,
      show_loading:false,
      manageScope_show: false, //管理上级
      scope_loading: false, //直接上级

      userInfo: {},
      superior_list: [], //用户上级
      dirSupervisor:{}, //用户直属上级
      employeeAll:[],//启用的人员列表
      manageListData: [],//公司管理员列表
      employeeList: [],
      selected_manage: { employee: [], dept: [] },
    };
  },
  watch: {
    dept_id(val) {
      this.getEmployee();
    }
  },
  created() {
    this.getInfo();
    this.getEmployee();
  },
  mounted() {
    this.filtration();
    // this.manageList();
  },
  methods: {
    manage_confirm(date) {
    	let manageId = [];
    	date.employee.forEach(item => manageId.push(item.id))
    	let data = {
    		employee_id: this.newId,
    		manage_id: manageId
    	}
    	this.$http('post', '/api/employee/superior', data).then(res =>{
    			this.$message.success('设置成功');
    			this.moreMessage();
    	})
    },
    dirSup_confirm(date){
    	let data = {
    		employee_ids: [this.newId],
    		superior_id: date.employee.length > 0 ? date.employee[0].id : null
    	}
    	this.$http('post','/api/employee/directly_superior',data).then(res =>{
    			this.$message.success('设置成功');
    			this.moreMessage();
    	})
    },
    setSuperior(){
    	this.selected_manage.employee =JSON.parse(JSON.stringify(this.superior_list));
    	this.manageScope_show = true
    },
    dirSuperior(row){
    	if(this.dirSupervisor.id){
    		this.selected_manage.employee = [this.dirSupervisor]
    	}else{
    		this.selected_manage.employee = []
    	}
    	this.scope_loading = true
    },
    moreMessage(id) {
    	if(id){
    		this.newId = id
    	}
    	this.diaTableVisible = true
    	this.show_loading = true
    	this.$http('get', '/api/employee/info', { id: this.newId }).then(res=>{
        	let data = res.data.data
          this.userInfo = data
        	if(data.employee_detail.superior_list){
        		let employeeD = data.employee_detail
        		if(employeeD.superior_id != 0){
        			this.dirSupervisor = employeeD.superior_list.filter(x => x.id == employeeD.superior_id)[0]||{}
        		}else{
        			this.dirSupervisor = {}
        		}
        		// 过滤已经离职人员
        		this.superior_list=[...this.employeeAll].filter(x => [...employeeD.superior_list].some(y => y.id === x.id));
        	}
      }).finally(() =>{
    		this.show_loading = false
    	})
    },
    // 所有已启用的人员
    filtration() {
      this.$http('get', '/api/employee/index', {page: 0, page_size: 3000,is_official:1 }).then(res => {
    	 this.employeeAll = res.data.data.list;
      });
    },
    //管理列表
    manageList(){
    	let params = {
    		roles: ['creator', 'admin', 'point_manager', 'dept_manager']
    	}
    	this.$http('get', '/api/employee/role_employee', params).then(res =>{
    		if(res.data.code == 1){
    			this.manageListData = res.data.data.list
    		}
    	})
    },
    entryclick(row) {
      let data = {
        employee_id: row.id,
        accedence_time: row.accedence_time / 1000
      };
      row.entryIf = true;
      this.$http('post', '/api/employee/accedence_time', data)
        .then(res => {
          if (res.data.code == 1) {
          }
        })
        .finally(() => {
          row.entryIf = false;
        });
    },
    //同步信息
    tb() {
      this.$http('get', '/api/sync').then(res => {
        if (res.data.code == 1) {
          this.$message.success({ message: '正在同步，请稍候刷新页面查看同步结果' });
        }
      });
    },
    //搜索
    searchUser: _debounce(function() {
      this.page = 1;
      this.getEmployee();
    }),
    //是否开通
    changeIs(e, id) {
      if(e==1){
        this.$confirm("禁用后，相关人员将不再允许进入积分系统，并且移除其上下级管理关系，确认禁用吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
            var url = e == 1 ? '/api/employee/disable' : '/api/employee/enable';
            this.$http('post', url, { employee_id: [id] }).then(res => {
              if (res) {
                if (e == 0) {
                  this.$message.success({ message: '开启成功,可在"角色权限设置对应管理范围"' });
                } else {
                  this.$message.success({ message: res.data.msg });
                }
                this.getEmployee();
              }
            });
        });
      }else{
        var url = e == 1 ? '/api/employee/disable' : '/api/employee/enable';
        this.$http('post', url, { employee_id: [id] }).then(res => {
          if (res) {
            if (e == 0) {
              this.$message.success({ message: '开启成功,可在"角色权限设置对应管理范围"' });
            } else {
              this.$message.success({ message: res.data.msg });
            }
            this.getEmployee();
          }
        });
      }
      
    },
    //批量开通权限
    participation() {
      if (this.selectIds.length == 0) {
        this.$message.error({ message: '请选择参与的人员！' });
        return;
      }

      this.enable_loading = true;
      this.$http('post', '/api/employee/enable', { employee_id: this.selectIds })
        .then(res => {
          if (res) {
            this.$message.success({ message: '开启成功,可在"角色权限设置对应管理范围"' });
            this.getEmployee();
          }
        })
        .finally(err => {
          this.enable_loading = false;
        });
    },
    //获取公司信息
    getInfo(is) {
      this.ruleDeprt = true;
      this.$http('get', '/api/site/info').then(res => {
        this.info = res.data.data;
        this.getDepartment(is);
      });
    },
    //选择员工
    handleSelectionChange(e) {
      var arr = [];
      for (var item in e) {
        arr.push(e[item].id);
      }
      this.selectIds = arr;
    },
    isSelectable: function(row, index) {
      return row.is_official != 1;
    },
    //点击部门
    handleNodeClick(e) {
      this.page = 1;
      this.dept_id = e.id;
    },
    //获取部门
    getDepartment() {
      this.ruleDeprt = true;
      this.$http('get', '/api/department/tree')
        .then(res => {
          var list = [
            {
              id: 0,
              name: this.info.name,
              children: res.data.data.list
            }
          ];
          this.bmList = list;
        })
        .finally(() => {
          this.ruleDeprt = false;
        });
    },
    //获取员工
    getEmployee() {
      this.tableToading = true;
      let params = {
        page: this.page,
        page_size: this.perPage,
        dept_id: this.dept_id,
        keywords: this.keywords
      };
      if (this.page == 0) {
        params.page = this.page;
      } else {
        params.page = this.page - 1;
      }
      this.$http('get', '/api/employee/index', params)
        .then(res => {
        this.total = res.data.data.pageInfo.count;
          let list = res.data.data.list;
          list.forEach(item => {
            item.entryIf = false;
            item.accedence_time *= 1000;
          });
          this.userList = list;
          var visible = localStorage.getItem('visible');
          if (!visible) {
            this.visible = true;
          }
        })
        .finally(err => {
          this.tableToading = false;
        });
    },
    visible_close() {
      localStorage.setItem('visible', 'true');
      this.visible = false;
    },
    handleSizeChange: function(val) {
      this.perPage = val;
      this.page = 1;
      this.getEmployee();
    },
    //页码变更
    handleCurrentChange: function(val) {
      this.page = val;
      this.getEmployee();
    }
  }
};
</script>
<style lang="scss" scoped>
.input-box{
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 15px;
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.name {
  text-overflow: ellipsis;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  width: 120px;
}
.administration {
  color: #e6a23c;
  border: 1px solid #e6a23c;
  border-radius: 2px;
  font-size: 12px;
  margin-left: 4px;
  padding: 2px;
}

.el-table th > .cell {
  font-weight: normal;
}
.el-table .has-gutter th > .cell {
  background-color: #fff;
  font-size: 14px;
  color: #909399;
  font-weight: normal;
}
.title {
  color: #303133;
  font-size: 20px;
}
.el-button--text {
  color: #606266;
}
.add {
  color: #26a2ff;
  font-size: 14px;
  //padding-top: 20px;
  cursor: pointer;
}
.el-pagination {
  text-align: center;
  margin-top: 15px;
}
.arrRotation {
  transform: rotate(180deg);
}
.treeActice {
  color: #606266;
}

.treeIcon {
  display: none;
}
.custom-tree-node {
  // display: flex;
  //flex-direction:row;
  // justify-content: space-between;
  // width: 100%;
  margin-left: -4px;
}
.custom-tree-node * {
  vertical-align: middle;
}
.custom-tree-node:hover {
  .treeIcon {
    display: inline-block;
    width: 55%;
  }
}
.item:hover {
  .blueTree {
    display: block;
  }
  .iconTree {
    display: none;
  }
}

.blueTree {
  display: none;
}
el-tooltip {
  display: none;
}
.add {
  color: #26a2ff;
  font-size: 14px;
  //padding-top: 20px;
  cursor: pointer;
}
.architecture {
  display: flex;
  text-align: center;
  // margin-top:20px;
  padding-left: 0px;
  background-color: #fff;
  width: 100%;
  overflow: hidden;
  cursor: default;
  min-height: calc(100vh - 160px);
}
.architecture .RuleLine {
  display: table-cell;
  width: 1px;
  min-height: 600px;
  background: #efefef;
}
.architecture .RuleLeft {
  display: block;
  text-align: center;
  padding: 20px 10px;
  border-right: none;
  overflow: auto;
}
/*滚动条的宽度*/

.architecture .RuleLeft::-webkit-scrollbar {
  width: 9px;
  height: 9px;
}

/*外层轨道。可以用display:none让其不显示，也可以添加背景图片，颜色改变显示效果*/

.architecture .RuleLeft::-webkit-scrollbar-track {
  width: 6px;
  background-color: #fff0;
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
}

/*滚动条的设置*/

.architecture .RuleLeft::-webkit-scrollbar-thumb {
  background-color: #fff0;
  background-clip: padding-box;
  min-height: 28px;
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
}
/*滚动条移上去的背景*/

.architecture .RuleLeft:hover::-webkit-scrollbar-thumb {
  background-color: rgba(144, 147, 153, 0.3);
}

.architecture .RuleLeft .company_name {
  position: relative;
  display: block;
  font-family: 'Microsoft YaHei';
  text-align: left;
  padding: 15px 28px 17px;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  border-bottom: 1px #f8f8f8 solid;
}
.architecture .RuleLeft .company_name img {
  position: relative;
  display: inline-block;
  top: 2px;
  width: 18px;
  height: 18px;
  margin-right: 4px;
}
.architecture .RuleLeft /deep/ .el-button {
  margin-bottom: 16px !important;
}
.architecture .RuleRight {
  position: relative;
  display: table-cell;
  text-align: left;
  padding: 20px;
}
.architecture .RuleRight .title span .sapn {
  display: inline-block;
  vertical-align: middle;
  max-width: 600px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.architecture .RuleRight:after {
  content: ' ';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 1px;
  background: #ebeef5;
}
.architecture .RuleRight .list_box {
  width: 100%;
  background: #fff;
}
.architecture .RuleRight .list_box /deep/ table {
  font-family: 'Microsoft YaHei';
  width: 100% !important;
  /*max-width:1920px; */
}
.architecture .department_box {
}
.architecture .department_box /deep/ .el-tree-node {
  display: block;
  text-align: center;
}
.architecture .department_box /deep/ .el-tree-node__content {
  // padding-left:24px !important;
  height: auto !important;
}

.architecture .department_box /deep/ .el-tree-node .el-icon-caret-right {
  display: inline-block;
  color: #909399;
  font-size: 16px;
  padding: 6px 8px;
}
.architecture .department_box /deep/ .el-tree-node .el-icon-caret-right.is-leaf {
  color: transparent;
  cursor: default;
}
.architecture .department_box /deep/ .el-tree-node .custom-tree-node img {
  margin-top: 0px;
  width: 20px;
}
.architecture .department_box /deep/ .el-tree-node .custom-tree-node span {
}
.architecture .department_box /deep/ .el-tree-node__content {
  padding: 12px 0;
  border-bottom: 1px #f8f8f8 solid;
}
.architecture .department_box /deep/ .el-tree-node__content:hover {
  background: #ecf5ff;
  border-radius: 4px;
}
.architecture .department_box /deep/ .is-focusable .is-current {
  border-radius: 4px;
}
.architecture .department_box /deep/ .is-focusable .is-current .name {
  color: #409eff;
  font-weight: normal;
  transition: 0.35s ease-in-out;
}
.diy-tip {
  margin-bottom: 15px;
  border: 1px solid #67c23a;
  padding: 20px 16px;
  p {
    color: #67c23a !important;
    font-size: 14px;
    margin: 0 !important;
    padding: 4px 0;
  }
}

.switch {
  margin: 0;
  display: inline-block;
  position: relative;
  width: 40px;   height: 20px;
  border: 1px solid #dcdfe6;
  outline: none;   border-radius: 10px;
  box-sizing: border-box;
  background: #dcdfe6;   cursor: pointer;
  transition: border-color 0.3s, background-color 0.3s;
  vertical-align: middle;
}
.switch:after {
  content: '';
  position: absolute;
  top: 1px;
  left: 1px;   border-radius: 100%;
  transition: all 0.3s;
  width: 16px;
  height: 16px;   background-color: #fff;
}
.switch-box .switch {
  border-color: #409eff;
  background-color: #409eff;
}
.switch-box .switch:after {   left: 100%;
  margin-left: -17px;
}

/deep/ .tabaccTIme {
  width: 100px;
  .el-input__inner {
    border: 0;
    background-color: transparent;
    cursor: pointer;
    padding: 0;
    width: 100px;
  }
  .el-input__prefix {
    display: none;
  }
}
</style>
