<template>
    <div class="oSchool controller" :class="[preview ? '' : 'o-unit']" v-if="widget.type == 'school'">
        <van-field
            :name="widget.model"
            v-model="dataModel"
            :label="widget.name || '文本框'"
            :required="fileCheck ? false : options.required || false"
            :disabled="options.disabled || false"
            clearable
            readonly
            clickable
            :placeholder="options.placeholder || '请输入'"
            :rules="rule"
            clear-trigger="always"
            @click="onClick"
            v-if="!preview"
        >
            <template #right-icon>
                <i class="van-icon van-icon-arrow van-cell__right-icon"></i>
            </template>
        </van-field>

        <van-cell class="preview" :border="false" :title="widget.name || '文本框'" :value="dataModel" v-else></van-cell>

        <!-- 处理显示问题 -->
        <div class="valueShow" v-if="showDataModel && !preview">{{ showDataModel }}</div>
        <div class="valueShow valuePreview" v-if="showDataModel && preview">{{ showDataModel }}</div>

        <van-popup v-model="showSelect" position="bottom">
            <van-picker
                show-toolbar
                :columns="columns"
                @confirm="onConfirm"
                visible-item-count="4"
                @cancel="onCancel"
            />
        </van-popup>
    </div>
</template>
<script>
import { getOrganCooperation } from '../api'
export default {
    name: 'oSchool',
    props: ['widget', 'preview', 'value', 'fileCheck'],
    data() {
        return {
            dataModel: this.widget.options?.defaultValue || null,
            showDataModel: null,
            showSelect: false,
            columns: [],
            organId: null,
        }
    },
    async mounted() {
        // 初始化参数
        this.options?.options?.forEach(item => {
            this.columns.push(item.value)
        })
        // console.log(this.widget, this.value)
        if(this.value) {
            const widget = this.widget
            const model = widget.originModel || widget.model
            for(let v in this.value) {
                if(v == model) {
                    this.dataModel = this.value[v]
                }
            }
            setTimeout(async () => {
                let subForm = widget.model.indexOf('subform')
                let name = widget.options.displayRelation
                let relation = null
                if(subForm > -1) {
                    relation = widget.model.replace(widget.originModel, name)
                }
                // 判断，使用的是哪个分部为基本
                let organElement = document.querySelector(`input[name="${name}"]`) || document.querySelector(`input[name="${relation}"]`)
                const organId = organElement ? organElement.value : null
                if(!organId) {
                    return
                }
                this.organId = organId
                await this.getList()
                // 反显分部
                this.columns.forEach(item => {
                    if(this.dataModel == item.value) {
                        this.showDataModel = item.text
                    }
                })
            }, 200);
        }
    },
    methods: {
        async onClick() {
            const widget = this.widget
            let subForm = widget.model.indexOf('subform')
            let name = widget.options.displayRelation
            let relation = null
            if(subForm > -1) {
                relation = widget.model.replace(widget.originModel, name)
            }
            // 判断，使用的是哪个分部为基本
            let organElement = document.querySelector(`input[name="${name}"]`) || document.querySelector(`input[name="${relation}"]`)
            if(!name || !organElement) {
                this.$toast('模板配置有误，请联系总部管理员')
                return
            }
            const organId = organElement.value
            if(!organId) {
                this.$toast('请选择分部')
                return
            }
            // 判断分部编号是否有修改或更新
            if(organId != this.organId) {
                this.organId = organId
                await this.getList()
            }

            this.showSelect = true
        },
        async getList() {
            // 获取所有分部
            try {
                this.columns = []
                let res = await getOrganCooperation({ organId: this.organId })
                let tempRes = res.data || []
                tempRes.forEach(item => {
                    this.columns.push({
                        text: item.name,
                        value: item.id
                    })
                })
            } catch {
                //
            }
        },
        onConfirm(val) {
            this.dataModel = val.value
            this.showDataModel = val.text
            this.showSelect = false
        },
        onCancel() {
            this.showSelect = false
        },
    },
    computed: {
        options() {
            return this.widget.options || {}
        },
        rule() {
            let rules = this.widget.rules || []
            if(rules && rules.length > 0) {
                rules.forEach(item => {
                    if(item.pattern) {
                        item.pattern = eval(item.pattern)
                    }
                    // 判断是否上传文件
                    if(this.fileCheck) {
                        item.required = false
                    }
                });
            }
            return rules
        }
    },
    watch: {
        // dataModel: {
        //     deep: true,
        //     handler(newValue) {
        //         if (newValue !== undefined && newValue !== null) {
        //         }
        //     }
        // },
    }
}
</script>

<style lang='less' scoped>
@import url('./controlCommon.less');
.oSchool {
    position: relative;
     .valueShow {
        position: absolute;
        bottom: 12px;
        left: 16px;
        line-height: 24px;
        padding: .03rem 0;
        background: #fff;
    }
    .valuePreview {
        bottom: 2px;
    }
}
</style>