<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="16">
        <!--工具栏-->
        <div class="head-container">
          <!-- 搜索 -->
          <el-input
            v-model="listQuery.Filter"
            clearable
            size="small"
            placeholder="搜索..."
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-button
            class="filter-item searchbutton"
            size="mini"
            type="success"
            icon="el-icon-search"
            @click="handleFilter"
          >搜索</el-button>
          <div class="opts">
  
          </div>
        </div>
        <!--表格渲染-->
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list"
          size="small"
          style="width: 100%;"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          :height="tableHeight"
          @current-change="handleSegalChange"
        >
          <el-table-column type="selection" ></el-table-column>
          <el-table-column label="用户名" prop="userName" sortable="custom" align="center">
          </el-table-column>
          <el-table-column label="邮箱" prop="email" sortable="custom" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.email}}</span>
            </template>
          </el-table-column>
          <el-table-column label="电话" prop="phoneNumber" sortable="custom" align="center" >
            <template slot-scope="scope">
              <span>{{scope.row.phoneNumber}}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="totalCount>0"
          :total="totalCount"
          :page.sync="page"
          :limit.sync="listQuery.MaxResultCount"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="4">
        <div class="head-container">
         <!-- <el-button
                  v-permission="['BaseService.UserBranch.Update']"
                  :loading="savePerLoading"
                  :disabled="multipleSelection.length != 1"
                  icon="el-icon-check"
                  size="mini"
                  style="padding: 6px 9px"
                  type="primary"
                  @click="saveUserBranch"
                >保存用户角色信息
                </el-button> -->
        <el-tag  size="mini" icon="el-icon-check" effect="plain" style="height:25px" >注意：配置角色时必须且只能选择一个组织！</el-tag>
        </div>
        <div class="system-content">
          <div class="system-view-nav"
               :style="{ height: treeHeight + 'px'}"
               style="background: #fff"
          >
            <el-tree
              :data="orgData"
              :load="getOrgs"
              :props="defaultProps"
              default-expand-all
              show-checkbox
              lazy
              @node-click="handleNodeClick"
              @check-change="handleCheckChange"
              style="margin-top:15px"
              ref="treeleft"
              node-key="id"
            />
          </div></div>
      </el-col>
      <el-col :span="4">

        <div class="head-container">
          <el-button
                  v-permission="['BaseService.UserBranch.Create']"
                  :loading="savePerLoading"
                  :disabled="multipleSelection.length != 1"
                  icon="el-icon-check"
                  size="mini"
                  style="padding: 6px 9px"
                  type="primary"
                  @click="saveUserBranch"
                >保存配置信息
                </el-button>
        </div>
        <div class="system-content">
          <div class="system-view-nav"
               :style="{ height: treeHeight + 'px'}"
               style="background: #fff"
          >
            <el-tree
              :data="roleList"
              :props="defaultProps2"
              style="margin-top:15px"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="treeright"
            />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { isvalidPhone } from "@/utils/validate";
  import Pagination from "@/components/Pagination";
  import permission from "@/directive/permission/index.js";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect";
  // function validCase(str) {
  //   var   re =/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/;
  //   return   re.test(str);
  // }

  const defaultForm = {
    id:undefined,
    orgId:undefined,
    userName:'',
    phoneNumber:'',
    name:'',
    email:'',
    password:'',
    lockoutEnabled:false,
    roleNames:[],
    jobs:[],
    orgIdToName: null,
  }
  export default {
    name: "User",
    components: { Pagination, Treeselect },
    directives: { permission },
    data() {
      const validateNameInput = (rule, value, callback) => {
        if (!value || value <= 0) {
          return callback(new Error('此项必填！'))
        }
        // else if (!validCase(value)) {
        //   callback(new Error("密码至少包含一位非字母数字字符., 密码至少包含一位小写字母 ('a'-'z')., 密码至少包含一位大写字母 ('A'-'Z')."));
        // }
        else {
          callback()
        }
      }
      // 自定义验证
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入电话号码"));
        } else if (!isvalidPhone(value)) {
          callback(new Error("请输入正确的11位手机号码"));
        } else {
          callback();
        }
      };
      const validName=(rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入登录名称"));
        } else if(/[\u4E00-\u9FA5]/g.test(value)) {
          callback(new Error("登录名不能输入汉字"));
        } else {
          callback();
        }
      };
      return {
        rules: {
          userName: [
            { required: true,  trigger: "blur",validator: validName },
            { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
          ],
          name: [
            { required: true, trigger: "blur", message: "请输入姓名"},
            { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
          ],
          email: [
            { required: true, message: "请输入邮箱地址", trigger: "blur" },
            { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
          ],
          phoneNumber: [
            { required: true, trigger: "blur", validator: validPhone }
          ]
          // ,password:[
          //   {required:true,trigger: "blur",minlength:6,validator: validateNameInput}
          // ]
        },
        savePerLoading: false,
        defaultProps2: { children: "children", label: "name", isLeaf: "leaf" },
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        form: Object.assign({}, defaultForm),
        list: null,
        orgName: "",
        orgs: [],
        roleName:'',
        roles:[],
        roleData:[],
        jobData:[],
        orgData: [],
        roleList: [],
        checkedRole: [],
        totalCount: 0,
        listLoading: true,
        formLoading: false,
        listQuery: {
          OrgId: null,
          Filter: "",
          Sorting: "",
          SkipCount: 0,
          MaxResultCount: 10
        },
        listSave:{
          branchId:null,
          userId:null,
          roles:[{
            roleId: ''
          }]
        },
        listSaveOrg:{
          branchId:null,
          userId:null
        },
        page: 1,
        dialogFormVisible: false,
        multipleSelection: [],
        formTitle: "",
        isEdit: false,
        tableHeight: document.documentElement.clientHeight - 270, // 表的高度
        treeHeight: document.documentElement.clientHeight - 150, // 表的3度
        treeHeight2:document.documentElement.clientHeight - 150,
        currentroleMessage:[],
        currentroleMessageOrg:[],
        selectBranch:false

      };
    },
    created() {
      // this.getList();
      // this.getAllRoles()
      var self = this
      /** 控制table的高度 */
      window.onresize = function() {
        self.tableHeight = document.documentElement.clientHeight - 270
        self.treeHeight = document.documentElement.clientHeight - 150
        self.treeHeight2 = document.documentElement.clientHeight - 150
      }
    },
    mounted(){
      this.getList();
      this.getAllRoles()
    },
    methods: {
       saveUserBranch() {//保存配置信息
        this.savePerLoading = true
        if (this.multipleSelection.length != 1) {
            this.$message({
              message: "保存必须选择一行用户信息！",
              type: "warning"
            });
            return;
          } else {
              var treeNodes=this.$refs.treeleft.getCheckedNodes();
              if(treeNodes.length <=0 || treeNodes.length !=1){
                  this.$message({
                        message: "保存必须选择组织且只能选中一个！",
                        type: "warning"
                      });
                    this.savePerLoading = false
                    return;
              } 
              else{
                let checkedKeys = this.$refs.treeright.getCheckedKeys();
                if(checkedKeys.length <=0){//没有选中角色，只保存用户-组织信息
                 this.$axios
                    .posts(
                      "/api/base/userbranch/createUpdate",this.listSaveOrg)
                    .then(response => {
                      this.$notify({
                           title: "成功",
                           message: "用户-组织信息添加成功",
                          type: "success",
                          duration: 2000
                      });
                    this.savePerLoading = false
                  });
              }
              else{
                this.$axios.gets("/api/base/userbranch/userRoles/"+this.listSave.userId+"/"+this.listSave.branchId )
                .then(response => {
                  if(response.length===0){//用户-组织-角色表中无当前条件的角色
                    //add
                    if(checkedKeys.length > 0){
                      this.listSave.roles=checkedKeys.map(itemid=>{
                        return {
                          roleId: itemid
                        }
                      })
                    }
                    this.$axios
                      .posts(
                        "/api/base/userbranch/createUpdate",this.listSave)
                        .then(response => {
                          this.$notify({
                              title: "成功",
                              message: "添加成功",
                              type: "success",
                              duration: 2000
                            });
                            this.savePerLoading = false
                      });
                  }
                  else{
                    //update
                    if(response.length >=1 && checkedKeys.length===0){
                      //用户-组织-角色表中有至少有一条角色信息，但是界面所有角色全不选操作
                      this.listSave.roles=checkedKeys.map(itemid=>{
                        return {
                          roleId: response
                        }
                      })
                    }
                    else{
                      if(checkedKeys.length > 0){
                      this.listSave.roles=checkedKeys.map(itemid=>{
                        return {
                          roleId: itemid
                          }
                        })
                      }
                    }
                    this.$axios
                      .posts(
                        "/api/base/userbranch/createUpdate",this.listSave)
                        .then(response => {
                          this.$notify({
                              title: "成功",
                              message: "更新成功",
                              type: "success",
                              duration: 2000
                            });
                            this.savePerLoading = false
                      });
                    
                  }
                  //
                });
             
              }
            }//else-end
          
        }
      },
      getOrgs(node, resolve) {
        const params = {};
        if (typeof node !== "object") {
          if (node) {
            params["filter"] = node;
          }
        } else if (node.level !== 0) {
          params["id"] = node.data.id;
        }
        //TODO:仅获取启用机构
        setTimeout(() => {
          this.$axios
            .gets("/api/base/branch/all", params)
            .then((response) => {
              if (resolve) {
                resolve(response.items);
              } else {
                this.orgData = response.items;
              }
            });
        }, 100);
      },
      getOrgNodes() {
        this.$axios.gets("/api/base/branch/children").then((response) => {
          this.loadTree(response);
        });
      },
      // getJobs(){
      //   this.$axios.gets('/api/base/job/jobs').then((response)=>{
      //     this.jobData=response.items
      //   })
      // },
      getList() {
        this.listLoading = true;
        this.listQuery.SkipCount = (this.page - 1) * 10;
        this.$axios.gets("/api/base/user", this.listQuery).then(response => {
          this.list = response.items;
          this.totalCount = response.totalCount;
          this.listLoading = false;
        });
      },
      fetchData(id) {
        this.getAllRoles();
        this.getOrgNodes();
        //this.getJobs()
        this.$axios.gets("/api/base/user/" + id).then(response => {
          this.form = response;
        });
        this.$axios.gets("/api/identity/users/" + id + "/roles").then(data => {

          data.items.forEach(item=>{
            this.checkedRole.push(item.name)
          })
        });
      },
      loadOrgs({ action, parentNode, callback }) {
        if (action === LOAD_CHILDREN_OPTIONS) {
          this.$axios
            //.gets("/api/base/orgs/loadOrgs", { id: parentNode.id })
            .gets("/api/base/branch/all", { id: parentNode.id })
            .then((response) => {
              parentNode.children = response.items.map(function (obj) {
                if (!obj.leaf) {
                  obj.children = null;
                }
                return obj;
              });
              setTimeout(() => {
                callback();
              }, 100);
            });
        }
      },
      getAllRoles(node) {
        const params = {};
        if (typeof node !== "object") {
          if (node) {
            params["filter"] = node;
          }
        }
        this.$axios
          .gets("/api/identity/roles/all",params)
          .then((response) => {
              this.roleList = response.items;
          });
      },
      handleFilter() {
        this.page = 1;
        this.getList();
      },
      handleNodeClick(data) {
        this.listSave.userId=this.multipleSelection[0].id;
        this.listSave.branchId=data.id;
        this.selectBranch=true;
        this.$axios.gets("/api/base/userbranch/userRoles/"+this.listSave.userId+"/"+this.listSave.branchId ).then(response => {
        this.currentroleMessage=response.map(item=>{
            let JSonmessge={
              id:item.roleId,
              label:item.roleId
            }
            return JSonmessge
          })
          this.getRoleRulesInfotwo()
        });
      },
      handleCheckChange(data, checked, indeterminate) {
        //  var str=[];
        //     str =this.$refs.treeleft.getCheckedKeys(); 
        //     if(str.length<=0){ // 因为vue返回的是选中的key的数组
        //       this.$message({
        //               message: "保存必须选择组织！",
        //               type: "warning"
        //             });
        //       this.savePerLoading = false
        //       return;
        //     }
        //      str.forEach(item=>{ 
        //         this.listSave.userId=null
        //         this.listSave.branchId=null
        //         this.listSave.userId=this.multipleSelection[0].id;
        //         this.listSave.branchId=item;

        //      });



        // var treeNodes=this.$refs.treeleft.getCheckedNodes();
        // if(treeNodes.length !=1)
        // {
        //    this.$message({
        //         message: "只能选中一个组织！",
        //         type: "warning"
        //       });
        //     return;
        // }
        
        var branchid=data.id
        var userid=this.multipleSelection[0].id
        if(checked){
          this.listSave.branchId=branchid;
          this.listSave.userId=userid;
          this.selectBranch=true;
           this.listSaveOrg.branchId=branchid;
          this.listSaveOrg.userId=userid;
          
        }
        else{
          this.selectBranch=false;
        }
        this.$axios.gets("/api/base/userbranch/userRoles/"+userid+"/"+branchid ).then(response => {
        this.currentroleMessage=response.map(item=>{
            let JSonmessge={
              id:item.roleId,
              label:item.roleId
            }
            return JSonmessge
          })
          this.getRoleRulesInfotwo()
        });

      },
      handleNodeClick2(data) {
        this.listQuery.RolesId = data.id;
        this.getList();
      },
      sortChange(data) {
        const { prop, order } = data;
        if (!prop || !order) {
          this.handleFilter();
          return;
        }
        this.listQuery.Sorting = prop + " " + order;
        this.handleFilter();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
       handleRowClick(row, column, event) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row);
      },
      cancel() {
        this.form = Object.assign({}, defaultForm),
        this.checkedRole=[]
        this.orgs=[]
        this.jobData=[]
        this.dialogFormVisible = false;
        this.$refs.form.clearValidate();
      },
      //TODO：引用公共方法
      loadTree(data) {
        data.items.forEach((element) => {
          if (!element.pid) {
            element.hasChildren = element.leaf ? false : true;
            if (!element.leaf) {
              element.children = [];
            }
            this.orgs.push(element);
          }
        });
        this.setChildren(this.orgs, data.items);
      },
      setChildren(roots, items) {
        roots.forEach((element) => {
          items.forEach((item) => {
            if (item.pid == element.id) {
              if (!element.children) element.children = [];
              element.children.push(item);
            }
          });
          if (element.children) {
            this.setChildren(element.children, items);
          }
        });
      },
      handleSegalChange(val){
        this.currentroleMessage=[]
        this.currentroleMessageOrg=[]
        if(val.userName==="admin"){
            if(val&&val.id){
              this.fetchUserforAdminRole(val.id)
              this.$refs.treeleft.setCheckedNodes([]);
            }
        }
        else{ 
        if(val&&val.id){
            //this.fetchData(val.id);
            this.fetchUserforRole(val.id)
            this.fetchUserforOrg(val.id)
            this.getRoleRulesInfo()
          }
        }
        // this.currentroleMessage=[]
        // this.currentroleMessageOrg=[]
        // if(val&&val.id){
        //   //this.fetchData(val.id);
        //   this.fetchUserforRole(val.id)
        //   this.fetchUserforOrg(val.id)
        //   this.getRoleRulesInfo()
        // }
      },
       //admin-roles
      fetchUserforAdminRole(id){
        this.$axios.gets("/api/identity/users/"+ id+"/roles" ).then(response => {
          this.currentroleMessage=response.items.map(item=>{
            let JSonmessge={
              id:item.id,
              label:item.name,
              disabled: true
            }
            return JSonmessge
          })
          this.getRoleRulesInfotwo()
        });
      },
      //加载用户-组织-角色
      fetchUserforRole(id){
        this.$axios.gets("/api/base/userbranch/"+ id+"/userRoles" ).then(response => {
          this.currentroleMessage=response.map(item=>{
            let JSonmessge={
              id:item.roleId,
              label:item.roleId
            }
            return JSonmessge
          })
          this.getRoleRulesInfotwo()
        });
      },
      
      fetchUserforOrg(id){
        this.$axios.gets("/api/base/userbranch/"+id+"/branches" ).then(response => {
          console.log(JSON.stringify(response))
          this.currentroleMessageOrg=response.map(item=>{
            let JSonmessge={
              id:item.branchId,
              label:item.branchName
            }
            return JSonmessge
          })
          this.getRoleRulesInfo()
        });
      },
      /**
       * 获取权限信息
       */
      getRoleRulesInfo() {
        this.$nextTick(() => {
          console.log(JSON.stringify(this.currentroleMessageOrg))
          // this.$refs.treeleft.setCheckedKeys([1]);
          this.$refs.treeleft.setCheckedNodes(this.currentroleMessageOrg);
        })
      },
      getRoleRulesInfotwo(){
        this.$nextTick(() => {
          console.log(JSON.stringify(this.currentroleMessage))
          this.$refs.treeright.setCheckedNodes(this.currentroleMessage);
        })
      }
    }
  };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .opts {
    padding: 6px 0;
    display: -webkit-flex;
    display: flex;
    align-items: center;
  }
  .leftTree {
    height: calc(100vh - 100px);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .system-content {
      position: relative;
      height: 100%;
      flex: 1;
      display: flex;
      overflow: hidden;
    }
    .system-view-nav {
      width: 100%;
      height: 100%;
      overflow: auto;
      background: #fff;
      border: 1px solid #e6e6e6;
    }
  }
</style>
