<template>
  <div class="auto select-overspread">
    <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;" v-show="!depPermissionShow">

        <div class="col-sm-6"  :class="[$v.userid.required ? 'has-error' : '']">
          <label class="font_normal_body" >员工编号</label>
          <input type="text"  v-model="model.userid" @blur="validateDul('userid')" v-validate:userid='{required: true }' class="input_search" style="width:60%" placeholder="员工编号" v-next-el="name">
        </div>
        <div class="col-sm-6"  :class="[$v.f_name.required ? 'has-error' : '']">
          <label class="font_normal_body" >员工姓名</label>
          <input type="text"  v-model="model.name" v-validate:f_name='{required: true }' class="input_search" style="width:60%" placeholder="员工姓名" v-next-el="name">
        </div>

        <div class="col-sm-6"   :class="[$v.ename.required ? 'has-error' : '']">
          <label class="font_normal_body" >&nbsp;&nbsp;&nbsp;登录名</label>
          <input type="text"  v-model="model.ename"
                 v-validate:ename="{required: true }" @blur="validateDul('ename')" class="input_search" style="width:60%" placeholder="登录名">
        </div>
        <!--修改用户-->
        <div class="col-sm-6"   v-if="model.id.length>0" :class="[$v.password.required ? 'has-error' : '']">
          <label  class="font_normal_body" >登录密码</label>
          <input type="text" v-model="valueText"
                 disabled
                 v-validate:password="{required: true }"
                 class="input_search" style="width:45%" placeholder="登录密码">
          <button type="button" class="btn button_new btn-lg" style="width:13%" @click="initpassword">
            <span class="glyphicon glyphicon-repeat" ></span>
          </button>
        </div>
        <!--新增用户-->
        <div class="col-sm-6"   v-if="model.id.length==0" :class="[$v.password.required ? 'has-error' : '']">
          <label  class="font_normal_body" >登录密码</label>
          <input type="text" v-model="valueText"
                 @keyup="keyUp(valueText,$event)"
                 @keydown="keyDown($event)" @input="input"
                 v-validate:password="{required: true }"
                 class="input_search" style="width:60%" placeholder="登录密码">
        </div>
        <div class="col-sm-6" >
          <label  class="font_normal_body" >&nbsp;&nbsp;&nbsp;电话&nbsp;&nbsp;&nbsp;</label>
          <input type="text" v-model="model.f_user_telephone" class="input_search" style="width:60%" placeholder="电话">
        </div>
        <div class="col-sm-6">
          <label  class="font_normal_body" >&nbsp;&nbsp;&nbsp;状态&nbsp;&nbsp;&nbsp;</label>
          <v-select :value.sync="model.state"
                    :options='userStates'
                    :value-single="true"
                    placeholder='状态'
                    close-on-select
                    v-model='model.state'></v-select>
        </div>

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

        <div class="col-sm-6" >
          <label class="font_normal_body" >&nbsp;&nbsp;&nbsp;性别&nbsp;&nbsp;&nbsp;</label>
          <v-select
            v-model="model.f_sex"
            placeholder='请选择'
            :value.sync="model.f_sex"
            :value-single="true"
            :options='getsexs'
            close-on-select>
          </v-select>
        </div>
        <div class="col-sm-6">
          <label class="font_normal_body" >&nbsp;&nbsp;&nbsp;年龄&nbsp;&nbsp;&nbsp;</label>
          <input type="number" v-model="model.f_age" class="input_search" style="width:60%" placeholder="年龄">
        </div>

        <div class="col-sm-6" >
          <label class="font_normal_body" >身份证号</label>
          <input type="text" v-model="model.f_idnumber" class="input_search" style="width:60%" placeholder="身份证号">
        </div>

        <div class="col-sm-12">
          <label  class="font_normal_body" style="margin-bottom: 25%">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
          <textarea class="ver-textarea" style="width:80%" rows="4" v-model="model.f_description" placeholder="备注"></textarea>
        </div>

      </form>
      <div class="row">
        <div style="float:right;">
          <button class="button_new button_spacing" style="width: max-content" @click="permissionOper()" v-if="!depPermissionShow">组织授权</button>
          <button class="button_search button_spacing" style="width: max-content" @click="permissionOper()" v-if="depPermissionShow">返回用户信息</button>
          <button class="button_search button_spacing" @click="confirm()" :disabled='!$v.valid' v-if="!depPermissionShow">确认</button>
          <button class="button_clear button_spacing" @click="deleteStaff()" v-if="model.id">删除</button>
          <button class="button_clear button_spacing" @click="close()" v-if="!depPermissionShow">取消</button>
        </div>
      </div>
    </validator>

    <department-modal :show.sync="orgModalShow" :data="data" @depart="getDepart"></department-modal>
    <role-permissions-modal v-if="roleModalShow" :show.sync="roleModalShow" :data="data" @role="getRoles"></role-permissions-modal>
    <department-permission v-show="depPermissionShow" :user="model" :data="data" :orgs.sync="dataPermissions"></department-permission>
  </div>

</template>

<script>
  import co from 'co'
  let passwodGen = function * (self) {
    var json={
      password : self.model.password ,
      newpassword : 1? '000000':self.$login.f.initpassword,
      affirmpassword : 1? '000000':self.$login.f.initpassword,
      ename : self.model.ename
    }
    let res = self.$resetpost('/rs/user/modifypwd', {data: json })
    console.log(res)
  }
  export default {
    title: '添加人员',
    data () {
      return {
        valueText: '',
        valueTrea:[],
        //真实密码
        isCtrl:'',
        flag:true,
        valueShow:'',
        model: {
          loginid: this.$login.f.id,
          id: '',
          name: '',
          ename: '',
          password: '',
          parentid: '',
          state: '在职',
          f_sex: '男',
          f_age: '',
          f_idnumber: '',
          f_department_name:'', // 用作显示
          f_role_name: '',
          rolelist: [],
          rolestr: '',
          resourcetype: 'user',
          f_description: '',
          f_user_telephone: ''
        },
        // 组织树模态框
        orgModalShow: false,

        // 角色模态框
        roleid: null,
        roleModalShow: false,

        // 权限
        depPermissionShow: false,
        dataPermissions: [],

        userStates: [{label:'在职', value: '在职'}, {label:'离职', value: '离职'}],
        getsexs: [{label:'男', value: '男'}, {label:'女', value: '女'}]
      }
    },
    props: ['data'],
    ready () {
      this.init()
    },
    watch: {
      'data' (val) {
        this.init()
      }
    },
    methods: {
      async initpassword () {
        let res = await this.$showMessage(`确认初始化该员工: ${this.model.name} 的密码吗？`, ['confirm', 'cancel'])
        if (res === 'confirm') {
          try {
            var json={
              password : this.model.password ,
              newpassword : 1? '000000':this.$login.f.initpassword,
              affirmpassword : 1? '000000':this.$login.f.initpassword,
              ename : this.model.ename
            }
            let res = this.$resetpost('/rs/user/modifypwd', {data: json })
          } catch (error) {
            this.$showAlert(error.data, 'danger', 0)
          }
          this.$dispatch('refresh')
        }
      },
      keyDown(event) {
        //ctrl复制粘贴事件（true|false）
        this.isCtrl = event.ctrlKey;
        if(event.keyCode==8){
          this.flag=false;
          this.valueTrea=this.valueTrea.join().replace(/,/g, "").split('');
          var $num=event.target.selectionEnd-event.target.selectionStart;
          if($num==1 || $num==0){
            var index= event.target.selectionStart;
            this.valueTrea.splice(index-1,1);
          }else{
            this.valueTrea.splice(event.target.selectionStart,$num);
          }
          this.model.password = this.valueTrea.join().replace(/,/g, "") // 输入的明文
        }else{
          this.flag=true;
        }
      },
      input() {
        if(this.flag && this.valueText.replace(/\*/g, "") !=''){
          this.passwordText()
        }
      },
      keyUp() {
        if (this.isCtrl && !this.valueCtrl) {
          this.valueCtrl = this.valueText //  粘贴的明文
          this.model.password = ''
        }
        this.passwordText()
      },
      passwordText(){
        this.valueTrea.push(this.valueText.replace(/\*/g, ""));
        this.model.password=this.valueTrea.join().replace(/,/g, "");
        this.valueText = this.valueText.replace(/./g, '*'); // 替换成密文*号
      },
      init() {
        if (this.data) {
          this.model = Object.assign({}, this.model, this.data)
          if (this.model.roles) {
            this.model.rolelist.push({id: this.model.roles})
          }
          if (!this.model.state) {
            this.model.state = '在职'
          }
          if(this.model.password){
            this.valueText=this.model.password
            this.input()
          }
        } else {
          this.initModel()
        }
      },
      initModel() {
        // 处理角色默认数据
        this.valueText= '',
          this.valueTrea= [],
          //真实密码
          this.isCtrl= '',
          this.flag= true,
          this.valueShow= '',
          this.model = {
            loginid: this.$login.f.id,
            id: '',
            name: '',
            ename: '',
            password: '',
            parentid: '',
            state: '在职',
            f_sex: '男',
            f_age: '',
            f_idnumber: '',
            f_department_name:'', // 用作显示
            f_role_name: '',
            rolelist: [],
            rolestr: '',
            resourcetype: 'user',
            f_description: '',
            f_user_telephone: ''
          }
      },
      permissionOper () {
        this.depPermissionShow = !this.depPermissionShow
      },
      async confirm () {
        // 验证是否包含数据权限，
        if (this.dataPermissions.length == 0) {
          this.$showAlert('请对该人员进行组织授权!!', 'warning', 2000)
          return
        }
        // 保存用户
        try {
          let res = await this.$resetpost('rs/data/save', {data: this.model})
          console.log('保存用户。。', res)
          // 保存部门权限
          let userId = res.data + ''
          // 组织角色权限数据
          let param = {
            parentid: userId,
            loginid: this.$login.f.id,
            licenses:[]
          }
          this.dataPermissions.forEach((item) => {
            let license = {}
            license.isinherit = "是"
            license.byisinherit = item.byisinherit ? item.byisinherit : "是"
            license.resourceresult = ""
            license.parentid = userId
            license.resourceid = userId
            license.byresourceid = item.id
            license.righttype = 'org'
            license.byresourceresult = ''
            license.licensepolicy = ''
            param.licenses.push(license)
          })

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

          this.$showAlert('保存成功', 'success', 2000)
        } catch (error) {
          this.$showAlert(`用户保存失败！！错误信息：${error}`, 'danger', 0)
        }
        this.$dispatch('refresh')
      },
      close () {
        this.$dispatch('refresh')
      },
      async deleteStaff () {
        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: '删除出错'})
          } catch (error) {
            this.$showAlert(error.data, 'danger', 0)
          }
          this.$dispatch('refresh')
        }
      },
      openOrgModal () {
        console.log('打开部门模态框')
        this.orgModalShow = true
      },
      getDepart (val) {
        console.log('获取到所属部门', val)
        this.model.f_department_name = val.name
        this.model.parentid = val.id
      },
      openRoleModal () {
        this.roleModalShow = true
      },
      getRoles (roles) {
        // this.model.f_role_name = roles.name
        // this.model.rolelist.push({id: roles.id})
        this.model.f_role_name = ''
        this.model.rolelist = []
        roles.forEach((res) => {
          this.model.f_role_name += (res.name + ' ')
          this.model.rolelist.push({
            id: res.id
          })
        })
      },
      async validateDul (type) {
        // 判断是修改还是新增
        let cond = type === 'userid' ? `userid = '${this.model.userid}'` : `ename = '${this.model.ename}'`
        if (this.data) {
          if (this.model.userid !== this.data.userid ) {
            let validate = await this.$resetpost('rs/sql/ldap_getAllUser', {data: {condition: cond}}, {rejectMsg: '验证用户重复出错！！', resolveMsg: null})
            if (validate.data.length > 0) {
              if (type === 'userid') {
                this.model.userid = this.data.userid
              } else {
                this.model.ename = this.data.ename
              }
              this.$showAlert(`${type === 'userid' ? '编号' : '登录名'}重复，请重新输入！！`, 'warning', 2000)
            }
          }
        } else {
          let validate = await this.$resetpost('rs/sql/ldap_getAllUser', {data: {condition: cond}}, {rejectMsg: '验证用户重复出错！！', resolveMsg: null})
          if (validate.data.length > 0) {
            if (type === 'userid') {
              this.model.userid = ''
            } else {
              this.model.ename = ''
            }
            this.$showAlert(`${type === 'userid' ? '编号' : '登录名'}重复，请重新输入！！`, 'warning', 2000)
          }
        }
      }
    }
  }

</script>
