<template>
    <!-- 单行输入框 -->
    <el-form label-width="auto" ref="form" :model="form">
        <el-form-item prop="value" :rules="rules(listItem)">
            <el-input
                :value="form.value"
                @input="form.value = input($event)"
                :placeholder="listItem.placeholder"
                show-word-limit
                :minlength="minlength"
                :maxlength="maxlength"
            ></el-input>
        </el-form-item>
        <el-form-item prop="code" :rules="rules(listItem, 'code')" v-if="listItem.verify.sms">
            <div class="code">
                <el-input
                    :value="form.code"
                    @input="form.code = posInt($event)"
                    placeholder="请输入验证码"
                ></el-input>
                <el-button
                    type="primary"
                    :disabled="isWait"
                    @click="getCode"
                >{{ isWait ? count + 's' : '获取验证码' }}</el-button>
            </div>
        </el-form-item>
    </el-form>
</template>

<script>
import mixin from '../mixin.js'
import { isMobilePhone } from '@/assets/utils/validator.js'
import { checkIdCardNo } from '@/assets/utils/checkIdCard.js'
import { number, int, posInt } from '@/assets/utils/formatString.js'
export default {
    name: 'FormInput',
    props: {
        listItem: { type: Object, default: () => ({}) },
        formItem: { type: Object, default: () => ({}) },
        formId: { type: String, default: '' }
    },
    mixins: [mixin],
    data () {
        return {
            posInt,
            form: {
                value: this.formItem.value, // 输入框的值
                code: '' // 验证码
            },
            minlength: this.listItem.verify.length ? this.listItem.verify.lengthMin : '', // 最小字数
            maxlength: this.listItem.verify.length ? this.listItem.verify.lengthMax // 最大字数
                : this.listItem.inputType === 'tel' ? 11
                    : this.listItem.inputType === 'idcard' ? 18 : '',
            isWait: false, // 验证是否等待中
            timer: null, // 计时器
            count: 60 // 验证码等待秒数

        }
    },
    watch: {
        // 同步 value
        'form.value': function (value) {
            this.formItem.value = value
        }
    },
    methods: {
        // 输入类型筛选
        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.$message('请输入手机号')
            } else if (!isMobilePhone(this.formItem.value)) {
                this.$message.warning('手机号格式不正确')
            } 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.$message.warning(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()
                }
            }
        },
        // 提交校验
        verify () {
            return new Promise((resolve, reject) => {
                this.$refs.form.validate(valid => {
                    valid ? resolve() : reject(new Error('input 错误'))
                })
            })
        }
    }
}
</script>

<style lang="less" scoped>
.code {
    display: flex;
    /deep/ .el-button {
        width: 100px;
        margin-left: 20px;
        flex-shrink: 0;
    }
}
</style>
