<template>
    <!-- 单行输入框 -->
    <group gutter="0" :class="applicable">
        <x-input
            :type="type(listItem.inputType)"
            :value="form.value"
            @input="form.value = input($event), $refs.value.currentValue = form.value"
            @on-change="clearValidate"
            @on-blur="verify().catch(() => {})"
            :placeholder="listItem.placeholder"
            v-bind="minmax"
            class="input"
            ref="value"
        >
            <template slot="label">
                <slot></slot>
            </template>
        </x-input>
        <x-input
            type="tel"
            :value="form.code"
            @input="form.code = posInt($event), $refs.code.currentValue = form.value"
            @on-change="clearValidate"
            @on-blur="verify().catch(() => {})"
            placeholder="请输入验证码"
            class="code"
            ref="code"
            v-if="listItem.verify.sms"
        >
            <template slot="label" v-if="applicable === 'Form'">
                <i :class="{ required: listItem.verify.required }"></i>
                验证码
                <i class="tips" data-field="code"></i>
            </template>
            <i class="tips" data-field="code" slot="label" v-else></i>
            <x-button
                slot="right"
                class="code-btn"
                type="primary"
                mini
                :disabled="isWait"
                @click.native="getCode"
            >{{ isWait ? count + 's' : '获取' }}</x-button>
        </x-input>
    </group>
</template>

<script>
import common from '@/common/formRender/mixin/common.js'
import length from '@/common/formRender/mixin/length.js'
import { isMobilePhone } from '@/assets/utils/validator.js'
import { checkIdCardNo } from '@/assets/utils/checkIdCard.js'
import { number, int, posInt } from '@/assets/utils/formatString.js'
import { Group, XInput, XButton } from 'vux'
export default {
    name: 'FormInput',
    mixins: [common, length],
    components: {
        Group, XInput, XButton
    },
    inject: ['applicable', 'formId'],
    props: {
        listItem: { type: Object, default: () => ({}) },
        formItem: { type: Object, default: () => ({}) }
    },
    data () {
        // 输入框属性
        const minmax = {}
        const { verify, inputType } = this.listItem
        if (verify.length) {
            if (verify.lengthMin) minmax.min = verify.lengthMin - 0
            if (verify.lengthMax) minmax.max = verify.lengthMax - 0
        } else {
            if (inputType === 'tel') minmax.max = 11
            if (inputType === 'idcard') minmax.max = 18
        }
        return {
            posInt,
            form: {
                value: this.formItem.value, // 输入框的值
                code: '' // 验证码
            },
            minmax, // 最小最大输入字符
            isWait: false, // 验证是否等待中
            timer: null, // 计时器
            count: 60 // 验证码等待秒数
        }
    },
    watch: {
        // 同步 value
        'form.value': function (value) {
            this.formItem.value = value
        }
    },
    created () {
        this.verifyInit()
    },
    methods: {
        // 输入框类型
        type (type) {
            switch (type) {
            case 'number':
            case 'tel': return 'tel'
            case 'email': return 'email'
            default: return 'text'
            }
        },
        // 输入类型筛选
        input (value) {
            if (this.listItem.inputType === 'tel') {
                return posInt(value)
            } else if (this.listItem.inputType === 'number') {
                return this.listItem.verify.int ? int(value) : number(value)
            } else {
                return value
            }
        },
        // 获取验证码
        getCode () {
            if (!this.formItem.value) {
                this.toast('请输入手机号')
            } else if (!isMobilePhone(this.formItem.value)) {
                this.toast('手机号格式不正确')
            } else if (!this.isWait) {
                this.isWait = true
                this.timer = setInterval(() => {
                    this.count--
                    if (!this.count) this.endWait()
                }, 1000)
                this.$api.platBaseApi.sendVerifyCode(this.formItem.value).then(res => {
                    if (!res.data.Status) {
                        this.endWait()
                        this.toast(res.data.ResponseError.LongMessage)
                    }
                }).catch(() => {
                    this.endWait()
                })
            }
        },
        // 验证码结束计时
        endWait () {
            clearInterval(this.timer)
            this.isWait = false
            this.count = 60
        },
        // 获取校验规则
        rules (item, type) {
            const rules = []
            if (type !== 'code') {
                if (item.verify.required) rules.push(this.required(item.title)) // mixin
                if (item.inputType === 'no') {
                    if (item.verify.length) {
                        if (item.verify.lengthMin) rules.push(this.lengthMin(item.verify.lengthMin)) // mixin
                        if (item.verify.lengthMax) rules.push(this.lengthMax(item.verify.lengthMax)) // mixin
                    }
                } else if (item.inputType === 'tel') {
                    rules.push(this.tel())
                    if (item.verify.unique) rules.push(this.unique())
                } else if (item.inputType === 'email') {
                    rules.push(this.email())
                    if (item.verify.unique) rules.push(this.unique())
                } else if (item.inputType === 'idcard') {
                    rules.push(this.idcard())
                    if (item.verify.unique) rules.push(this.unique())
                } else if (item.inputType === 'number') {
                    if (item.verify.range) {
                        if (item.verify.rangeMin) rules.push(this.rangeMin(item.verify.rangeMin))
                        if (item.verify.rangeMax) rules.push(this.rangeMax(item.verify.rangeMax))
                    }
                }
            } else {
                if (item.verify.required) rules.push(this.required('验证码'))
                // rules.push(this.telSms(item)) // ---- 接口待定
            }
            return rules
        },
        // 手机号格式校验
        tel () {
            return {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    value && !isMobilePhone(value)
                        ? callback(new Error(`手机号格式不正确`))
                        : callback()
                }
            }
        },
        // 重复校验
        unique () {
            return {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    if (value) {
                        this.$api.commonApi.formRecordValidation({
                            create_user_id: '', // 后期可根据需求传入当前用户 id 让自己上传的可以重复
                            form_id: this.formId,
                            form_control_id: this.formItem.uuid,
                            key: 'value',
                            value
                        }).then(res => {
                            !res.data.Status
                                ? callback(new Error(`该手机号已提交过`))
                                : callback()
                        }).catch(() => {
                            callback(new Error(`重复校验请求失败`))
                        })
                    } else {
                        callback()
                    }
                }
            }
        },
        // 手机号验证码校验 ---- 接口待定
        telSms () {
            return {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    if (isMobilePhone(this.formItem.value)) {
                        if (!value) {
                            callback(new Error('请输入验证码'))
                        } else {
                            setTimeout(() => {
                                value !== '1111'
                                    ? callback(new Error(`验证码错误`))
                                    : callback()
                            }, 500)
                        }
                    } else {
                        callback()
                    }
                }
            }
        },
        // 邮箱格式校验
        email () {
            return {
                type: 'email',
                trigger: 'blur',
                message: '邮箱格式不正确'
            }
        },
        // 身份证格式校验
        idcard () {
            return {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    value && !checkIdCardNo(value)
                        ? callback(new Error(`身份证格式不正确`))
                        : callback()
                }
            }
        },
        // 数字最小值校验
        rangeMin (min) {
            return {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    value < min - 0
                        ? callback(new Error(`不能低于最小值 ${min}`))
                        : callback()
                }
            }
        },
        // 数字最大值校验
        rangeMax (max) {
            return {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                    value > max - 0
                        ? callback(new Error(`不能超过最大值 ${max}`))
                        : callback()
                }
            }
        },
        // 校验初始化
        verifyInit () {
            const rule = { value: this.rules(this.listItem) }
            if (this.listItem.verify.sms) rule.code = this.rules(this.listItem, 'code')
            this.validator = new this.Schema(rule)
        },
        // 提交校验
        verify () {
            return this.validate(this.form)
        }
    }
}
</script>

<style lang="less" scoped>
/deep/ .code-btn {
    width: 50px;
    height: 28px;
    margin: -2px 0;
    font-size: 12px;
    padding: 0;
    margin-left: 15px;
    flex-shrink: 0;
}
</style>
