<template>
  <div class="auto select-overspread" style="overflow-y: hidden">
    <validator name='v'>
      <ul class="nav nav-tabs">
        <p class="bg-info text-center" style="padding: 8px;">角色信息</p>

        <!--<li class="active"><a href="#">角色信息</a></li>-->
      </ul>
      <form class="form-horizontal" style="margin-top:20px;flex: 1;">
      <div class="row">
        <div class="col-sm-6"  :class="[$v.f_role_id.required ? 'has-error' : '']">
          <label class="font_normal_body" >角色编号</label>
          <input type="text"  v-model="model.f_role_id" @blur="validateDul" v-validate:f_role_id='{required: true }' class="input_search" style="width:60%" placeholder="角色编号" v-next-el="name">
        </div>

        <div class="col-sm-6"   :class="[$v.name.required ? 'has-error' : '']">
          <label for="f_adjustable_name" class="font_normal_body" >角色名称</label>
          <input type="text"  v-model="model.name"
                 v-validate:name="{required: true }" class="input_search" style="width:60%" placeholder="角色名称" v-el:name v-next-el="address">
        </div>


        <div class="col-sm-6"  :class="[$v.oname.required ? 'has-error' : '']">
          <label for="f_area" class="font_normal_body" >所属组织</label>
          <input type="text" v-model="model.oname"
                 v-validate:oname="{required: true }" class="input_search" style="width:45%" placeholder="所属组织" readonly >
          <button type="button" class="btn button_new btn-lg" style="width:13%">
            <span class="glyphicon glyphicon-search" @click="openOrgModal"></span>
          </button>
        </div>
        <div class="col-sm-6"></div>
      </div>
      </form>

      <div style="text-align:right;height:auto;margin-top:6px;">
        <button class="button_search button_spacing" @click="confirm()" :disabled='!$v.valid'>确认</button>
        <button class="button_clear button_spacing" @click="deleteRole()" v-if="model.id">删除</button>
        <button class="button_new button_spacing" @click="close()">取消</button>
      </div>
      <organization-modal :show.sync="orgModalShow" style="float: left" @depart="getDepart"></organization-modal>
      <button  class="button_search button_spacing " style="width:80px" @click="permissionsShow('func')"  type="button">
        <span class="glyphicon glyphicon-cog">功能权限</span>
      </button>
      <button  class="button_search button_spacing" style="width:80px" @click="permissionsShow('role')"  type="button">
        <span class="glyphicon glyphicon-cog">下属角色</span>
      </button>
    </validator>
    <func-permissions v-show="funcPermissionsShow" :data="data" :roots.sync="funcPermissions"></func-permissions>

    <role-permissions v-show="rolePermissionsShow" :data="data" :roots.sync="rolePermissions" :is-edit="isEdit"></role-permissions>
  </div>
</template>

<script>

  import RolePermissions from "../common/RolePermissions";
  import FuncPermissions from "../common/FuncPermissions";
  export default {
    components: {RolePermissions, FuncPermissions},
    title: '添加角色',
    data () {
      return {
        model: {
          id: '',
          name: '',
          f_role_id:'',
          parentid: '',
          selfid: '',
          f_description: '',
          resourcetype: 'role',
          oname: ''
        },

        // 所属组织
        orgModalShow: false,

        funcPermissionsShow: true,
        funcPermissions: [],

        rolePermissionsShow: false,
        rolePermissions: [],
        // 功能权限
        permissionsType: 'function'

      }
    },
    props: ['data', 'isEdit'],
    ready () {
      this.model = Object.assign({}, this.model, this.data)
    },
    watch: {
      'data' (val) {
        if (val) {
          this.model = Object.assign({}, this.model, this.data)
        } else {
          // 初始化角色组件
          // TODO
          this.initModel()
        }
      }
    },
    methods: {
      initModel () {
        this.model = {
          id: '',
          name: '',
          f_role_id:'',
          parentid: '',
          selfid: '',
          f_description: '',
          resourcetype: 'role',
          oname: ''
        }
      },
      permissionsShow (val) {
        if (val === 'func') {
          this.funcPermissionsShow = true
          this.rolePermissionsShow = false
        } else {
          this.rolePermissionsShow = true
          this.funcPermissionsShow = false
        }
      },
      async confirm () {
    // 保存用户
    console.log('要保存用户了', this.data, this.model, this.permissions)
    // 保存角色
    this.model.f_create_date = this.$login.toStandardTimeString()
    let saveRole = await this.$resetpost('rs/data/save',{data:this.model},{resolveMsg: null, rejectMsg: '保存角色出错！！'})

    let roleId = this.model.id ? this.model.id : saveRole.data + ''
    // 保存权限
    console.log('开始保存权限', roleId)

    // 组织角色权限数据
    let param = {
      parentid: roleId,
      licenses:[]
    }

    this.rolePermissions.forEach((item) => {
      let license = {}
      license.isinherit = "是"
    license.byisinherit = "否"
    license.resourceresult = ""
    license.parentid = roleId
    license.resourceid = roleId
    license.byresourceid = item.id
    license.righttype = 'role'
    license.byresourceresult = ''
    license.licensepolicy = ''
    param.licenses.push(license)
  })

    this.funcPermissions.forEach((item) => {
      let license = {}
      license.isinherit = "是"
    license.byisinherit = "是"
    license.resourceresult = ""
    license.parentid = roleId
    license.resourceid = roleId
    license.byresourceid = item.id
    license.righttype = 'function'
    license.byresourceresult = ''
    license.licensepolicy = ''
    param.licenses.push(license)
  })

    await this.$resetpost('rs/license/save', param, {resolveMsg: '保存成功', rejectMsg: '保存权限失败！请您重试！！'})
    this.$dispatch('refresh')
  },
  close () {
    this.$dispatch('refresh')
  },
  async deleteRole () {
    let res = await this.$showMessage(`确认要删除角色: ${this.model.name} 吗？`, ['confirm', 'cancel'])
    if (res === 'confirm') {
      console.log('开始删除', this.model)
      let param = []
      param.push(this.model)
      try {
        await this.$resetpost('rs/data/delete', {data: param}, {resolveMsg: '删除成功！！', rejectMsg: null})
      } catch (error) {
        this.$showAlert(error.data, 'danger', 0)
      }
      this.$dispatch('refresh')
    }
  },
  openOrgModal () {
    this.orgModalShow = true
  },
  getDepart (val) {
    this.model.oname = val.name
    this.model.parentid = val.id
  },
  async validateDul () {
    // 判断是修改还是新增
    if (this.data) {
      if (this.model.f_role_id !== this.data.f_role_id ) {
        let validate = await this.$resetpost('rs/sql/ldap_getAllRole', {data: {condition: `f_role_id = '${this.model.f_role_id}'`}}, {rejectMsg: '验证角色编号重复出错！！', resolveMsg: null})
        if (validate.data.length > 0) {
          this.model.f_role_id = this.data.f_role_id
          this.$showAlert('编号重复，请重新输入！！', 'warning', 2000)
        }
      }
    } else {
      let validate = await this.$resetpost('rs/sql/ldap_getAllRole', {data: {condition: `f_role_id = '${this.model.f_role_id}'`}}, {rejectMsg: '验证角色编号重复出错！！', resolveMsg: null})
      if (validate.data.length > 0) {
        this.model.f_role_id = ''
        this.$showAlert('编号重复，请重新输入！！', 'warning', 2000)
      }
    }
  }
  }
  }

</script>

