/*
 * @Author: housy
 * @Email: housy@guahao.com
 * @Date: 2019-05-21
 * @Description: 图片验证码
 */

<template>
    <div class="img-code-wrapper">
        <el-input
            v-model.trim="formParams[name]"
            v-bind="getMergedObject(extend, {placeholder:'请输入验证码'})"
            v-on="extend"
            class="code-input" />
        <img
            v-if="!materialConfig.disabled"
            :src="src"
            @click="() => handleImgClick()"
            class="img-box">
    </div>
</template>

<script>
import { getMergedObject } from 'utils/util';

export default {
    name: 'BkImageCode',
    props: {
        // 元件配置
        materialConfig: {
            type: Object,
            required: true
        },
        // 表单所有元件参数
        formParams: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            getMergedObject,
            name: '',
            src: '',
            extend: {}
        };
    },
    created() {
        const { name, extend } = this.materialConfig;
        this.name = name;
        this.extend = extend;
        this.handleImgClick();
    },
    methods: {
        handleImgClick(materialConfig = '') {
            const obj = materialConfig || this.materialConfig;
            const { http } = obj;
            const {
                url, params, method, onBefore, onSuccess, onFaild 
            } = http || {};
            if (!url) {
                console.error('http.url is undefined');
                return;
            }
            const timeStamp = new Date().getTime();
            let finalParams = Object.assign(
                {},
                {
                    [(params && params.default) || 'codeSign']: timeStamp
                },
                params || {}
            );
            if (finalParams.default) delete finalParams.default;

            // 调用请求发送前函数钩子
            if (typeof onBefore === 'function') {
                const result = onBefore(finalParams, this);
                if (result === false) return;
                if (typeof result === 'object') finalParams = result;
            }

            this.$fetch({
                url,
                params: finalParams,
                method
            }).then(res => {
                if (!res) {
                    if (typeof onFaild === 'function') onFaild(res, this);
                    return;
                }
                const { data } = res;
                this.src = `data:image/jpeg;base64,${data}`;
                // 验证时间戳保存
                this.$emit('update:codeSign', timeStamp);
                // 成功回调
                if (typeof onSuccess === 'function') {
                    onSuccess(res, this);
                }
            }).catch(err => {
                // 失败回调
                if (typeof onFaild === 'function') {
                    onFaild(err, this);
                }
            });
        }
    }
};
</script>
