<template>
  <div class="auto select-overspread" style="overflow-y: hidden">
    <validator name='v'>
      <ul class="nav nav-tabs">
        <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 form-group form-input-group"  :class="[$v.f_role_id.required ? 'has-error' : '']">
            <label class="control-label">角色编号</label>
            <input type="text"  v-model="model.f_role_id" v-validate:f_role_id='{required: true }' class="form-control" placeholder="角色编号" v-next-el="name">
          </div>

          <div class="col-sm-6 form-group form-input-group"   :class="[$v.name.required ? 'has-error' : '']">
            <label for="f_adjustable_name" class="control-label">角色名称</label>
            <input type="text"  v-model="model.name"
                   v-validate:name="{required: true }" class="form-control" placeholder="角色名称" v-el:name v-next-el="address">
          </div>
        </div>
        <div class="row">
          <div class="col-sm-6 form-group form-input-group"  :class="[$v.oname.required ? 'has-error' : '']">
            <label for="f_area" class="control-label">所属组织</label>
            <input type="text" v-model="model.oname"
                   v-validate:oname="{required: true }" class="form-control" placeholder="所属组织" readonly >
            <button type="button" class="btn btn-default btn-lg">
              <span class="glyphicon glyphicon-search" @click="openOrgModal"></span>
            </button>
          </div>
        </div>
      </form>
      <div style="text-align:right;height:auto;margin-top:6px;">
        <button class="btn btn-success" @click="confirm()" :disabled='!$v.valid'>确认</button>
        <button class="btn btn-danger" @click="deleteRole()" v-if="model.id">删除</button>
        <button class="btn btn-default" @click="close()">取消</button>
      </div>
      <organization-modal :show.sync="orgModalShow" @depart="getDepart"></organization-modal>
      <div class="auto" style="margin-top: 5%;">
        <role-permissions :data="data" :roots.sync="permissions" :is-edit="isEdit"></role-permissions>
      </div>
    </validator>
  </div>
</template>

<script>

  import FunctionEdit from "../Authorization/FunctionEdit";
  import RolePermissions from "../common/RolePermissions";

  export default {
    components: {RolePermissions, FunctionEdit},
    title: '添加角色',
    data () {
      return {
        model: {
          id: '',
          name: '',
          f_role_id:'',
          parentid: '',
          selfid: '',
          f_description: '',
          resourcetype: 'role',
          oname: ''
        },

        // 所属组织
        orgModalShow: false,

        // 功能权限
        permissionsType: 'function',
        permissions: []
      }
    },
    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: ''
        }
      },
      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.permissions.forEach((item) => {
          let license = {}
          license.isinherit = "是"
          license.byisinherit = "是"
          license.resourceresult = ""
          license.parentid = roleId
          license.resourceid = roleId
          license.byresourceid = item.id
          license.righttype = ''
          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
      }
    }
  }

</script>
