<template>
  <div class="auto select-overspread">
    <validator name='v'>
      <ul class="nav nav-tabs">
        <p class="bg-info text-center" style="padding: 8px;">员工信息</p>
      </ul>
      <div class="form-horizontal select-overspread container-fluid auto" style="margin-top:20px;flex: 1;">
        <div class="row">
          <!--<div class="col-sm-6 form-group" id="img_self">-->
          <!--<label class="font_normal_body">头&emsp;&emsp;像</label>-->
          <!--<img-self v-if="model.imgid && model.imgid.length>0" :src="model.imgid"></img-self>-->
          <!--<button type="button" class="btn button_new btn-lg" v-if="!(model.imgid&&model.imgid.length>0)" :disabled="look" @click="addFile">-->
          <!--<span>上传</span>-->
          <!--</button>-->
          <!--</div>-->
          <!--<div class="col-sm-6 form-group">-->
          <!--<label class="font_normal_body" >二&ensp;维&ensp;码</label>-->
          <!--<img style="width: 60px;height: 60px" v-if="model.qrcode && model.qrcode.length>0" :src="model.qrcode"/>-->
          <!--<button type="button" class="btn button_new btn-lg" @click="downloadCodeImg()">-->
          <!--<span>下载</span>-->
          <!--</button>-->
          <!--</div>-->
          <div class="col-sm-6 form-group"  :class="[$v.userid.required ? 'has-error' : '']">
            <label class="font_normal_body" >员工编号</label>
            <input type="text"  v-model="model.userid"
                   :disabled="look"
                   @blur="validateDul('userid')" v-validate:userid='{required: true }'
                   class="input_search" style="width:45%" placeholder="员工编号" v-next-el="name">
            <button type="button" class="btn button_new btn-lg" style="width:13%"
                    :disabled="look"
                    @click="codeGeneration">
              <span class="glyphicon glyphicon-repeat" ></span>
            </button>
          </div>
          <div class="col-sm-6 form-group"  :class="[$v.f_name.required ? 'has-error' : '']">
            <label class="font_normal_body" >员工姓名</label>
            <input type="text"  v-model="model.name"
                   :disabled="look"
                   v-validate:f_name='{required: true }'
                   class="input_search" style="width:60%" placeholder="员工姓名" v-next-el="name">
          </div>
          <div class="col-sm-6 form-group"   :class="[$v.ename.required ? 'has-error' : '']">
            <label class="font_normal_body" >&nbsp;&nbsp;&nbsp;登录名</label>
            <input type="text"  v-model="model.ename"
                   :disabled="look"
                   v-validate:ename="{required: true }"
                   @blur="validateDul('ename')" class="input_search" style="width:60%"
                   placeholder="登录名">
          </div>
          <!--修改用户-->
          <div class="col-sm-6 form-group"   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%"
                    :disabled="look"
                    @click="initpassword">
              <span class="glyphicon glyphicon-repeat" ></span>
            </button>
          </div>
          <!--新增用户-->
          <div class="col-sm-6 form-group"   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="look"
                   @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 form-group" >
            <label  class="font_normal_body" >&nbsp;&nbsp;&nbsp;电话&nbsp;&nbsp;&nbsp;</label>
            <input type="text" v-model="model.f_user_telephone"
                   :disabled="look"
                   class="input_search" style="width:60%" placeholder="电话">
          </div>
          <div class="col-sm-6 form-group">
            <label  class="font_normal_body" >&nbsp;&nbsp;&nbsp;状态&nbsp;&nbsp;&nbsp;</label>
            <v-select :value.sync="model.state"
                      :options='userStates'
                      :value-single="true"
                      :disabled="look"
                      placeholder='状态'
                      close-on-select
                      v-model='model.state'></v-select>
          </div>
          <div class="col-sm-6 form-group"  :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"
                    :disabled='look'
                    style="width:13%"
                    @click="openOrgModal">
              <span class="glyphicon glyphicon-search" ></span>
            </button>
          </div>
          <div class="col-sm-6 form-group" :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"
                    :disabled='look'
                    style="width:13%"  @click="openRoleModal">
              <span class="glyphicon glyphicon-search" ></span>
            </button>
          </div>
          <div class="col-sm-6 form-group" >
            <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"
              :disabled='look'
              :options='getsexs'
              close-on-select>
            </v-select>
          </div>
          <div class="col-sm-6 form-group">
            <label class="font_normal_body" >&nbsp;&nbsp;&nbsp;年龄&nbsp;&nbsp;&nbsp;</label>
            <input type="number" v-model="model.f_age"
                   :disabled='look'
                   class="input_search" style="width:60%" placeholder="年龄">
          </div>

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

          <div class="col-sm-12 form-group">
            <label  class="font_normal_body">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
            <textarea class="ver-textarea" style="width:80%"
                      :disabled='look'
                      rows="2" v-model="model.f_description" placeholder="备注"></textarea>
          </div>
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">展示角色</label>
            <input type="text" v-model="model.f_show_rolestr"
                   :disabled='look'
                   class="input_search" style="width:60%" placeholder="对外展示角色名称">
          </div>
          <div class="col-sm-6 form-group">
            <label class="font_normal_body">展示部门</label>
            <input type="text" v-model="model.f_show_department_name"
                   :disabled='look'
                   class="input_search" style="width:60%" placeholder="对外展示部门名称">
          </div>
        </div>
      </div>
      <div class="row">
        <div style="float:right;">
          <button @click="permissionOper()" class="btn button_search "
                  style="width: 70px"
                  v-if="!look"
                  :disabled='!$v.valid' v-if="!depPermissionShow">
            数据授权
          </button>
          <button @click="confirm()" class="btn button_search "
                  v-if="!look"
                  style="width: 70px"
                  :disabled='!$v.valid'>
            <span class="glyphicon glyphicon-floppy-disk"></span>保存
          </button>
          <button @click='close()' class="btn button_clear"style="width: 70px">
            <span class=" glyphicon glyphicon-log-out"></span>取消
          </button>

        </div>
      </div>
    </validator>
    <department-modal :show.sync="orgModalShow"  v-if="!look" :data="data" @depart="getDepart"></department-modal>
    <role-modal :show.sync="roleModalShow"  v-if="!look" :data="data" @role="getRoles"></role-modal>
    <data-permission-modal v-ref:datapersisson :show.sync="depPermissionShow"   v-if="!look" :data="data" :roots.sync="depPermissions"  :is-edit="isEdit"></data-permission-modal>
    <div class="row" v-if="look&&model.id&&model.id.length>0" style="height: 200px;overflow: auto;">
      <licensepolicy  v-if="look&&model.id&&model.id.length>0" :id="model.id"></licensepolicy>
    </div>
    <modal :show.sync="showFile" v-ref:modal backdrop="true">
      <header slot="modal-header" class="modal-header">
        <button type="button" class="close" @click="closeFile"><span>&times;</span></button>
        <h4 class="modal-title">选择头像</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="form-group">
          <file-upload class="my-file-uploader" name="userUploadFile" action="rs/file/uploadFile" tagname="确定" multiple v-ref:file></file-upload>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer"></footer>
    </modal>
  </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: '',
        //文件上传弹框
        showFile: false,
        valueTrea:[],
        //真实密码
        isCtrl:'',
        flag:true,
        valueShow:'',
        model: {
          userid: '',
          loginid: this.$login.f.id,
          imgid:'',
          qrcode:'',
          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: '',
          f_show_rolestr: '',
          f_show_department_name: ''
        },
        // 组织树模态框
        orgModalShow: false,

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

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

        userStates: [{label:'在职', value: '在职'}, {label:'离职', value: '离职'}],
        getsexs: [{label:'男', value: '男'}, {label:'女', value: '女'}],
      }
    },
    props: ['data','look'],
    ready () {
      this.init()
    },
    watch: {
      'data' (val) {
        this.init()
      }
    },
    events: {
      'onFileUpload': async  function(file, res){
        //头像ID赋值
        this.model.imgid='/rs/file/getfile/'+res.id
        //关闭上传框
        this.closeFile()
      },
      'onFileError'(error) {
        this.$showAlert(error, 'warning', 2000)
      }
    },
    methods: {
      codeGeneration () {
        this.model.userid = (Math.random()*10000000).toString(16).substr(0,4)+'-'+(new Date()).getTime()+'-'+Math.random().toString().substr(2,5)
        console.log('0000==>' + this.model.userid)
      },
      async initpassword () {
        let res = await this.$showMessage(`确认初始化该员工: ${this.model.name} 的密码[000000]吗？`, ['confirm', 'cancel'])
        if (res === 'confirm') {
          try {
            var json={
              password : this.model.password ,
              newpassword : '000000',
              affirmpassword : '000000',
              ename : this.model.ename
            }
            let res = this.$resetpost('/rs/user/modifypwd', {data: json })
            this.model.password='000000'
          } 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()
        }
      },
      // 关闭文件上传对话框
      closeFile() {
        this.showFile = false
        // 将选的文件清空
        this.$refs.file.$el.querySelector('input').value = ''
      },
      // 上传对话框
      addFile() {
        this.showFile = true
        // 将选的文件清空
        this.$refs.file.$el.querySelector('input').value = ''
      },
      initModel() {
        // 处理角色默认数据
        this.valueText= '',
          this.valueTrea= [],
          //真实密码
          this.isCtrl= '',
          this.flag= true,
          this.valueShow= '',
          this.model = {
            userid: '',
            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
      },
      downloadCodeImg(){
        console.log('下载图片')
        var a = document.createElement('a')
        a.download =  this.model.name || 'pic'
        // 设置图片地址
        a.href = this.model.qrcode;
        a.click();
      },
      async confirm () {
        // 保存用户
        try {
          //处理二维码数据
          let str = this.model.userid
          this.model.qrcode='/rs/user/getQRcode?QRCODE='+str
          //处理保存数据中的数据
          if(this.model.rolelist != null && this.model.rolelist.length>0){
            if(this.model.rolelist.length == 1){
              let oldid = this.model.rolelist[0].id;
              //如果传输的数据是一个 ，间隔的字符串
              if(oldid.split(",").length>1){
                let arrid = oldid.split(",");
                this.model.rolelist =  [];
                arrid.forEach((item)=>{
                  this.model.rolelist.push({id:item})
                })
              }
            }
          }
          let res = await this.$resetpost('rs/data/save', {data: this.model})
          // 验证是否包含数据权限，
          if (this.depPermissions.length>0) {
            console.log('保存用户。。', res)
            // 保存部门权限
            let userId = res.data + ''
            // 组织角色权限数据
            let param = {
              parentid: userId,
              loginid: this.$login.f.id,
              licenses:[]
            }
            this.depPermissions.forEach((item) => {
              item.parentid = userId
              item.resourceid = userId
              param.licenses.push(item)
            })
            await this.$resetpost('rs/license/save', param, {resolveMsg: '保存成功', rejectMsg: '保存权限失败！请您重试！！'})
          }
          this.$showAlert('保存成功', 'success', 2000)
          this.$dispatch('success')
        } catch (error) {
          error = error.data ? error.data : error;
          this.$showAlert(`用户保存失败！！错误信息：${error}，请刷新后重试`, 'danger', 0)
          this.$dispatch('cancel')
        }
      },
      close () {
        this.$dispatch('cancel')
      },
      openOrgModal () {
        console.log('打开部门模态框')
        this.orgModalShow = true
      },
      async getDepart (val) {
        console.log('获取到所属部门', val)
        this.model.f_department_name = val.name
        this.model.parentid = val.id;
        this.model.f_department_id = val.id
        let orgData  = await this.$resetpost('rs/search', {source: `this.getParentByType($organization$)`, userid: val.id}, {resolveMsg: null, rejectMsg: '获取分公司id错误'})
        this.model.f_organization_id = orgData.data && orgData.data.id ? orgData.data.id : ""
        //选择部门后自动赋予数据权限
        //this.permissionids.push(this.model.parentid);
        let license = {}
        license.isinherit = "是"
        license.byisinherit = "是"
        license.resourceresult = ""
        license.byresourceid = this.model.parentid;
        license.righttype = "org"
        license.licensepolicy = ""
        license.byresourceresult = '';
        this.depPermissions.push(license);
        //刷新权限
        await this.$refs.datapersisson.ids.push(val.id);
        await this.$refs.datapersisson.DealRoots();
      },
      openRoleModal () {
        this.roleModalShow = true
      },
      getRoles (val) {
        this.model.f_role_name = ''
        this.model.rolelist = []
        val.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>
<style lang="less">
  #img_self {
    div {
      height: auto;
    }
  }
</style>
