<template>
  <div class="companyAddress-wrap common-set-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="roleName" class="">
            <!-- <el-input v-model="ruleForm.name" disabled placeholder="" class="w-380"></el-input> -->
            <limitInput
              :inputWidth="500"
              :inputValue.sync="ruleForm.roleName"
              :holder="'请输入角色名称'"
              :maxLength="20">
            </limitInput>
          </el-form-item>
          <el-form-item label="角色说明" prop="remark" class="">
            <limitTextarea
              :inputWidth="500"
              :inputValue.sync="ruleForm.remark"
              :holder="'请输入角色说明'"
              :maxLength="50">
            </limitTextarea>
          </el-form-item>
          <el-form-item label="菜单权限" prop="leftChecked" class="">
            <el-transfer
              class="el-transfer-check"
              :titles="['一级权限', '二级权限']"
              :left-default-checked="ruleForm.leftChecked"
              :data="ruleForm.left"
              @left-check-change="leftChange">
              <span slot-scope="{ option }">{{ option.label }}</span>
            </el-transfer>
            <el-transfer
              class="el-transfer-check"
              :titles="['二级权限', '二级权限']"
              :left-default-checked="ruleForm.rightChecked"
              :data="ruleForm.right"
              @left-check-change="rightChange">
              <span slot-scope="{ option }">{{ option.label }}</span>
            </el-transfer>
          </el-form-item>
          <!-- <el-form-item label="应用权限" prop="" class="">
            <el-transfer
              :titles="['一级权限', '二级权限']"
              :left-default-checked="ruleForm.leftCheckedApp"
              :data="ruleForm.leftApp"
              @left-check-change="leftChangeApp">
            </el-transfer>
            <el-transfer
              :titles="['二级权限', '二级权限']"
              :left-default-checked="ruleForm.rightCheckedApp"
              :data="ruleForm.rightApp"
              @left-check-change="rightChangeApp">
            </el-transfer>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
  </div>
</template>
<script>
import navCrumb from '@/components/nav/nav.vue';
import limitInput from '@/components/limit-input.vue';
import limitTextarea from '@/components/limit-textarea.vue';

import strLength from '@/common/js/strlen';
import showMsg from '@/common/js/showmsg';
import errMsg  from '@/common/js/error';
import { _debounce } from "@/common/js/public";
import { getRequest, postRequest, postJson, postForm } from '@/api/api';
export default {
  name: "addAdminRole",
  data() {

    return {
      // 面包屑参数
      navpath: [
        {
          name: '首页',
          path: '/index',
          relocation: true
        },
        {
          name: '设置',
          path: '/companyAddress'
        },
        {
          name: '设置子管理员',
          path: '/setChildAdmin'
        },
        {
          name: '新增管理员角色',
          path: ''
        }
      ],

      ruleForm: {
        roleId: '',
        roleName: '企业管理员',
        remark: '角色说明',
        leftChecked: [],
        left: [
          // {
          //   key: 'index',
          //   label: '首页'
          // },
          // {
          //   key: 'center',
          //   label: '审核中心'
          // },
          // {
          //   key: 'set',
          //   label: '设置'
          // }
        ],
        rightChecked: [],
        right: [
          // {
          //   key: 'index',
          //   label: '首页'
          // },
          // {
          //   key: 'center',
          //   label: '审核中心'
          // },
          // {
          //   key: 'set',
          //   label: '设置'
          // }
        ],
        leftCheckedApp: [],
        leftApp: [
          {
            key: 'index',
            label: '首页'
          },
          {
            key: 'center',
            label: '审核中心'
          },
          {
            key: 'set',
            label: '设置'
          }
        ],
        rightCheckedApp: [],
        rightApp: [
          {
            key: 'index',
            label: '首页'
          },
          {
            key: 'center',
            label: '审核中心'
          },
          {
            key: 'set',
            label: '设置'
          }
        ]
      },
      rules: {
        roleName: [
          { required: true, message: '请填写角色名称', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请填写角色说明', trigger: 'change' }
        ],
        leftChecked: [
          { required: true, message: '请选中菜单权限', trigger: 'change' }
        ],
      }

    }
  },
  computed: {

  },
  methods: {
    /**
     * 保存
     */
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate((valid) => {
        console.log(valid)
        if (valid) {
          let data = [];

          that.ruleForm.left.forEach(function(ele,index){
            // console.log(ele.check)
            if (!!ele.check) {
              data.push({rightId: ele.rightId})
              ele.children.forEach(function(el,key){
                if (!!el.check) {
                  data.push({rightId: el.rightId})
                }
              })
            }
          })
          // console.log(that.ruleForm.left,data)
          that.postSave(data)
        } else {

          return false;
        }
      });
    },500),

    /**
     * 保存---api
     */
    postSave(data) {
      const that = this;
      const para = {
        data: JSON.stringify(data),
        roleId: that.ruleForm.roleId,
        roleName: that.ruleForm.roleName,
        remark: that.ruleForm.remark
      }

      postRequest('/haoban-manage-web/save-role',para)
      .then((res) => {
        // console.log(res,res.data,res.data.errorCode)
        var resData = res.data
        if (resData.errorCode == 1) {
          showMsg.showmsg('操作成功','success')
          return;
        }

        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    /**
     * 获取菜单列表
     */
    getMenuList() {
      const that = this;
      const para = {

      }

      postRequest('/haoban-manage-web/menu-list',para)
      .then((res) => {
        // console.log(res,res.data,res.data.errorCode)
        var resData = res.data
        if (resData.errorCode == 1) {

          if (!resData.result) {
            that.$message.error({message: '菜单列表为空'})
            return;
          }
          that.ruleForm.left = that.treeData(resData.result)
          // that.ruleForm.right = that.ruleForm.left[0].children
          that.ruleForm.left.forEach(function(ele,index){
            ele.key = ele.rightId;
            ele.label = ele.rightName;
            ele.check = false;
            if (!!ele.children && !!ele.children.length) {
              ele.children.forEach(function(el,key){
                el.key = el.rightId;
                el.label = el.rightName;
                el.check = false;
              })
            }
          })

          that.ruleForm.right = that.ruleForm.left[0].children;
          if (!!that.ruleForm.roleId) {
            that.getRoleDetail(that.ruleForm.roleId)
          }

          return;
        }

        errMsg.errorMsg(resData)

      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    /**
     * 简单数组-->父子数组对象
     */
    treeData(data){
      let tree = data.filter((father)=>{                  //循环所有项
        let branchArr = data.filter((child)=>{
          return father.haobanMenuRightId == child.parentRightId;    //返回每一项的子级数组
        });
        if(branchArr.length>0){
          father.children = branchArr;    //如果存在子级，则给父级添加一个children属性，并赋值
        }
        return father.parentRightId == -1;        //返回第一层
      });
      return tree;
    },

    /**
     * 获取角色详情
     */
    getRoleDetail(roleId) {
      const that = this;
      const para = {
        roleId: roleId
      }

      postRequest('/haoban-manage-web/role-detail',para)
      .then((res) => {
        // console.log(res,res.data,res.data.errorCode)
        var resData = res.data
        if (resData.errorCode == 1) {
          // showMsg.showmsg('操作成功','success')
          that.ruleForm.roleId = resData.result.role.roleId;
          that.ruleForm.roleName = resData.result.role.roleName;
          that.ruleForm.roleCode = resData.result.role.roleCode;
          that.ruleForm.remark = resData.result.role.remark;

          let list = that.ruleForm.right.map(item=>item.rightId);
          let rightChecked = []
          resData.result.menuRightList.forEach(function(ele,index){
            if (list.includes(ele.rightId)) {
              rightChecked.push(ele.rightId)
            }
          })
          that.ruleForm.rightChecked = rightChecked;

          let newList = that.treeData(resData.result.menuRightList)
          /*newList.forEach(function(ele,index){
            ele.key = ele.rightId;
            ele.label = ele.rightName;
            ele.check = true;
            if (!!ele.children && !!ele.children.length) {
              ele.children.forEach(function(el,key){
                el.key = el.rightId;
                el.label = el.rightName;
                el.check = true;
              })
            }
          })*/
          // console.log(JSON.stringify(newList))

          // 设置 左侧/右侧 选中
          that.ruleForm.leftChecked = newList.map(item=>item.rightId);
          return;
        }
        errMsg.errorMsg(resData)
      })
      .catch(function (error) {
        console.log(error);

        that.$message.error({
          duration: 1000,
          message: error.message
        })
      });
    },

    /**
     * 选择
     */
    leftChange(value, direction) {
      const that = this
      that.ruleForm.leftChecked = value;
      let selFlag = value.includes(direction[0]); // true: 选中；false: 未选
      value.includes(direction[0])? replaceData(): replaceData();

      function replaceData(){
        that.ruleForm.right = []
        that.ruleForm.left.forEach(function(ele,index){
          // 确定选择哪一个一级菜单，设置右侧数据
          if(ele.rightId.includes(direction[0])) {
            // 未选择设置 check
            if (!selFlag) {
              ele.check = false;
            }else {
              ele.check = true;
            }
            ele.children.forEach(function(el,key){
              that.ruleForm.right.push(el)
            })
          }
        })
      }
      // console.log(that.ruleForm.right)
      // 设置右侧已选
      that.ruleForm.rightChecked = that.ruleForm.right.map(item=>{
        if(item.check===true){
          return item.rightId
        }
      })
      // console.log( that.ruleForm.rightChecked )
    },

    /**
     * 选择
     */
    rightChange(value, direction) {
      const that = this;
      console.log(value, direction)
      let selFlag = value.includes(direction[0]); // true: 选中；false: 未选
      that.ruleForm.rightChecked = value;

      that.ruleForm.left.forEach(function(ele,index){
        ele.children.forEach(function(el,key){
          // 确定选择哪一个一级菜单，设置右侧数据
          if(el.rightId.includes(direction[0])) {
            // 未选择设置 check
            if (!selFlag) {
              el.check = false;
            }else {
              el.check = true;
            }
          }
        })
      })
    },

    /**
     * 选择
     */
    leftChangeApp(value, direction) {
      console.log(value, direction)
    },

    /**
     * 选择
     */
    rightChangeApp(value, direction) {
      console.log(value, direction)
    },
  },
  mounted() {
    const that = this
    console.log(that.$route.query)
    that.getMenuList();
    if (!!that.$route.query.hasOwnProperty('roleId')) {
      that.ruleForm.roleId = that.$route.query.roleId;
      that.navpath[3].name= '管理员角色'
      // that.getRoleDetail(that.ruleForm.roleId)
    }

  },
  components: {
    navCrumb,
    limitInput,
    limitTextarea
  }
}

</script>
<style lang="less" scoped>
.right-content {
  /*width: 100%;*/
  padding: 24px;
  min-height: calc(100% - 240px);

  .right-box {
    background: #fff;
    padding: 24px;
    min-height: 500px;

    h2 {
      font-size: 16px;
      color: #303133;
    }

    p {
      font-size: 14px;
      color: #909399;
    }

    .m-t-24 {
      margin-top: 24px;
    }

    .w-380 {
      width: 380px;
    }

    .el-transfer {
      display: inline-block;
      vertical-align: top;
      /deep/ .el-transfer-panel:last-child {
        display: none;
      }
      /deep/ .el-transfer__buttons {
        padding: 0 5px;
        .el-button {
          display: none;
        }
      }
      &.el-transfer-check {
        /deep/ .el-transfer-panel__item {
          &:hover {
            background: #F5F7FA;
          }
          &:active {
            background: #F5F7FA;
          }
        }
      }
    }
  }
}
</style>
