<template>
  <div class="all">
    <div class="flex-box-ce">
      <div class="flex-1">
        <div class="title">绩效主管理员</div>
        <div class="text fontColorC">拥有全部权限，支持更换主管理员</div>
      </div>
      <el-button  plain @click="setCreator = true" v-if="isCreator" class="primaryBtn"><i class="el-icon-plus"></i>添加</el-button>
    </div>
	<div class="flex-box flex-d-wrap" style="width: 900px;padding-top: 16px;">
		<div class="flex-box-ce zitem"  v-for="(item,index) in userMain" :key="index">
		  <userImage :user_name="item.name" :img_url="item.img_url" :id="item.id" fontSize="14"></userImage>
		  <span class="name flex-1">{{ item.name }}</span>
		  <i class="el-icon-close" v-if="item.id!=$getUserData().id"  @click="deleteUser2(item.id)"></i>
		  <!-- <el-button @click="deleteUser2(item.id)" type="text" class="red" v-if="item.id!=$getUserData().id">删除</el-button> -->
		</div>
	</div>
    <div class="flex-box-ce" style="margin-top: 20px;">
      <div class="flex-1">
        <div class="title">绩效子管理员</div>
        <div class="text fontColorB">负责绩效考核日常的管理工作，由主管理员分配权限</div>
      </div>
      <el-button  class="primaryBtn" plain @click="isAdministrator = true"><i class="el-icon-plus"></i>添加</el-button>
    </div>
    <div class="table-box" style="margin-top: 20px;">
      <el-table stripe :data="AdministratorList" style="width: 100%;" v-loading="loading">
        <el-table-column prop="date" label="姓名">
          <template slot-scope="scope">
            <div class="flex-box-ce">
              <userImage :user_name="scope.row.name" fontSize="14" :img_url="scope.row.img_url"></userImage>
              <span class="name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="range" label="管理范围">
          <template slot-scope="scope">
            <span>{{ filtrationStr(scope.row.range) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="menu" label="权限菜单">
          <template slot-scope="scope">
            <span>{{ filtrationStr(scope.row.menu) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="group" label="管理考核表">
          <template slot-scope="scope">
            <span>{{ filtrationStr(scope.row.group) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="compile(scope.row)" type="text" >编辑</el-button>
            <el-button @click="deleteUser(scope.row.id)" type="text" class="red" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page="page" :page_size="page_size" :page_sizes="[5]" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></Pagination>
    </div>
    <div>
      <!-- <div class="title-f fontColorB">其他角色权限说明</div> -->
      <div class="title-f">
        <div class="title">部门主管</div>
        <div class="text fontColorB">部门主管在【钉钉的组织架构】中设置，可对部门及子部门员工进行绩效指导、过程监督、评分以及查看结果</div>
      </div>
      <div class="title-f">
        <div class="title">普通员工</div>
        <div class="text fontColorB">员工只能看到自己的绩效，编写执行计划并进行沟通反馈</div>
      </div>
    </div>

    <!-- 更换主管理员 -->
    <EmployeeSelector
      title="设置主管理员"
      :is_filtration_creator="false"
      :multi="false"
      :isChecKedAll="false"
      :visible.sync="setCreator"
      @confirm="confirmCreator"
    />

    <!-- 绩效子管理员设置 -->
    <BrawerBox drawerTitle="绩效子管理员设置" :showDrawer.sync="isAdministrator" :closeModal="false">
      <template slot="main">
        <el-form ref="detailForm" @submit.native.prevent label-width="130px">
          <el-form-item label="子管理员:">
            <el-input v-model="userData.name" placeholder="请选择子管理员" class="width-150" :disabled="isDisabled"></el-input>
            <div @click="addUser()" class="inputDc" v-if="!isDisabled"></div>
          </el-form-item>
          <el-form-item>
            <template slot="label">
              <span>管理范围:</span>
            </template>
            <el-radio-group v-model="scope">
              <el-radio :label="3">全公司</el-radio>
              <el-radio :label="4">管理范围下的人员</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单权限:">
            <div v-for="(item, index) in checkboxs" :key="index">
              <el-checkbox v-model="item.check" :label="item.label" @change="actionCheck($event, item)"></el-checkbox>
              <div v-if="item.child" class="flex-box flex-d-wrap checkChild">
                <el-checkbox v-model="item2.check" :label="item2.label" @change="actionCheck2($event, item.child)" v-for="(item2, index2) in item.child" :key="index2"></el-checkbox>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="考核表权限:" v-show="isReviewShow">
            <el-radio-group v-model="review">
              <el-radio :label="14">全部考核表</el-radio>
              <el-radio :label="13">特定考核表</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="特定考核表:" v-show="isReviewShow2 && isReviewShow">
            <el-button @click="openKp()" plain class="primaryBtn" >请选择</el-button>
            <div v-for="(item, index) in selectGroup" :key="index">
              <el-tag type="success">{{ item.name }}</el-tag>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template slot="footer">
        <el-button plain @click="closeBrawer()">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm()">保存</el-button>
      </template>
    </BrawerBox>

    <!-- 嵌套Brawer -->
    <BrawerBox drawerTitle="选择考核表" :showDrawer.sync="isChecks" :closeModal="false">
      <template slot="main">
        <el-input prefix-icon="el-icon-search" placeholder="搜索考核表" v-model="searchWords" class="input-all" clearable></el-input>
        <div>
          <ul class="ul">
            <div class="flex-box-end" style="margin-bottom: 10px;"><el-button plain @click="qkSelect()" type="danger" size="mini">清空</el-button></div>
            <li v-for="(item, index) in groupList" :key="index" class="flex-box-ce li" v-if="returnName(item)">
              <el-checkbox class="flex-box-ce flex-1" v-model="item.check" style="padding: 15px 0;">
                <div class="flex-box-ce">
                  <div class="flex-1">{{item.name}}</div>
                 <div class="blue" v-if="item.employee_num > 0">{{ item.employee_num }} 人</div>
                </div>
              </el-checkbox>
            </li>
          </ul>
        </div>
      </template>
      <template slot="footer">
        <div>
          <el-button  @click="isChecks = false">取消</el-button>
          <el-button type="primary"  @click="saveKp()">保存</el-button>
        </div>
      </template>
    </BrawerBox>

    <!-- 选择子管理员 -->
    <EmployeeSelector
	:selected="selected"
	:is_filtration_creator="false"
	:multi="false"
	:isChecKedAll="false"
	:visible.sync="setAdministrator"
	@confirm="confirmAdministrator"
	:employee_not_select="employee_not_select"
	/>
  </div>
</template>

<script>
import EmployeeSelector from '@/components/public/EmployeeSelector';
import BrawerBox from '@/components/public/BrawerBox';
export default {
  components: { EmployeeSelector, BrawerBox },
  name: 'JurisdictionSet',
  data() {
    return {
      total: 0,
      page: 1,
      page_size: 5,
      loading: false,
      isAdministrator: false,
      isChecks: false,
      setAdministrator: false,

      // 编辑添加管理员
      checkboxs: [
        { label: '全部权限', id: 'all', check: true },
        {
          label: '考核管理',
          id: 'kh',
          check: true,
          child: [
            { label: '发起考核', id: '7', check: true },
            { label: '开始评分', id: '8', check: true },
            { label: '调整结果', id: '9', check: true },
            { label: '等级配置', id: '10', check: true },
            { label: '导出报表', id: '11', check: true },
			{ label: '批量转交', id: '17', check: true },
			{ label: '批量修改目标值', id: '18', check: true },
          ]
        },
        { label: '指标库', id: '12', check: true },
        { label: '基础设置', id: '15', check: true },
        { label: '绩效报表', id: '16', check: true },
        { label: '考核表设置', id: 'kp', check: true }
      ],
      selected: { employee: [], dept: [] },
      // 考核表
      searchWords: '',
      groupList: [],
      userMain: {}, //主管理员
      AdministratorList: [], //子管理员列表
      setCreator: false, //更换主管理员
      isCreator: false, //是否创始人
      employee_not_select: [],//过滤的管理员

      // 添加编辑子管理员
      userData:{},
      scope: 3, //管理范围
      isKjJg: true, //是否可见考核结果
      review: 14, //考核表
      isReviewShow: true, //控制考核表是否能显示
      isReviewShow2: false, //控制考核表是否能显示
      parameter: {
        id: '',
        permission: '',
        group: '',
		main:0
      },
      selectGroup: [], //选择的考核表
      isDisabled: false,
      id: ''
    };
  },
  watch: {
	searchWords(val){
		console.log(val) 
	}, 
    review(val) {
      this.isReviewShow2 = val == 14 ? false : true;
    },
  },
  computed:{
	returnName(){
		return (item)=>{
			return item.name.indexOf(this.searchWords) >= 0
		}
	}  
  },
  created() {
    this.isCreator = this.$authoritys('masterAdministrator');//是否主管理员
    this.getList();
    this.getList2();
    this.getGroups();
  },
  mounted() {
    this.$nextTick(() => {});
  },
  methods: {
    actionCheck2(e, obj){
      let data=obj.filter(item=>{
        return item.check
      })
      if(data.length==0){
        for (let i in this.checkboxs) {
          if(this.checkboxs[i].id=='kh'){
            this.$set(this.checkboxs[i], 'check', false);
          }
        }
      }
      if(e){
        for (let i in this.checkboxs) {
          if(this.checkboxs[i].id=='kh'){
            this.$set(this.checkboxs[i], 'check', true);
          }
        }
      }
    },
    deleteUser(id) {
      this.$confirm('确定删除该子管理员', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios('POST', '/api/per/user/delete_sub_manager', { id_code: this.$returnCode(id) }).then(res => {
            this.$message.success('删除成功');
            this.getList();
          });
        })
        .catch(() => {});
    },
	//删除主管理员
	deleteUser2(id) {	
	  this.$confirm('确定删除该主管理员', '提示', {
	    confirmButtonText: '确定',
	    cancelButtonText: '取消',
	    type: 'warning'
	  })
	    .then(() => {
	      this.$axios('POST', '/api/per/user/delete_sub_manager', { id_code: this.$returnCode(id) }).then(res => {
	        this.$message.success('删除成功');
	        this.getList2();
	      });
	    })
	    .catch(() => {});
	},
    // 过滤
    filtrationStr(str, is) {
      if (is) {
        var text = [...str].toString();
        return str.length > 0 ? text : '--';
      } else {
        return str ? str : '--';
      }
    },
    // 关闭
    closeBrawer() {
      this.qkSelect();
      this.scope = 3;
      this.review = 14;
      this.isKjJg = true;
      this.isReviewShow = true;
      this.isReviewShow2 = false;
      this.userData = {};
      this.parameter = { id: '',permission: '',group: '',main:0},
      this.selected = { employee: [], dept: [] };
      this.isDisabled = false;
      this.isAdministrator = false;
    },
    qkSelect() {
      // 初始化数据
      this.selectGroup = [];
      for (let i in this.groupList) {
        this.$set(this.groupList[i], 'check', false);
      }
      for (let i in this.checkboxs) {
        this.$set(this.checkboxs[i], 'check', true);
        if (this.checkboxs[i].child) {
          for (let j in this.checkboxs[i].child) {
            this.$set(this.checkboxs[i].child[j], 'check', true);
          }
        }
      }
    },
    //获取考核表
    getGroups() {
      this.$axios('get', '/api/per/evaluation/all_group').then(res => {
        let list = res.data.data.list || [];
        list.forEach(item => {
          item.check = false;
        });
        this.groupList = list;
      });
    },
    // 获取主管理员
    getList2() {
      this.$axios('get', '/api/per/user/manager_info', { range: 1 }).then(res => {
        let userMain = res.data.data.list || [];
		this.userMain = userMain.filter(item => {
			item.name=this.$getEmployeeList()[item.id].name
			return item
		});
      });
    },
    // 获取子管理员
    getList() {
      this.loading = true;
      this.$axios('get', '/api/per/user/manager_info', { page: this.page, page_size: this.page_size, range: 0 })
        .then(res => {
          let data = res.data.data.list || [];
          this.total = res.data.data.total;
          this.AdministratorList = data.filter(item => {
			item.name=this.$getEmployeeList()[item.id].name
            this.employee_not_select.push(item.id);
            return item.main == 0;
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 编辑
    compile(obj) {
      this.setCheckboxs();
      // 人员复原
      this.userData={
        name: obj.name,
        id: obj.id,
        img_url: obj.img_url
      }
      // this.selected = { employee: [{ name: obj.name, id: obj.id, img_url: obj.img_url }], dept: [] };
      // 权限复原
      let permissionIds = obj.permission.map(item => {
        return item.id;
      }); //返回权限ID
      var checkboxs = this.checkboxs;
      this.isKjJg = false;
      let isReviewShow = false;
      permissionIds.forEach(item => {
        if (item == 6) {
          this.isKjJg = true;
        }
        if (item == 3 || item == 4) {
          this.scope = item;
        }
        if (item == 13 || item == 14) {
          this.review = item;
          isReviewShow = true;
        }
        for (let i in checkboxs) {
          if (checkboxs[i].id == item) {
            this.$set(checkboxs[i], 'check', true);
          }
          if ((item == 13 || item == 14) && checkboxs[i].id == 'kp') {
            this.$set(checkboxs[i], 'check', true);
          }
          if (checkboxs[i].child) {
            for (let j in checkboxs[i].child) {
              if (checkboxs[i].child[j].id == item) {
                this.$set(checkboxs[i], 'check', true);
                this.$set(checkboxs[i].child[j], 'check', true);
              }
            }
          }
        }
      });
      //特定考评复原
      this.selectGroup = obj.group_list;
      this.isReviewShow = isReviewShow;
      this.isDisabled = true;
      this.isAdministrator = true;
    },
    //将权限全部取消
    setCheckboxs() {
      for (let i in this.checkboxs) {
        this.$set(this.checkboxs[i], 'check', false);
        if (this.checkboxs[i].child) {
          for (let j in this.checkboxs[i].child) {
            this.$set(this.checkboxs[i].child[j], 'check', false);
          }
        }
      }
    },
    // 添加子管理员
    submitForm() {
      this.parameter.id = this.userData.id;
	  this.parameter.id_code = this.$returnCode(this.userData.id);
      var parameter = JSON.parse(JSON.stringify(this.parameter));
      if (!parameter.id) {
        this.$message.error('请选择子管理员');
        return false;
      }
      // 权限
      var permission = [];
      this.checkboxs.forEach(item => {
        if (item.check) {
          if (item.id != 'all' && item.id != 'kh' && item.id != 'kp') {
            permission.push(Number(item.id));
          }
          if (item.child) {
            item.child.forEach(item2 => {
              if (item2.check) {
                permission.push(Number(item2.id));
              }
            });
          }
        }
      });
      permission.push(this.scope); //管理范围
      if (this.isKjJg) {
        permission.push(6);
      } //可见考核结果
      // 指定考核表
      if (this.checkboxs[this.checkboxs.length - 1].check) {
        permission.push(this.review); //考核表
        if (this.review == 13) {
          let group = [];
          this.selectGroup.forEach(item => {
            group.push(item.id);
          });
          parameter.group = group.toString();
        }
      }
      parameter.permission = [...new Set(permission)].toString();
	  // console.log(parameter)
	  // return false;
      this.$axios('post', '/api/per/user/add_sub_manager', parameter).then(res => {
        this.$message.success('添加成功');
        this.getList();
        this.getList2();
        this.closeBrawer();
      });
    },
    actionCheck(e, obj) {
      if (obj.id == 'all') {
        //点击全部
        this.checkboxs.forEach(item => {
          item.check = e;
          if (item.child) {
            item.child.forEach(item2 => {
              item2.check = e;
            });
          }
        });
        this.isReviewShow = e;
        if (!e) {
          //当取消全部时的处理
          this.isReviewShow2 = e;
          this.review = 14;
        }
        return false;
      }
      if (obj.id == 'kp') {
        //点击考核表
        this.isReviewShow = e;
      }
      if (obj.child && obj.id == 'kh') {
        if (e) {
          obj.child.forEach(item => {
            item.check = true;
          });
        } else {
          obj.child.forEach(item => {
            item.check = false;
          });
        }
      }
      if (!e) {
        this.$set(this.checkboxs[0], 'check', false);
      }
    },
    openKp(){
      let group_ids=this.selectGroup.map(item=>{return item.id})
      this.groupList.forEach((item, index) => {
        this.$set(this.groupList[index], 'check', false);
        if (group_ids.indexOf(item.id) >= 0) {
          this.$set(this.groupList[index], 'check', true);
        }
      });
      this.isChecks=true
    },
    saveKp(){
      let selectGroup = [];
      this.groupList.forEach(item=>{
        if(item.check){
          selectGroup.push(item)
        }
      })
      this.selectGroup=selectGroup;
      this.isChecks=false
    },
    //设置主管理员
    confirmCreator(e) {
      if (e.employee.length == 0) {
        return;
      }
	 let data={
		 id_code:this.$returnCode(e.employee[0].id),
		 permission:'1,2,3,6,7,8,9,10,11,14,15,16,17,18',
		 main:1
	 }
      this.$axios('post', '/api/per/user/add_sub_manager', data).then(res => {
        this.$message.success('设置成功');
		this.getList();
        this.getList2();
      });
    },
    //选择人员
    addUser(){
      this.selected.employee=this.userData.name? [this.userData]:[];
      this.setAdministrator=true;
    },
    //设置子管理员
    confirmAdministrator(e) {
      this.userData=e.employee.length>0? e.employee[0]:{};
      this.setAdministrator=false;
    },
    // 页面变更
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
    // 页面跳转
    handleSizeChange(val) {
      this.page_size = val;
      this.getList();
    }
  }
};
</script>

<style scoped="scoped">
.el-icon-close{
	position: relative;
	top: -14px;
	cursor: pointer;
}
.el-icon-close:hover{
	color: #F56C6C;
}
.zitem{
	padding: 10px;
	width: 180px;
	border-radius: 5px;
	background-color: #F5F9FF;
	margin-right: 10px;
	margin-bottom: 10px;
}	
.all {
  min-height: calc(100vh - 210px);
  overflow: auto;
  padding: 10px;
}
.title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
}
.name {
  padding-left: 10px;
}
.title-f {
  margin-bottom: 20px;
}
.inputDc {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 9;
}
.checkChild {
  background-color: #fbfdff;
  margin-left: 20px;
}
.li {
  border-bottom: 1px solid #f1f1f1;
}
.li:hover {
  background-color: #f5f7fa;
}
.ul {
  margin: 20px 0;
  margin-top: 10px;
}
</style>
