<template>
  <div class="auto">
    <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_dep_id.required ? 'has-error' : '']">
            <label class="control-label">部门编码</label>
            <input type="text"  v-model="model.f_dep_id" v-validate:f_dep_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="部门名称">
          </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>
        <div class="row">
          <div class="col-sm-12 form-group form-input-group">
            <label for="f_area" class="control-label">备注</label>
            <textarea class="form-control" rows="3" v-model="model.f_remark" placeholder="备注"></textarea>
          </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="deleteDep()" v-if="model.id">删除</button>
        <button class="btn btn-default" @click="clear()">取消</button>
      </div>
    </validator>
    <organization-modal :show.sync="orgModalShow" @depart="getDepart"></organization-modal>

    <button  class="btn btn-success " @click="permissionsShow('data')"  type="button">
      <span class="glyphicon glyphicon-cog">数据权限</span>
    </button>
    <button  class="btn btn-success " @click="permissionsShow('role')"  type="button">
      <span class="glyphicon glyphicon-cog">角色权限</span>
    </button>
    <organization-permission  v-show="dataPermissionsShow" :data="data" :orgs.sync="dataPermissions"></organization-permission>
    <!--<role-permissions v-if="dataPermissionsShow" :data="data" :type.sync="permissionType" :roots.sync="dataPermissions" :need-init="dataInit"></role-permissions>-->
    <role-permissions v-show="rolePermissionsShow" :data="data" :type.sync="permissionType" :roots.sync="rolePermissions" :need-init="roleInit"></role-permissions>
  </div>
</template>
<script>

  import RolePermissions from "../common/RolePermissions"

  export default {
    components: {RolePermissions},
    data () {
      return {
        model:{
          loginid: this.$login.f.id,
          f_description: '',
          id: '',
          selfid: '',
          tablename: 't_department',
          entitytype: 't_department',
          position: '1',
          resourcetype: 'department',
          f_dep_id: '',
          f_remark: '',
          oname: '',
          name: '',
          parentid: ''
        },
        // 组织树模态框
        orgModalShow: false,

        permissionType: 'role',
        dataPermissionsShow: true,
        dataPermissions: [],

        rolePermissionsShow: false,
        rolePermissions: [],

        // 存储当前该部门具有的权限
        permissionsSwitch: true,

        dataInit: true,
        roleInit: true
      }
    },
    props: ['data'],
    ready () {
      this.model = Object.assign({}, this.model, this.data)
    },
    watch: {
      'data' (val) {
        if (val) {
          this.permissionsSwitch = true
          this.model = Object.assign({}, this.model, this.data)
        } else {
          this.initModel()
        }
      }
    },
    methods: {
      initModel () {
        this.model = {
          loginid: this.$login.f.id,
          f_description: '',
          id: '',
          selfid: '',
          tablename: 't_department',
          entitytype: 't_department',
          position: '1',
          resourcetype: 'department',
          f_dep_id: '',
          f_remark: '',
          oname: '',
          name: '',
          parentid: ''
        }
        this.dataPermissions = []
        this.rolePermissions = []
      },
      async confirm () {
        try {
          // 保存部门 资源服务的特殊保存程序，这里去掉除部门表外的其他字段
          delete this.model.onumber
          let saveDep = await this.$resetpost('rs/data/save', {data: this.model}, {resolveMsg: '保存部门成功', rejectMsg: '保存部门失败'})
          // 保存部门权限
          let depId = saveDep.data + ''

          // 将此次添加的部门添加到数据权限中
          this.validateDataPermissions(depId)

          // 组织角色权限数据
          let param = {
            parentid: depId,
            licenses:[]
          }
          this.dataPermissions.forEach((item) => {
            let license = {}
            license.isinherit = "是"
            license.byisinherit = "是"
            license.resourceresult = ""
            license.parentid = depId
            license.resourceid = depId
            license.byresourceid = item.id
            license.righttype = ''
            license.byresourceresult = ''
            license.licensepolicy = ''
            param.licenses.push(license)
          })
          this.rolePermissions.forEach((item) => {
            let license = {}
            license.isinherit = "是"
            license.byisinherit = "是"
            license.resourceresult = ""
            license.parentid = depId
            license.resourceid = depId
            license.byresourceid = item.id
            license.righttype = ''
            license.byresourceresult = ''
            license.licensepolicy = ''
            param.licenses.push(license)
          })

          console.log('保存权限数据', param)

          await this.$resetpost('rs/license/save', param, {resolveMsg: '保存成功', rejectMsg: '保存权限失败！请您重试！！'})

          this.$dispatch('refresh')
        } catch (error) {
          this.$showAlert(error, 'danger', 0)
        }
      },
      validateDataPermissions (val) {
        let temp = false
        this.dataPermissions.forEach((res) => {
          if (res.id == val) {
            temp = true
          }
        })
        if (!temp) {
          // 说明数据权限中不存在当前选中的部门, 添加该部门
          this.dataPermissions.push({id: val})
          // console.log('要加如了')
        }
      },
      openOrgModal () {
        this.orgModalShow = true
      },
      permissionsShow (val) {
        if (val === 'data') {
          this.rolePermissionsShow = false
          this.dataPermissionsShow = true
        } else {
          this.dataPermissionsShow = false
          this.rolePermissionsShow = true
        }
        if (this.rolePermissions.length > 0) {
          this.roleInit = false
        }
        // if (this.dataPermissions.length > 0) {
        //   this.dataInit = false
        // }
        // this.permissionType = val === 'data' ? 'department' : 'role'
      },
      getDepart (val) {
        this.model.oname = val.name
        this.model.parentid = val.id
      },
      parentidSave () {
        this.$resetpost('rs/sql/ldap_getAllDep', {data: {condition: "d.parentid = '" + this.model.parentid + "' and d.name = '" + this.model.name + "'"}}, {rejectMsg: null, resolveMsg: null}).then((res) => {
          if (res.data.length > 0) {
            this.$showAlert('此部门名称已存在，请核实后重新输入！！', 'warning', 5000)
          } else {
            this.f_dep_id = this.listinfo.f_dep_id
          }
        }).catch((error) => {
          if (error.status) {
            this.$warn(`加载数据出错, ${JSON.stringify(error)}`)
            return
          }
        })
      },
      clear () {
        this.$dispatch('refresh')
      },
      async deleteDep () {
        let res = await this.$showMessage(`确认要删除部门: ${this.model.name} 吗？`, ['confirm', 'cancel'])
        if (res === 'confirm') {
          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')
        }
      },
      dataPermissionsById (val) {
        let temp = false
        this.dataPermissions.forEach((item) => {
          if (val == item.id) {
            temp = true
            return
          }
        })
        return temp
      }
    },
    events: {
      'getlicense' (val) {
        console.log('获取的权限。。', val)
        // 此时数据权限dataPermission已加载 将rolePermission进行复制
        if (this.permissionsSwitch) {
          this.permissionsSwitch = false
          val.forEach((res) => {
            if (!this.dataPermissionsById(res.byresourceid)) {
              this.rolePermissions.push({id: res.byresourceid})
            }
          })
        }
      }
    }
  }
</script>
<style>

</style>
