<template>
    <el-form
        v-bind="$data['attr' + applicable]"
        :class="'applicable-' + applicable.toLowerCase()"
    >
        <el-form-item
            v-for="(item, index) in list"
            :key="index"
            :label="(item.nth || '') + item.title"
        >
            <component
                :is="'form-' + item.component"
                :value="item.value"
                v-if="item.component"
            ></component>
            <!-- 子表单 -->
            <template v-else>
                <el-form
                    class="subform"
                    v-bind="$data['attr' + applicable]"
                    v-for="(valueItem, valueIndex) in item.value"
                    :key="valueIndex"
                >
                    <div class="title">{{ item.title }} {{ valueIndex + 1 }}</div>
                    <el-form-item
                        v-for="(subItem, subIndex) in valueItem"
                        :key="subIndex"
                        :label="subItem.title"
                    >
                        <component
                            :is="'form-' + subItem.component"
                            :value="subItem.value"
                        ></component>
                    </el-form-item>
                </el-form>
            </template>
        </el-form-item>
    </el-form>
</template>

<script>
export default {
    name: 'FormDetail',
    components: {
        FormText: () => import('./components/FormText'),
        FormImg: () => import('./components/FormImg'),
        FormFile: () => import('./components/FormFile'),
        FormOptionImg: () => import('./components/FormOptionImg'),
        FormRate: () => import('./components/FormRate')
    },
    props: {
        formId: { type: String, default: '' }, // 表单 id
        applicable: { type: String, default: 'Form' } // 控件类型，暂定 Form 和 Question
    },
    data () {
        return {
            list: [], // 详情列表

            // 表单 Form 类型属性
            attrForm: {
                'label-width': 'auto',
                'label-suffix': '：'
            },
            // 表单 Question 类型属性
            attrQuestion: {
                'label-position': 'top'
            }
        }
    },
    watch: {
        // 根据 formId 获取详情
        formId: {
            handler (formId) {
                if (this.formId) this.getList()
            },
            immediate: true
        },
        // 如果是问卷类型添加控件序号
        list: {
            handler (list) {
                if (this.applicable === 'Question') {
                    list.forEach((item, index) => {
                        item.nth = `${index + 1}、`
                    })
                }
            },
            immediate: true
        }
    },
    methods: {
        // 获取详情列表
        getList () {
            this.$api.commonApi.formRecordGet({
                b_id: this.formId
            }).then(res => {
                if (res.data.Status) {
                    const id = res.data.Data.form_id
                    const data = JSON.parse(res.data.Data.value)
                    this.getFormList(id, data)
                }
            })
        },
        // 获取表单列表（表单列表可能会被编辑，所以需要根据 uuid 对应最新的）
        getFormList (formId, data) {
            this.$api.commonApi.formInfoGet({
                b_id: formId
            }).then(res => {
                if (res.data.Status) {
                    const list = JSON.parse(res.data.Data.content)
                    const findItem = uuid => {
                        let formItem = {}
                        list.forEach(item => {
                            if (item.uuid === uuid) formItem = item
                            if (item.type === 'subform') {
                                item.list.forEach(n => {
                                    if (n.uuid === uuid) formItem = n
                                })
                            }
                        })
                        return formItem
                    }
                    const setTitle = valueList => {
                        valueList.forEach((item, index) => {
                            const formItem = findItem(item.uuid)
                            item.title = formItem.title
                            if (item.type === 'dateRange') {
                                item.title2 = formItem.title2
                                item.time = formItem.date.time
                                if (item.time) item.title3 = formItem.date.title
                            }
                            if (item.type === 'radioImg' && item.value) item.value.type = formItem.option.type
                            if (item.type === 'checkboxImg' && item.value.length) item.value[0].type = formItem.option.type
                            if (item.type === 'rate') item.value = { ...formItem.rate, value: item.value }
                            if (item.type === 'subform') item.value.forEach(setTitle)
                        })
                    }
                    setTitle(data)
                    this.format(data)
                }
            })
        },
        // 格式化列表
        format (data) {
            const dataList = []
            const text = { component: 'text' }
            const img = { component: 'img' }
            const file = { component: 'file' }
            const optionImg = { component: 'option-img' }
            const rate = { component: 'rate' }
            // 日期区间需要拆分，子表单需要二次循环，所以分为原数据列表，新列表
            const format = (oList, list) => {
                let value = null
                oList.forEach(item => {
                    switch (item.type) {
                    case 'dateRange':
                        const start = { ...text, ...item, value: item.value.start }
                        const end = { ...text, ...item, value: item.value.end, title: item.title2 }
                        list.push(start, end)
                        if (item.time) {
                            const { result, type } = item.value
                            value = result && result + type
                            const time = { ...text, ...item, value, title: item.title3 }
                            list.push(time)
                        }
                        return
                    case 'address':
                        const { region, detail } = item.value
                        value = region + (detail ? '\n' + detail : '')
                        return list.push({ ...text, ...item, value })
                    case 'img':
                        return list.push({ ...img, ...item })
                    case 'file':
                        return list.push({ ...file, ...item })
                    case 'checkbox':
                    case 'checkboxText':
                        value = item.value.join('，')
                        return list.push({ ...text, ...item, value })
                    case 'contacts':
                        value = item.value.map(n => n.realname).join('，')
                        return list.push({ ...text, ...item, value, data: item.value })
                    case 'subform':
                        value = []
                        item.value.forEach((valueItem, valueIndex) => {
                            value.push([])
                            format(valueItem, value[valueIndex])
                        })
                        return list.push({ ...item, value })

                    case 'radioImg':
                        return list.push({ ...optionImg, ...item, value: item.value ? [item.value] : [] })
                    case 'checkboxImg':
                        return list.push({ ...optionImg, ...item })
                    case 'radioMatrix':
                        value = item.value.map(n => `${n.name}：${n.label}`).join('\n')
                        return list.push({ ...text, ...item, value })
                    case 'sort':
                        value = item.value.map((n, i) => `${i + 1}、${n.name}`).join('\n')
                        return list.push({ ...text, ...item, value })
                    case 'rate':
                        return list.push({ ...rate, ...item })
                    case 'gradeClass':
                        value = Array.isArray(item.value) ? item.value.join('，') : item.value
                        return list.push({ ...text, ...item, value })

                    default:
                        return list.push({ ...text, ...item })
                    }
                })
            }
            format(data, dataList)
            this.list = dataList
            this.$emit('init', this.list)
        }
    }
}
</script>

<style lang="less" scoped>
@import "./applicable.less";
/deep/ .text {
    line-height: 20px;
    padding: 6px 0;
}
</style>
