<template>
  <Card>
      <template #title>
          <div>
            <P  style="font-size: large;font-weight: 700">
            欢迎登录
            <a style="color: #2d8cf0;float: right" @click="useUkey">检测UKEY<Icon v-if="loadingUkey" type="ios-loading" /></a>
            </P>
            <p v-if="useUkeyFlag" style="color: #2d8cf0;font-size: small;margin-bottom: 5px;">UKEY所属: <span v-text="userName"></span></p>
        </div>
    </template>
    <Modal v-model="showModalUkeyPassword" class-name="vertical-center-modal" :mask-closable="false" :closable="false" :title="modalTitle" :value="value" v-draggable="options">
      <i-form label-position="right" :label-width="100" ref="ukeyPasswordForm" :model="bean" :rules="rules" inline>
        <Row>
          <i-col :span="24">
            <Form-item label="密码" prop="loginConfirmPassword" class="ivu-form-item-search">
              <Input v-model="bean.loginConfirmPassword" type="password" password style="width: 200%" clearable></Input>
            </Form-item>
          </i-col>
        </Row>
      </i-form>
      <template #footer>
        <div>
            <Button @click="cancel">关闭</Button>
            <Button type="primary" :loading="saveLoading" @click="ok('ukeyPasswordForm')">确定</Button>
        </div>
      </template>
    </Modal>
  </Card>
</template>

<script>
    import {
        checkBasicUkey
    } from './basicUkey-api'
    import UKEY from './mTokenBasicOper2'

    let $this;
    export default {
        name: "ukeyPasswordModal",
        components: {
        },
        props : {
            value: Object,
            loginName: String,
            useUkeyFlag: {
                type: Boolean,
                default: false
            }
        },
        data () {
            const validatePass = (rule, value, callback) => {
                if(!value){
                    callback(new Error('密码不能为空!'));
                }else{
                    if(value != this.bean.loginPassword){
                        callback(new Error('密码不正确!'));
                    }else{
                        callback();
                    }
                }
            };
            return{
                ukey:null,
                deviceName:'',
                loadingUkey:false,
                userName:'',
                showModalUkeyPassword:false,
                bean:{},
                saveLoading: false,
                modalTitle: '密码',
                rules: {
                    loginConfirmPassword: [
                        { required: true, validator: validatePass, trigger: 'blur' }
                    ]
                },
                options: {
                    trigger: '.ivu-modal-header',
                    body: '.ivu-modal',
                    recover: true
                }
            }
        },methods: {
            ok (name) {
                this.saveLoading = true;
                this.$refs[name].validate((valid) => {
                    if (!valid) {
                        console.log("验证没通过");
                        this.saveLoading = false;
                        return false;
                    }

                    this.saveLoading = false;
                    this.$emit('update:useUkeyFlag', true );
                    this.$emit( "reload-data", this.bean );
                    this.showModalUkeyPassword = false;
                    this.$refs[name].resetFields();
                });
            },
            cancel () {
                this.showModalUkeyPassword = false;
            },
            useUkey (){//使用ukey
                this.loadingUkey = true;
                setTimeout(this.initUkey,2000);
                setTimeout(function () {
                    this.loadingUkey = false;
                } ,3000);
            },
            initUkey (){//初始化ukey
                this.loadingUkey = true;
                //1.读取ukey
                this.deviceName = UKEY.enumDevice();
                if (!this.deviceName) {this.$Message.error("请确认是否插入Ukey!");return;}

                //2.使用默认密码登录
                UKEY.verifyUserPin(this.$config.ukeyPwd);

                //3.获取指定容器的证书,默认是csbcrj
                UKEY.initCert(this.$config.ukeyContainerName,this.$config.ukeyCertType);
                //if (!certName){this.$Message.error("Ukey中没有指定证书!");return;}
                //4.读取ukey中的账号并填入输入框
                let fileName = this.$config.ukeyAccountFileName;
                let accountName = UKEY.readFile(fileName);
                accountName = this.trimStr(accountName);
                this.$emit('update:loginName', accountName);

                //5.读取ukey中的用户名并展示
                let userNameFileName = this.$config.userNameFileName;
                let userName = UKEY.readFile(userNameFileName);
                this.userName = this.trimStr(userName);

                this.$nextTick(()=>{
                    if(!this.loginName||!this.userName){
                        this.$Message.error("此Ukey没有注册，请联系系统管理员!");return;
                    }

                    let ukeyPrivateKey = UKEY.signData(this.deviceName,'1234567812345678',this.$config.ukeyLoginContainerName);//将ukeyId进行签名

                    checkBasicUkey({ukeyCode:this.deviceName,ukeyContainerName:this.$config.ukeyLoginContainerName,ukeyPrivateKey:ukeyPrivateKey,ukeyHolderLoginname:this.loginName,state:1}).then( data => {
                        if (!data.status){
                            this.$Message.error(data.error.message);
                            return false;
                        }
                        let result = data.result;
                        if(result){
                            this.$Message.success( "检测成功！" );
                            this.ukey = result;

                            let loginIsCheck = this.ukey.loginIsCheck;
                            let loginIsPassword = this.ukey.loginIsPassword;
                            if(loginIsCheck&&loginIsPassword){
                                this.showModalUkeyPassword = true;
                                this.$emit('update:useUkeyFlag', false );
                            }else{
                                this.$emit('update:useUkeyFlag', true );
                                this.$emit( "reload-data", this.ukey);
                            }
                            this.bean = this.ukey;
                        }else{
                            this.$Message.error( "操作失败！" );
                        }
                    }).catch(err =>{
                        this.$Message.error( "操作失败！");
                    })

                });
                //6.设置标记
                this.loadingUkey = false;
            },
            trimStr (str){//使用ukey登录
                if (!str){return '';}
                str = str.replace(//g,'')
                str = str.replace(/￀/g,'')
                str = str.replace(/￯/g,'')
                str = str.replace(/ /g,'')
                return str;
            },
            checkBasicUkey:checkBasicUkey
        },
        mounted() {
            $this = this;
        },
        watch:{
            value:{
                immediate:true,
                handler:function(){

                }
            }
        }

    }
</script>

<style lang="less" scoped>
  .ivu-form-item-search {
    margin-bottom: 21px;
  }
  .vertical-center-modal{
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal{
      top: 0;
    }
  }
</style>
