<template>
  <div class="table-form">
    <Form :model="model" :ref="action" :rules="rules" :label-width="labelWidth">
      <Row :gutter="10">
        <Col span="24">
         <Form-item label="用户名" prop="username" v-validate:username.required.maxInputLength="rules">
            <Input v-model="model.username" maxlength="32"  placeholder="请输入1~32位字符"  :disabled="model.if"></Input>
          </Form-item>
          <Form-item label="姓名" prop="name" v-validate:name.required.maxInputLength="rules">
            <Input v-model="model.name" maxlength="32"  placeholder="请输入1~32位字符" ></Input>
          </Form-item>
           <Form-item v-show="model.ispass" label="密码" prop="password" v-validate:password.required.maxInputLength="rules">
            <Input v-model="model.password" maxlength="32"  type = "password" paplaceholder="请输入1~32位字符" ></Input>
          </Form-item>
           <Form-item v-if="model.ispass" label="确认密码" prop="chkPwd"  >
            <Input v-model="model.checkPassword" maxlength="32"  type = "password" paplaceholder="请再次输入密码" ></Input>
         </Form-item>
           <Form-item label="联系电话" prop="phone" >
           <Input v-model="model.phone" placeholder="请输入11位电话号码" ></Input>
           </Form-item>
            <Form-item label="认证类型" prop="authType" >
           <div id="app1">
               <treeselect v-model="model.authType" :searchable="false" :multiple="false" :options="authTypes" placeholder="请选择认证类型..."/>
            </div>
           </Form-item>
           <Form-item label="角色" prop="roles" >
           <div id="app2">
               <treeselect v-model="model.roles" :searchable="false" :multiple="true" :options="options" placeholder="请选择角色..."/>
            </div>
           </Form-item>
              <Form-item label="电子邮箱" prop="email" >
           <Input v-model="model.email" placeholder="请输入您的电子邮箱" ></Input>
           </Form-item>
              <Form-item label="备注" prop="remark" >
           <Input v-model="model.remark"  type="textarea" maxlength="200"  :autosize="true" placeholder="请输入0~200位字符" ></Input>
           </Form-item>
        </Col>
      </Row>

      <Row class="buttonDiv">
        <Button :loading="loading"
          @click="submitForm(action)"
          type="primary"
          v-if="!(action == 'detail')"
        >确&nbsp;&nbsp;定</Button>
        <Button @click="cancel">关&nbsp;&nbsp;闭</Button>
      </Row>
    </Form>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Emit } from "vue-property-decorator";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
@Component({
  components: {
    Treeselect
  }
})
// @Component
export default class UserForm extends Vue {

    @Prop() private model!:any;
    @Prop(String) private action!:string;
    @Prop() private tableInfo!:any;
    @Prop() private tableVm!:any;

    loading : boolean = false;
    labelWidth:number =120;
    rules:any={};
    options: Array<any> = [];
    authTypes: Array<any> = [];
    roleList:any={};
    numberReg:any={};
    emailReg:any={};


    created(){
      this.getOptions();
      this.getAuthTypes();
    }

    getAuthTypes(){
      this.authTypes = [{
        id:'0',
        label:'普通认证'
      },{
        id:'1',
        label:'LDAP认证'
      }]
    }
    getOptions(){
       this.getApiData('post',this.$msPrefix.base+'/api/v1/data/list/role','',res=>{
            if (res.rtnCode == 0) {
                this.roleList = res.data.content;
                 res.data.content.forEach(element => {
                  var pool: any = {
                           id:'',
                           label:''
                   };
                   pool.id = element.id;
                   pool.label = element.name;
                   this.options.push(pool);
                 });
            }
        },err=>{
        });

    }

     isEmpty(obj){
      	return (typeof obj === 'undefined' || obj === null || obj === "" || obj.length ==0);
    }

    data() {
       var validateChkPwd = (rule, value, callback) => {
            if (typeof this.model.checkPassword === 'undefined' || this.model.checkPassword ==="") {
              callback(new Error("请再次输入密码"));
            } else {
              if (this.model.checkPassword !== this.model.password) {
                callback(new Error("两次输入密码不一致!"));
              }
              callback();
            }
          };
          var validatePhone = (rule, value, callback) => {
              let regExp = this.numberReg;
              let  errorMsg = "请输入正确的11位电话号码";            
              if (value && !regExp.test(value)) {
                callback(new Error(errorMsg));
              } else {
                callback();
              }
        };
         var validateEmail = (rule, value, callback) => {           
              let regExp2 = this.emailReg;
              let errorMsg2 = "请输入正确的邮箱地址";            
              if (value && !regExp2.test(value)) {
                callback(new Error(errorMsg2));
              } else {
                callback();
              }
        };
      var validateRoles = (rule, value, callback) => {   
            if (this.isEmpty(value)) {
              callback(new Error("请至少选择一个角色"));
            } else {
              callback();
            }
      };
      var validateAuthType = (rule, value, callback) => {   
            if (this.isEmpty(value)) {
              callback(new Error("请至少选择一种认证类型"));
            } else {
              callback();
            }
      };
                
      return {
        numberReg: /^1[3456789]\d{9}$/,
        emailReg: /^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+(\.[a-zA-Z]{2,3})+$/,
        rules: {
          chkPwd: [
          {
            required: true,
            validator: validateChkPwd,
            trigger: "blur"
          }
        ],
        phone: [
          {
            validator: validatePhone,
            trigger: "blur"
          }
        ], email: [
          {
            validator: validateEmail,
            trigger: "blur"
          }
        ], roles: [
          {
            required: true,
            validator: validateRoles,
            trigger: "blur"
          }
        ],
        authType: [
          {
            required: true,
            validator: validateAuthType,
            trigger: "blur"
          }
        ]
        },
        
        // define the default value
        value: null,
        // define options
      }
    }

    mounted(){
      if(this.model.action == 'update'){
        this.model.ispass = false;
    
      }else{
        this.model.ispass = true;
      }
      this.model.authType = 0;
    }
    save(){
      var saveRes:any={id:'',username:'',name:'',password:'',phone:'',authType:'',roles:[],email:'',remark:''};
      this.model.roles.forEach(element => {
          var roleDetail = this.roleList.find(role => role.id == element);
        saveRes.roles.push(roleDetail);
      });
      saveRes.id = this.model.id;
      saveRes.name =  this.model.name;
      saveRes.password =  this.model.password;
      saveRes.phone =  this.model.phone;
      saveRes.authType =  this.model.authType;
      saveRes.email =  this.model.email;
      saveRes.remark =  this.model.remark;
      saveRes.username = this.model.username;
        this.getApiData('post',this.$msPrefix.base+'/api/v1/data/save/user',saveRes,res=>{
           this.loading=!1;
            if (res.rtnCode == 0) {
                this.tableVm.getData();
                this.cancel();
                this.$tools.message('success',(this.action == 'update'?'修改':'新增')+'成功！')
            }
        },err=>{
           this.loading=!1;
        })
    }
    /*提交*/
      submitForm (action) {

        (this.$refs[action] as any).validate((valid) => {
          if (valid) {
          	if(!this.loading){
                this.loading=!0;
                this.save()
            }
          } else {
            this.$tools.message('info',"请完善必填项!")

          }
        });
      }

    @Emit('closeModal') close(){}
    cancel() {
      	this.close();
        (this.$refs[this.action] as any).resetFields();
      }

    get disabled(){
        return this.action=='detail'
    }
}
</script>

