<template>
  <div class="detail_contain">
    <p class="now_page_title">
      权限管理 / 角色管理 /
      <span>{{
        $route.path.indexOf("edit") !== -1
          ? "角色类型"
          : $route.path.indexOf("add") !== -1
          ? "新增角色"
          : "分配权限"
      }}</span>
    </p>
    <div class="info_contain">
      <p v-if="$route.path.indexOf('allot') !== -1" class="borerd">
        <span></span>基本信息
      </p>
      <el-form ref="form" :rules="rules" :model="form" label-width="0px">
        <el-form-item prop="name">
          <p class="formname">角色名称：</p>
          <el-input v-model="form.name" :disabled="edit_flag==3"></el-input>
        </el-form-item>

        <el-form-item prop="desc">
          <p class="formname">角色描述：</p>
          <el-input type="textarea" v-model="form.desc" :disabled="edit_flag==3"></el-input>
        </el-form-item>

        <el-form-item prop="person">
          <p class="formname">登记人：</p>
          <el-input v-model="form.person" disabled></el-input>
        </el-form-item>

        <el-form-item prop="date">
          <p class="formname">登记日期：</p>
          <el-input v-model="form.date" disabled></el-input>
        </el-form-item>

        <el-form-item class="bottom-btn">
          <el-button type="primary" @click="onSubmit('form')" class="right"
            >保存</el-button
          >
          <el-button class="right" @click="backPage()">取消</el-button>
        </el-form-item>
      </el-form>

      <p v-if="$route.path.indexOf('allot') !== -1" class="borerd">
        <span></span>菜单权限
      </p>
      <div
        v-if="$route.path.indexOf('allot') !== -1"
        style="margin-bottom:100px;margin-top:20px;"
      >
        <menu-permission
          :data="permissionData"
          @change="changePermissions"
        ></menu-permission>
      </div>
    </div>
  </div>
</template>

<script>
import { getRole } from "@/utils/common";
import menuPermission from "@/components/menu-permission";
export default {
  props: {},
  components: {
    menuPermission,
  },
  data() {
    return {
      form: {
        name: "",
        desc: "",
        person: "",
        date: "",
      },
      now_user: 2, //0：普通用户，1：组织管理员，2：超级管理员
      permissionData: [],
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        desc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { max: 200, message: "长度小于200个字符", trigger: "blur" },
        ],
      },
      edit_flag:0,
      service_node:[],
      permission_arr:[]
    };
  },
  watch: {},
  computed: {},
  created() {
    this.get_now_page()
    console.log(this.$route);
  },
  mounted() {},
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.edit_flag == 0){
            this.add_role()
          }else if(this.edit_flag == 1){
            this.set_role()
          }else if(this.edit_flag == 3){
            this.deal_node(this.permissionData,this.permission_arr)
            console.log(this.permission_arr,this.service_node);
            var temp = this.compare_arr(this.permission_arr,this.service_node)
            var temp_arr = []
            if(temp[0].length){
              temp_arr.push(this.add_node(temp[0]))
            }
            temp[1].forEach(e => {
              temp_arr.push(this.delete_node(e))
            });
            Promise.all(temp_arr).then((result) => {
              this.get_now_page()
            }).catch((error) => {
              console.log(error)
            })
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    get_now_page(){
        console.log(this.$route);
        if(this.$route.path.indexOf('add')!==-1){
            this.edit_flag = 0 
        }
        if(this.$route.path.indexOf('edit')!==-1){
            this.edit_flag = 1
            this.getInfo()
        }
        if(this.$route.path.indexOf('detail')!==-1){
            this.edit_flag = 2
            this.getInfo()
        }
        if(this.$route.path.indexOf('allot')!==-1){
            this.edit_flag = 3
            this.getInfo()
            Promise.all([this.get_tree(), this.get_use_tree()]).then((result) => {
              console.log(result)
              this.permissionData = result[0].data.data
              this.service_node = result[1].data.data
              this.permission_arr = []
              this.deal_tree_data(result[0].data.data,result[1].data.data)
            }).catch((error) => {
              console.log(error)
            })
        }
    },
    backPage(){
        this.$router.back(-1)
    },
    add_role(){
      var temp = {
          "role_name":this.form.name,
          "detail":this.form.desc
      }
      this.$http
            .post(`/apaas/backmgt/role`,temp)
            .then(response => {
                console.log(response);
                let data = response.data.data
                if(response.data.success){
                  this.$message.success('新增成功')
                  this.backPage()
                }else{
                  this.$message.error('新增失败')
                }

            })
            .catch((response)=> {
                this.$message.error('新增失败')
            });
    },
    set_role(){
      var temp = {
        	"role_id":this.$route.params.id,
          "role_name":this.form.name,
          "detail":this.form.desc
      }
      this.$http
            .put(`/apaas/backmgt/role`,temp)
            .then(response => {
                console.log(response);
                let data = response.data.data
                if(response.data.success){
                  this.$message.success('修改成功')
                  this.backPage()
                }else{
                  this.$message.error('修改失败')
                }
            })
            .catch((response)=> {
                this.$message.error('修改失败')
            });
    },
    delete_node(val){
      return this.$http
            .post(`/apaas/backmgt/role/menuDel`,{
              	"role_id":this.$route.params.id,
                "menu_id":val
            })
            .then(response => {
                if(response.data.success){
                  this.$message.success('删除分配菜单成功')
                }else{
                  this.$message.error('删除分配菜单失败')
                }
            })
            .catch((response)=> {
                this.$message.error('删除分配菜单失败')
            });
    },
    add_node(arr){
      return this.$http
            .post(`/apaas/backmgt/role/menuAdd`,{
              	"role_id":this.$route.params.id,
                "menu_id":arr
            })
            .then(response => {
                if(response.data.success){
                  this.$message.success('分配菜单成功')
                }else{
                  this.$message.error('分配菜单失败')
                }
            })
            .catch((response)=> {
                this.$message.error('分配菜单失败')
            });
    },
    deal_node(data,data1){
      data.forEach(e => {
        if(e.selected){
          data1.push(e.menu_id)
        }
        if(e.Child){
          this.deal_node(e.Child,data1)
        }
      });
    },
    compare_arr(arr1,arr2){
      var nowtemp = {}
      var oldtemp = {}
      var increase = []
      var reduce = []
      arr1.forEach(e => {
        nowtemp[e] = e
      });
      arr2.forEach(e => {
        oldtemp[e.menu_id] = e.menu_id
      });
      for (const key in nowtemp) {
        if (!oldtemp.hasOwnProperty(key)) {
          increase.push(key)
        }
      }
      for (const key in oldtemp) {
        if (!nowtemp.hasOwnProperty(key)) {
          reduce.push(key)
        }
      }
      return [increase,reduce]

    },
    getInfo() {
      this.$http
            .get(`/apaas/backmgt/role/id/${this.$route.params.id}`)
            .then(response => {
                console.log(response);
                let data = response.data.data
                this.form={
                  name: data.role_name,
                  desc: data.detail,
                  person: data.create_user,
                  date: data.create_date,
                }
            })
            .catch((response)=> {
                
            });
    },
    get_tree() {
      return this.$http
            .get(`/apaas/backmgt/menu/list`)
    },
    get_use_tree() {
      return this.$http
            .get(`/apaas/backmgt/role/menu/id/${this.$route.params.id}`)
    },
    deal_tree_data(data1,data2){
      var temp = {}
      data2.forEach(e => {
        temp[e.menu_id] = e.menu_id
      });
      this.merge_data(data1,temp)
    },
    merge_data(data,temp){
      data.forEach(e => {
        if(temp[e.menu_id]){
          e.selected = true
        }
        if(e.Child){
          this.merge_data(e.Child,temp)
        }
      });
    },
    changePermissions(values) {
      console.log(values);
      console.log(this.permissionData);
    },
  },
};
</script>

<style>
.info_contain .el-input__inner {
  background-color: #f7f8f9;
  width: 1022px;
}
.info_contain .el-textarea__inner {
  background-color: #f7f8f9;
  width: 1022px;
}
.info_contain .el-input.is-disabled .el-input__inner {
  background-color: #e3e4e6;
}
</style>

<style scoped>
.detail_contain {
  width: 100%;
  padding: 0 20px;
  height: calc(100% - 55px);
}
.info_contain {
  padding: 25px 20px;
  background-color: #fff;
  width: 100%;
  box-shadow: 0px 3px 6px 0px #f4f7fc;
  border-radius: 12px;
  min-height: calc(100% - 20px);
  margin-bottom: 20px;
  position: relative;
}
.now_page_title {
  margin: 15px 0;
  color: #898d9e;
}
.now_page_title span {
  color: #242c43;
}
.formname {
  color: #58617a;
}
.right {
  float: right;
  margin-left: 20px;
}
.removepic {
  display: inline-block;
  margin-top: -40px;
  float: left;
  margin-left: 180px;
  width: 76px;
  height: 32px;
  background-color: #495feb;
  border-radius: 8px;
  line-height: 32px;
  text-align: center;
  color: #e6ebfe;
  cursor: pointer;
}
.edit_change {
  width: 100%;
  border-bottom: 2px solid #f4f7fc;
  overflow: hidden;
}
.edit_change_box {
  width: 163px;
  height: 48px;
  line-height: 48px;
  background-color: #e3e5ef;
  border-radius: 8px;
  color: #8890a7;
  text-align: center;
  float: left;
  margin-right: 20px;
  font-weight: 600;
  margin-bottom: 25px;
  font-size: 16px;
  cursor: pointer;
}
.edit_change_box img {
  vertical-align: -3px;
  margin-right: 5px;
}
.safe_title {
  width: 100%;
  height: 65px;
  line-height: 65px;
  border-bottom: 2px solid #f4f7fc;
}
.safe_select {
  float: left;
  width: auto;
  margin-right: 40px;
  height: 65px;
  cursor: pointer;
}
.safe_box_select {
  padding: 30px 10px 10px 10px;
  width: 100%;
  height: 100%;
}
.openbgc {
  width: 56px;
  height: 23px;
  background-image: url("~@/assets/imgs/btn_on_hov.png");
  background-size: contain;
  cursor: pointer;
}
.formtitle {
  color: #58617a;
  margin: 15px 0;
}

.savebtn {
  position: absolute;
  right: 20px;
  bottom: 20px;
  width: 278px;
  overflow: hidden;
}
.btnsty {
  width: 124px;
  height: 44px;
  line-height: 44px;
  background-color: rgba(195, 202, 248, 0.5);
  border-radius: 8px;
  color: rgba(15, 38, 131, 1);
  text-align: center;
  float: left;
  margin-right: 30px;
  cursor: pointer;
}
.savebtn .btnsty:nth-last-of-type(1) {
  margin-right: 0px;
  background-color: rgba(15, 38, 131, 1);
  color: rgba(248, 249, 253, 1);
}

.bottom-btn {
  position: absolute;
  bottom: 20px;
  right: 50px;
}
.borerd {
  color: #58617a;
  font-size: 16px;
}
.borerd span {
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #515fe7;
  border-radius: 2px;
  margin-right: 10px;
  vertical-align: -2px;
}
</style>
