<template>
    <div class="right-board">
        <el-tabs v-model="currentTab" class="center-tabs">
            <el-tab-pane label="题目属性" name="field" />
            <template v-if="!isQuestionnaire">
                <el-tab-pane label="组件样式" name="style" />
                <el-tab-pane label="表单属性" name="form" />
            </template>
        </el-tabs>
        <div class="field-box">
            <el-scrollbar class="right-scrollbar">
                <!-- 组件属性 -->
                <el-form v-show="currentTab==='field' && showField" size="small" label-width="90px"
                    labelPosition="left">
                    <template v-if="activeData.__config__&&activeData.__config__.jnpfKey">
                        <template>
                            <el-form-item label="题目类型"
                                :label-width="activeData.__config__.jnpfKey==='card'?'76px':''">
                                <el-input :value="getCompName" disabled />
                            </el-form-item>
                            <!-- <el-form-item label="控件字段"
                                v-if="activeData.__vModel__!==undefined  && !noVModelList.includes(activeData.__config__.jnpfKey)||activeData.isStorage==1">
                                <el-input v-model="activeData.__vModel__" disabled
                                    placeholder="请输入数据库字段"
                                    @change="inputFieldChange($event,activeData.__config__.formId,activeData.__config__.parentVModel)" />
                            </el-form-item> -->
                        </template>

                        <!-- 自定义问卷组件 -->
                        <!-- 问卷标题 -->
                        <template v-if="activeData.__config__.jnpfKey==='question-title'">
                            <QTitle :active-data="activeData"></QTitle>
                        </template>
                        <!-- 问卷头部提示 -->
                        <template v-if="activeData.__config__.jnpfKey==='question-tip'">
                            <QTip :active-data="activeData"></QTip>
                        </template>

                        <!-- 问卷多行文本 -->
                        <template v-if="activeData.__config__.jnpfKey==='question-textarea'">
                            <QTextarea :active-data="activeData"></QTextarea>
                        </template>

                        <!-- 问卷单选 -->
                        <template v-if="activeData.__config__.jnpfKey==='question-radio'">
                            <QRadio :active-data="activeData"></QRadio>
                        </template>

                        <!-- 问卷多选 -->
                        <template v-if="activeData.__config__.jnpfKey==='question-checkbox'">
                            <QCheckbox :active-data="activeData"></QCheckbox>
                        </template>

                    </template>
                </el-form>
            </el-scrollbar>
        </div>
    </div>
</template>

<script>
import { noVModelList } from '@/components/Generator/generator/comConfig'


//引入问卷独有组件
import {
    questionnairetopComponents, questionnaireinputComponents, questionnaireselectComponents
} from './questionnaireComponentConfig'


import { isNumberStr } from '@/components/Generator/utils'
import { saveFormConf, getDrawingList } from '@/components/Generator/utils/db'
import { getDictionaryTypeSelector } from "@/api/systemData/dictionary"
import { getDataInterfaceSelector } from "@/api/systemData/dataInterface"
import { DataModelFieldList } from '@/api/systemData/dataModel'
import { getPrintDevSelector } from '@/api/system/printDev'

import QTitle from './RightComponents/QTitle.vue'
import QTip from './RightComponents/QTip.vue'
import QTextarea from './RightComponents/QTextarea.vue'
import QRadio from './RightComponents/QRadio.vue'
import QCheckbox from './RightComponents/QCheckbox.vue'


export default {
    components: {
        QTitle,
        QTip,
        QTextarea,
        QRadio,
        QCheckbox
    },
    inject: ["getShowType", "getFormInfo"],
    props: ['showField', 'activeData', 'formConf', 'modelType', 'webType', 'drawingList', 'formInfo', 'isQuestionnaire'],
    data() {
        return {
            currentTab: 'field',
            activeFunc: '',
            isConf: false,
            noVModelList,
            printTplList: [],
            fieldOptions: [],
            dictionaryOptions: [],
            dataInterfaceOptions: [],
            layoutTreeProps: {
                label(data, node) {
                    const config = data.__config__
                    return data.componentName || `${config.label}: ${data.__vModel__}`
                }
            },
        }
    },
    computed: {
        showType() {
            return this.getShowType()
        },
        changeName() {

        },
        activeTag() {
            return this.activeData.__config__.tag
        },
        formItemList: {
            get() {
                return this.$store.state.generator.formItemList
            },
            set(val) {
                this.$store.commit('generator/UPDATE_FORMITEM_LIST', val)
            }
        },
        subTable: {
            get() {
                return this.$store.state.generator.subTable || []
            },
            set(val) {
                this.$store.commit('generator/UPDATE_SUB_TABLE', val)
            }
        },
        allTable: {
            get() {
                return this.$store.state.generator.allTable || []
            },
            set(val) {
                this.$store.commit('generator/SET_ALL_TABLE', val)
            }
        },
        mainTable() {
            let allTable = this.$store.state.generator.allTable
            let item = allTable.filter(o => o.typeId == '1')[0]
            if (!item || !item.table) return ''
            return item.table
        },
        drawingOptions() {
            let list = []
            const loop = (data, parent) => {
                if (!data) return
                if (data.__config__ && data.__config__.jnpfKey !== 'table' && data.__config__.children && Array.isArray(data.__config__.children)) {
                    loop(data.__config__.children, data)
                }
                if (Array.isArray(data)) data.forEach(d => loop(d, parent))
                if (data.__vModel__ && data.__config__.jnpfKey !== 'table') {
                    list.push(data)
                }
            }
            loop(this.drawingList)
            return list
        },
        getCompName() {
            const allComps = [...questionnairetopComponents, ...questionnaireinputComponents, ...questionnaireselectComponents]
            const comp = allComps.filter(o => o.__config__.jnpfKey === this.activeData.__config__.jnpfKey);
            if (!comp.length) return '';
            return comp[0].__config__.label;
        },
        getScriptType() {
            return ['onLoad', 'beforeSubmit', 'afterSubmit'].includes(this.activeFunc) ? 'form' : 'formField'
        },
        enableFlow() {
            return this.formInfo && this.formInfo.enableFlow || false
        }
    },
    watch: {
        formConf: {
            handler(val) {
                // saveFormConf(val)
                if (val.formStyle === 'word-form' && val.labelPosition === 'top') {
                    val.labelPosition = 'left'
                }
            },
            deep: true
        },
        activeData(val) {
            if (!val || !val.__config__) return
            if (val.__config__.jnpfKey === 'relationFormAttr') {
                this.$nextTick(() => {
                    this.$refs.relationFormAttr && this.$refs.relationFormAttr.getOptions()
                })
            }
            if (val.__config__.jnpfKey === 'popupSelect' || val.__config__.jnpfKey === 'popupTableSelect') {
                this.$nextTick(() => {
                    this.$refs.popupAll && this.$refs.popupAll.getDataInterfaceInfo()
                })
            }
            if (val.__config__.jnpfKey === 'popupAttr') {
                this.$nextTick(() => {
                    this.$refs.popupAttr && this.$refs.popupAttr.getOptions()
                })
            }
            if (val.__config__.jnpfKey !== 'calculate') {
                this.$nextTick(() => {
                    this.$refs.calculate && this.$refs.calculate.reloadExpressionTemp()
                })
            }
            if (!val.__config__.tableName && val.__config__.jnpfKey !== 'table') {
                val.__config__.tableName = this.mainTable
            }
            if (!this.activeData.__config__.visibility) this.$set(this.activeData.__config__, "visibility", ["pc", "app"])
            this.setDefaultOptions()
        }
    },
    created() {
        this.getDictionaryType()
        this.getDataInterfaceSelector()
        this.getPrintTplList()
        if (!this.activeData || !this.activeData.__config__) return
        if (!this.activeData.__config__.visibility) this.$set(this.activeData.__config__, "visibility", ["pc", "app"])
        if (!this.activeData.__config__.tableName && this.activeData.__config__.jnpfKey !== 'table') {
            this.activeData.__config__.tableName = this.mainTable
        }
        this.setDefaultOptions()
    },
    methods: {
        refreshPrintOptions() {
            getPrintDevSelector(2).then(res => {
                let data = res.data.list
                let list = data.filter(o => o.children && o.children.length)
                this.printTplList = list.map(o => ({
                    ...o,
                    hasChildren: true
                }))
            }).catch(error => {
                reject(error)
            })
        },
        // 如果要跳转新页面，请用函数包裹打开新页签。否则会出现被拦截
        open(url) {
            window.open(url, "_blank");
        },
        // 打印模板快捷入口
        openPrint() {
            let routeUrl = this.$router.resolve({
                path: '/system/printDev?open=true'
            });
            this.open(routeUrl.href)
        },

        updateStyleScript(func) {
            this.formConf.classJson = func
            this.formConf.classNames = this.spiltByDoc(func).map(o => o.key)
        },
        spiltByDoc(str) {
            let func = str.trim()
            let arr = []
            let cut = func.split("}")
            cut.forEach(item => {
                if (item) {
                    let afterCut = item.split("{")
                    let classObject = {}
                    let name = ''
                    if (afterCut[0].split(" ").length > 1) {
                        name = afterCut[0].split(" ")[0]
                    } else {
                        name = afterCut[0]
                    }
                    if (name.split("\.").length > 1) {
                        name = name.split("\.")[1]
                    }
                    name = name.split("\:")[0]
                    let matching = new RegExp(/^[a-zA-Z]-?.*[a-zA-Z0-9_]*$/)
                    if (matching.test(name)) {
                        classObject.key = name.replace(/\r|\n/ig, '').trim()
                        classObject.value = item.replace(/\r|\n/ig, '') + "}"
                        arr.push(classObject)
                    }
                }
            })
            return arr
        },
        addReg() {
            this.activeData.__config__.regList.push({
                pattern: '',
                message: ''
            })
        },
        setDefaultValue(val) {
            if (Array.isArray(val)) {
                return val.join(',')
            }
            // if (['string', 'number'].indexOf(typeof val) > -1) {
            //   return val
            // }
            if (typeof val === 'boolean') {
                return `${val}`
            }
            return val
        },
        onDefaultValueInput(str) {
            if (Array.isArray(this.activeData.__config__.defaultValue)) {
                // 数组
                this.$set(
                    this.activeData.__config__,
                    'defaultValue',
                    str.split(',').map(val => (isNumberStr(val) ? +val : val))
                )
            } else if (['true', 'false'].indexOf(str) > -1) {
                // 布尔
                this.$set(this.activeData.__config__, 'defaultValue', JSON.parse(str))
            } else {
                // 字符串和数字
                this.$set(
                    this.activeData.__config__,
                    'defaultValue',
                    isNumberStr(str) ? +str : str
                )
            }
        },
        getSubTableFiled(key) {
            let item = {}
            let list = this.subTable.filter(o => o.table === key)
            if (list.length) {
                item = list[0]
            }
            let arr = []
            if (item && item.fields) arr = item.fields.filter(o => o.primaryKey != 1)
            return arr
        },
        fieldChange1(val) {
            if (!val) return
            const drawingList = getDrawingList() || []
            let boo = false
            const loop = list => {
                for (let i = 0; i < list.length; i++) {
                    const e = list[i]
                    const config = e.__config__
                    if (config.jnpfKey === 'table' && config.tableName === this.activeData.__config__.relationTable) {
                        for (let j = 0; j < config.children.length; j++) {
                            const child = config.children[j]
                            if (child.__vModel__ === val) {
                                boo = true
                                break
                            }
                        }
                    }
                    if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
                        loop(config.children)
                    }
                }
            }
            loop(drawingList)
            if (boo) {
                this.$message.warning(`子表字段【${val}】已存在,请重新选择!`)
                this.activeData.__vModel__ = ''
                return
            }
            let options = this.getSubTableFiled(this.activeData.__config__.relationTable)
            let item = options.filter(o => o.field == val)[0]
            if (!item || !item.fieldName) return
            this.activeData.__config__.label = item.fieldName
        },
        fieldChange(val) {
            if (!val) return
            const drawingList = getDrawingList() || []
            let boo = false
            const loop = list => {
                for (let i = 0; i < list.length; i++) {
                    const e = list[i]
                    const config = e.__config__
                    if (e.__vModel__ === val) {
                        boo = true
                        break
                    }
                    if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
                        loop(config.children)
                    }
                }
            }
            loop(drawingList)
            if (boo) {
                this.$message.warning(`字段【${val}】已存在,请重新选择!`)
                this.activeData.__vModel__ = ''
                return
            }
            let item = this.fieldOptions.filter(o => o.realField == val)[0]
            if (!item || !item.fieldName) return
            this.activeData.__config__.label = item.fieldName
            this.$forceUpdate()
        },
        inputFieldChange(val, formId, parentVModel) {
            if (!val) return
            let boo = false
            let childBoo = false
            if (parentVModel) {
                const loop = (data, parent) => {
                    if (!data) return
                    if (data.__config__ && data.__config__.children && Array.isArray(data.__config__.children)) {
                        loop(data.__config__.children, data)
                    }
                    if (Array.isArray(data)) data.forEach(d => loop(d, parent))
                    if (parent && parent.__config__ && parent.__config__.jnpfKey == 'table') {
                        if (data.__vModel__ && data.__vModel__.toLowerCase() === val.toLowerCase() && data.__config__.formId !== formId && data.__config__.parentVModel === parentVModel) {
                            childBoo = true
                            return
                        }
                    }
                }
                loop(getDrawingList())
            } else {
                const loop = (data, parent) => {
                    if (!data) return
                    if (data.__config__ && data.__config__.jnpfKey !== 'table' && data.__config__.children && Array.isArray(data.__config__.children)) {
                        loop(data.__config__.children, data)
                    }
                    if (Array.isArray(data)) data.forEach(d => loop(d, parent))
                    if (data.__vModel__ && data.__vModel__.toLowerCase() === val.toLowerCase() && data.__config__.formId !== formId) {
                        boo = true
                        return
                    }
                }
                loop(getDrawingList())
            }
            if (boo) {
                this.$message.warning(`字段【${val}】已存在,请重新输入!`)
                this.activeData.__vModel__ = ''
                return
            }
            if (childBoo) {
                this.$message.warning(`子表字段【${val}】已存在,请重新输入!`)
                this.activeData.__vModel__ = ''
            }
        },
        tableChange() {
            this.activeData.__vModel__ = ''
            this.setDefaultOptions()
        },
        changeStorage() {
            this.activeData.__vModel__ = ''
            if (this.activeData.isStorage == 0) this.activeData.__vModel__ = ''
            if (!this.$store.getters.hasTable && this.activeData.isStorage == 1) this.$emit('setVModel', this.activeData)
            const loop = list => {
                for (let i = 0; i < list.length; i++) {
                    const e = list[i]
                    const config = e.__config__
                    if (config.jnpfKey === 'table' && e.__vModel__ === this.activeData.__config__.parentVModel) {
                        this.activeData.__config__.relationTable = config.tableName
                    }
                    if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
                        loop(config.children)
                    }
                }
            }
            loop(this.drawingList)
        },
        setDefaultOptions() {
            if (!this.$store.getters.hasTable) return
            if ((this.activeData.__vModel__ === undefined && this.activeData.isStorage != 1) || this.activeData.__config__.jnpfKey === 'table') return
            if (!this.activeData.__config__.tableName || this.activeData.__config__.tableName === this.mainTable) {
                let fieldOptions = this.formItemList.map(o => ({ ...o, realField: o.field }))
                this.fieldOptions = fieldOptions.filter(o => o.primaryKey != 1)
            } else {
                let list = this.allTable.filter(o => o.table === this.activeData.__config__.tableName)
                if (!list.length) {
                    this.activeData.__config__.tableName = this.mainTable
                    let fieldOptions = this.formItemList.map(o => ({ ...o, realField: o.field }))
                    this.fieldOptions = fieldOptions.filter(o => o.primaryKey != 1)
                    this.activeData.__vModel__ = ''
                } else {
                    let item = list[0]
                    let options = item.fields.map(o => ({
                        ...o,
                        realField: 'jnpf_' + this.activeData.__config__.tableName + '_jnpf_' + o.field,
                    }))
                    this.fieldOptions = options.filter(o => o.primaryKey != 1)
                }
            }
        },
        spanChange(val) {
            this.formConf.span = val
        },
        onTableNameChange(tableName) {
            if (!tableName) return
            const drawingList = getDrawingList() || []
            let boo = false
            const loop = list => {
                for (let i = 0; i < list.length; i++) {
                    const e = list[i]
                    const config = e.__config__
                    if (config.jnpfKey === 'table' && config.tableName === tableName) {
                        boo = true
                        break
                    }
                    if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
                        loop(config.children)
                    }
                }
            }
            loop(drawingList)
            if (boo) {
                this.$message.warning(`子表【${tableName}】已存在,请重新选择!`)
                this.activeData.__config__.tableName = ''
                return
            }
            for (let i = 0; i < this.activeData.__config__.children.length; i++) {
                this.$set(this.activeData.__config__.children[i].__config__, 'relationTable', tableName)
                this.$set(this.activeData.__config__.children[i], '__vModel__', '')
            }
        },
        onBorderWidthChange(val) {
            if (!val) this.$nextTick(() => this.$set(this.activeData.__config__, 'borderWidth', 1))
        },
        getDictionaryType() {
            getDictionaryTypeSelector().then(res => {
                this.dictionaryOptions = res.data.list.filter(o => o.children && o.children.length);
            })
        },
        getDataInterfaceSelector() {
            getDataInterfaceSelector().then(res => {
                this.dataInterfaceOptions = res.data
            })
        },
        getPrintTplList() {
            this.$store.dispatch('base/getPrintFormTree').then(res => {
                let list = res.filter(o => o.children && o.children.length)
                this.printTplList = list.map(o => ({
                    ...o,
                    hasChildren: true
                }))
            })
        },
        getTipText(key) {
            let text = ''
            switch (key) {
                case 'change':
                    text = '发生变化时触发'
                    break;
                case 'blur':
                    text = '失去焦点时触发'
                    break;
                case 'click':
                    text = '点击时触发'
                    break;
                case 'tabClick':
                    text = '面板点击时触发'
                    break;
                default:
                    text = ''
                    break;
            }
            return text
        },
        updateScript(data) {
            if (this.isConf) {
                this.formConf.funcs[this.activeFunc] = data
            } else {
                this.activeData.on[this.activeFunc] = data
            }
        },


        async updateFieldOptions(data) {
            let tableName = ''
            if (!this.activeData.__config__.isSubTable) {
                tableName = this.activeData.__config__.tableName
            } else {
                tableName = this.activeData.__config__.relationTable
            }
            let queryType = 0, type = this.getFormInfo().type
            if (type == 3 || type == 4 || type == 5) queryType = 1
            let res = await DataModelFieldList(this.getFormInfo().dbLinkId, tableName, queryType)
            let fields = res.data.list
            for (let i = 0; i < this.allTable.length; i++) {
                if (this.allTable[i].table === tableName) {
                    this.allTable[i].fields = fields
                    break
                }
            }
            if (!this.activeData.__config__.isSubTable) {
                if (this.activeData.__config__.tableName === this.mainTable) this.formItemList = fields
                this.setDefaultOptions()
            } else {
                this.subTable = this.allTable.filter(o => o.typeId == '0')
            }
        },
        onBarcodeTextChange(val) {
            if (!val) return
            let reg = /^[A-Za-z0-9]+$/
            if (!reg.test(val)) {
                this.$message({
                    message: '固定值请输入数字或者英文字母',
                    type: 'error',
                    duration: 1500,
                })
            }
        },
        onRuleChange(id, item) {
            if (!id) {
                this.activeData.__config__.rule = ''
                this.activeData.__config__.ruleName = ''
                return
            }
            if (this.activeData.__config__.rule === id) return
            this.activeData.__config__.rule = id
            this.activeData.__config__.ruleName = item.fullName
        },
        addComponent(item, parent) {
            this.$emit('copyItem', item, parent, false)
        }
    }
}
</script>
<style lang="scss" scoped>
.printWrap {
    padding: 10px 0;
    text-align: center;
    >>> .el-divider--horizontal {
        margin: 10px 0;
    }
}
.right-board {
    width: 340px;
    position: absolute;
    right: 0;
    top: 0;
    padding-top: 3px;
    height: 100%;
    background: #fff;
    border-radius: 4px;
    .field-box {
        position: relative;
        height: calc(100% - 42px);
        box-sizing: border-box;
        overflow: hidden;
    }
    .el-scrollbar {
        height: 100%;
    }
}
>>> .select-item,
.select-item {
    display: flex;
    border: 1px dashed #fff;
    box-sizing: border-box;
    & .el-input + .el-input {
        margin-left: 4px;
    }
    & + .select-item {
        margin-top: 4px;
    }
    &.sortable-chosen {
        border: 1px dashed #409eff;
    }
    .select-line-icon {
        line-height: 32px;
        font-size: 22px;
        padding: 0 4px;
        color: #606266;
        .icon-ym-darg {
            font-size: 20px;
            line-height: 31px;
            display: inline-block;
        }
    }
    .close-btn {
        cursor: pointer;
        color: #f56c6c;
    }
    .option-drag {
        cursor: move;
    }
}
.time-range {
    .el-date-editor {
        width: 227px;
    }
    ::v-deep .el-icon-time {
        display: none;
    }
}
.document-link {
    position: absolute;
    display: block;
    width: 26px;
    height: 26px;
    top: 0;
    left: 0;
    cursor: pointer;
    background: #409eff;
    z-index: 1;
    border-radius: 0 0 6px 0;
    text-align: center;
    line-height: 26px;
    color: #fff;
    font-size: 18px;
}
.node-label {
    font-size: 14px;
}
.node-icon {
    color: #bebfc3;
}
.right-scrollbar {
    .el-form {
        >>> .el-date-editor,
        >>> .el-cascader,
        >>> .el-select {
            width: 100%;
        }
    }
}
.per-cell {
    display: flex;
    align-items: center;
    margin-bottom: 18px;
    .el-checkbox {
        width: 146px;
    }
    &.last {
        margin-bottom: 0;
    }
}
</style>
<style lang="scss">
.field-select-popper {
    .el-select-dropdown__empty {
        span,
        .el-link {
            line-height: 16px;
            vertical-align: top;
        }
    }
}
.custom-option-left {
    float: left;
}
.custom-option-right {
    float: right;
    color: #8492a6;
    font-size: 13px;
    margin-left: 20px;
}
</style>