import { getObjectKey } from '@/assets/utils/host.js'
import { isString } from '@/assets/utils/types.js'
import Schema from 'async-validator'
Schema.warning = () => {}
export default {
    data () {
        return {
            Schema,
            validator: null
        }
    },
    methods: {
        // 提示
        toast (msg) {
            this.$vux.toast.text(msg)
        },
        // 找到父级元素
        findParent (el) {
            const { classList } = el.parentElement
            return classList.contains('form-item') || classList.contains('weui-cell')
                ? el.parentElement
                : this.findParent(el.parentElement)
        },
        // 移除校验提示
        clearValidate () {
            if (this.$el) {
                const $tips = [...this.$el.querySelectorAll('.tips')]
                for (let item of $tips) {
                    item.innerText = ''
                    this.findParent(item).style.paddingBottom = ''
                }
                return $tips
            }
        },
        // 校验
        validate (form) {
            return new Promise((resolve, reject) => {
                if (!this.validator) {
                    resolve()
                } else {
                    const $tips = this.clearValidate()
                    this.validator.validate(form, {
                        firstFields: true
                    }).then(() => {
                        resolve()
                    }).catch(({ errors }) => {
                        // 显示校验提示
                        let firstEl = null
                        for (let { field, message } of errors) {
                            for (let item of $tips) {
                                if (item.dataset.field === field) {
                                    item.innerText = message
                                    const parent = this.findParent(item)
                                    if (!firstEl) firstEl = parent
                                    if (!parent.style.paddingBottom) {
                                        const oldPb = window.getComputedStyle(parent).paddingBottom.replace('px', '') - 0
                                        parent.style.paddingBottom = oldPb + 10 + 'px'
                                    }
                                }
                            }
                        }
                        errors[0].el = firstEl
                        reject(errors[0])
                    })
                }
            })
        },
        // 记录信息 label-value
        info (label, item, subTitle) {
            if (isString(subTitle)) label = `${subTitle} · ${label}`
            let value = item.value
            if (/dateRange|address|info|subform/.test(item.type) || item.hide) return ''
            if (/checkbox(Text)?/.test(item.type)) value = value.join('，')
            if (item.type === 'contacts') value = value.map(n => n.realname).join('，')
            if (/img|file/.test(item.type)) value = value.map(n => getObjectKey(n, 'fullName')).join('，')
            if (item.type === 'radioImg') value = value && value.value
            if (item.type === 'checkboxImg') value = value ? value.map(n => n.value).join('，') : ''
            if (item.type === 'radioMatrix') value = value.map(n => `${n.name}：${n.label}`).join('，')
            if (item.type === 'sort') value = value.map((n, i) => `${i + 1}、${n.name}`).join('，')
            if (item.type === 'rate') value = value.map((n, i) => `${i + 1}、${n.name}`).join('，')
            if (item.type === 'gradeClass') value = Array.isArray(value) ? value.join('，') : value
            return JSON.stringify({ label, value })
        },
        // 隐藏单选的关联项
        radioHide (form, optionList, optionChecked) {
            // 根据自身层级获取，即外面的拿外面的，子表单内拿子表单内的
            // 先将其他选项关联的隐藏，然后当前选项关联的显示（空的关联不参与循环）
            optionList.forEach(optionItem => {
                if (optionItem.value !== optionChecked) {
                    optionItem.link.forEach(linkId => {
                        for (let i in form) {
                            if (form[i].uuid === linkId) form[i].hide = true
                        }
                    })
                }
            })
            optionList.forEach(optionItem => {
                if (optionItem.value === optionChecked) {
                    optionItem.link.forEach(linkId => {
                        for (let i in form) {
                            if (form[i].uuid === linkId) form[i].hide = false
                        }
                    })
                }
            })
        },
        // 必填校验
        required (title, deep) {
            return {
                required: true,
                trigger: ['change', 'blur'],
                validator: (rule, value, callback) => {
                    let val = deep ? value.value : value
                    if (Array.isArray(val)) val = val.length
                    !val
                        ? callback(new Error(title + '必填'))
                        : callback()
                }
            }
        }
    }
}
