<template>
    <van-form ref='form' class="doc-form instpect-common" >
        <div class="doc-form-label" required>检查项目</div>
        <van-field is-link
            :modelValue="checkName"
            readonly
            placeholder="请选择"
            name="check"
            @click="showCheck = true"
            :rules="[{ required: true, message: '请选择' }]"
        />
        <van-popup v-model:show="showCheck" position="bottom" style="height: 60%">
            <div class="pt-4 h-full flex flex-col popup-checkbox">
                <div class="flex justify-between shrink-0 pb-2">
                    <button class="van-picker__cancel van-haptics-feedback" @click="showCheck = false">取消</button>
                    <span class="text-16">请选择（可多选）</span>
                    <button class="van-picker__confirm van-haptics-feedback" @click="checkConfirm">确认</button>
                </div>
                <div class="bottom-small-line"></div>
                <van-checkbox-group v-model="check" class="px-4 pb-4 pt-2 grow overflow-y-auto">
                    <van-checkbox v-for="(item, index) in store.getDict('CP00111')" :key="index"
                        :name="item.value"
                        class="mb-3">
                        <span :class="{'text-primary': adviseCheck.includes(item.value)}">{{ item.name }}</span>
                    </van-checkbox>
                </van-checkbox-group>
            </div>
        </van-popup>

        <div class="flex flex-col mt-3 check-list">
            <div v-for="(row, index1) in viewData" :key="row.insType"
                class="pt-3 px-2 mb-2 check-list-item"
                :style="`order: ${row.insType}`">
                <div class="required-mark mb-3">{{ row.insName }}</div>
                <template v-for="(item, index2) in row.items">
                    <van-field
                        v-model="item.itemValue"
                        placeholder="请输入"
                        :maxLength="500"
                        :rules="[{ required: true, message: '请录入' }]"
                        :name="['viewData', index1, 'items', index2, 'itemValue'].join('.')"
                        class="no-back mb-2"
                        maxlength="100"
                        v-destory:itemValue="item"
                        v-if="item.itemType === 1"
                    />
                    <van-field :name="['viewData', index1, 'items', index2, 'itemValue'].join('.')"
                        class="no-back mb-2"
                        label="图片上传"
                        label-align="top"
                        v-if="item.itemType === 5">
                        <template #input>
                            <DocImageUpload :imageData="item.imageData"
                                @change="(ids, option) => item.itemValue = ids"
                                :maxLength="3"
                                description="请上传JPG、PNG格式图片，文件大小不超过10M"
                                class="w-full"/>
                        </template>
                    </van-field>
                </template>
            </div>

        </div>
    </van-form>
</template>

<script>
import { checkDefault } from './config.js'
import { useStore } from '@/doctor/store/index.js'
import { getInspectCode } from '@/api/doctor/disease.js'
import DocImageUpload from '@/doctor/components/docImageUpload/DocImageUpload.vue'

export default {
    name: 'CheckCommon',
    components: {
        DocImageUpload
    },
    props: {
        // 初始化数据
        info: { default: () => [] },
        // 慢病
        disease: [String, Number]
    },
    data() {
        return {
            store: useStore(),
            check: [],
            checkName: '',
            viewData: [],
            // 可显示的检验项
            codeTable: [],
            showCheck: false,
        }
    },
    computed: {
        // 推荐选中的项目
        adviseCheck() {
            return checkDefault(this.disease)
        }
    },
    created() {
        this.init()
    },
    methods: {
        init() {
            if (this.info.check) {
                let check = this.info.check
                this.check = typeof check === 'string' ? check.split(',') : check
            }
            getInspectCode(2).then(res => {
                console.log(res)
                const check = this.check
                const data = this.info.items || []
                this.codeTable = res.data || []
                this.codeTable.forEach(e => {
                    const item = data.find(i => e.itemCode === i.itemCode) || {}
                    // 根据表单类型处理
                    if (item.itemType === 5) {
                        e.itemValue = item.inspectFile || ''
                        e.imageData = item.inspectFileList || []
                    } else {
                        e.itemValue = item.itemValue
                    }
                })
                this.viewData = check.map(val => {
                    const items = this.codeTable.filter(e => e.insType === val)
                    if (!items.length) return {}
                    return {
                        insName: items[0].insName,
                        insType: val,
                        items: [...items]
                    }
                })
            })
        },
        submit() {
            return new Promise((resolve, reject) => {
                this.$refs.form.validate().then(() => {
                    const check = this.check.join(',')
                    let data = []
                    this.viewData.forEach(e => {
                        data = data.concat(e.items)
                    })
                    data = data.map(e => {
                        // 根据表单类型处理
                        let value = e.itemValue
                        return {
                            ...e,
                            itemValue: value
                        }
                    })
                    console.log(data, check)
                    resolve({ check, data })
                }).catch((e) => {
                    reject(e)
                })
            })
        },
        checkConfirm() {
            this.checkName = this.store.getDict('CP00111').map(e => {
                return this.check.includes(e.value) ? e.name : ''
            }).filter(e => e).join('、')
            this.showCheck = false
            this.checkChange(this.check)
            setTimeout(() => {
                this.$refs.form.resetValidation()
            }, 0)
            console.log('checkChange', this.viewData)
        },
        checkChange(val) {
            const viewData = this.viewData
            const addValue = val.filter(e => !viewData.find(i => i.insType === e))
            const delValue = viewData.filter(i => !val.includes(i.insType)).map(e => e.insType)
            if (delValue.length) {
                this.viewData = this.viewData.filter(e => !delValue.includes(e.insType))
            }
            if (addValue.length) {
                addValue.forEach(val => {
                    const items = this.codeTable.filter(e => e.insType === val)
                    if (!items.length) return {}
                    this.viewData.push({
                        insName: items[0].insName,
                        insType: val,
                        items: [...items]
                    })
                })
            }
        }
    },
}
</script>

<style lang="less" scoped>
.check-list {
    .check-list-item {
        background-color: #F5F5F5;
        border-radius: 8px;
    }
    :deep(.van-field) {
        border-radius: .08rem;
    }
}
</style>

