<template>
    <div class="diagnose-form-cont">
        <van-form ref='form' class="doc-form">
            <div class='font-semibold'>诊断信息</div>
            <div class='doc-form-label' required>纳入管理日期</div>
            <van-field
                v-model="form.manageDate"
                is-link
                readonly
                :disabled="!!info.manageDate"
                name="manageDate"
                placeholder="请选择"
                @click="showDate('manageDate')"
                :rules="rules.requiredSelect"
            />
            <van-popup v-model:show="dateOption.show" position="bottom">
                <van-date-picker
                    :min-date="dateRange.min"
                    :max-date="dateRange.max"
                    @confirm="dateConfirm" @cancel="dateOption.show = false" />
            </van-popup>

            <div class='doc-form-label' required>诊断名称</div>
            <van-field
                v-model="form.diseaseName"
                is-link
                readonly
                name="manageDate"
                placeholder="请选择"
                @click="showIcd = true"
                :rules="rules.requiredSelect"
            />
            <DiagnosePicker v-model:show="showIcd"
                v-model:value="form.icdCode"
                :diseaseType="diseaseType"
                @change="icdChange"/>

            <div class='doc-form-label' required>诊断日期</div>
            <van-field
                v-model="form.diseaseDate"
                is-link
                readonly
                name="diseaseDate"
                placeholder="请选择"
                @click="showDate('diseaseDate')"
                :rules="rules.requiredSelect"
            />

            <div class='doc-form-label' required v-if="![1, 4].includes(diseaseType)">诊断评估</div>
            <template v-if="diseaseType == 1">
                <div class='doc-form-label' required>高血压分级</div>
                <van-field
                    v-model="form.diagnoseAssessName"
                    is-link
                    readonly
                    name="diagnoseAssess"
                    placeholder="请选择"
                    @click="showOptions('diagnoseAssess', 'CP00096')"
                    :rules="rules.requiredSelect"
                />
                <div class='doc-form-label' required>高血压危险分层</div>
                <van-field
                    v-model="form.diagnoseLevelName"
                    is-link
                    readonly
                    name="diagnoseLevel"
                    placeholder="请选择"
                    @click="showOptions('diagnoseLevel', 'CP00097')"
                    :rules="rules.requiredSelect"
                />
            </template>

            <template v-else-if="diseaseType == 4">
                <div class='doc-form-label' required>缺血性脑卒中</div>
                <van-field
                    v-model="form.diagnoseResultName"
                    is-link
                    readonly
                    name="diagnoseResult"
                    placeholder="请选择"
                    @click="showOptions('diagnoseResult', 'CP00103', 'checkbox')"
                />
                <div class='doc-form-label' required>出血性脑卒中</div>
                <van-field
                    v-model="form.diagnoseLevelName"
                    is-link
                    readonly
                    name="diagnoseLevel"
                    placeholder="请选择"
                    @click="showOptions('diagnoseLevel', 'CP00104')"
                />
            </template>
            <template v-else-if="[2,3].includes(diseaseType)">
                <!-- 糖尿病 冠心病 -->
                <van-field
                    v-model="form.diagnoseResultName"
                    is-link
                    readonly
                    name="diagnoseResult"
                    placeholder="请选择"
                    @click="showOptions('diagnoseResult', resultSelectOption.dictMap[diseaseType], 'checkbox')"
                    :rules="rules.requiredSelect"
                />
            </template>
            <template v-else>
                <!-- 慢阻肺 慢性肾脏病 血脂异常 -->
                <van-field
                    v-model="form.diagnoseAssessName"
                    is-link
                    readonly
                    name="diagnoseAssess"
                    placeholder="请选择"
                    @click="showOptions('diagnoseAssess', resultSelectOption.dictMap[diseaseType])"
                    :rules="rules.requiredSelect"
                />
            </template>


            <van-popup v-model:show="resultSelectOption.show" position="bottom">
                <div class="pt-4 pb-4 popup-checkbox">
                    <div class="flex justify-between pb-2">
                        <button class="van-picker__cancel van-haptics-feedback" @click="optionCancel">取消</button>
                        <span class="text-16" >请选择 {{ resultSelectOption.formType === 'radio' ? '（仅单选）' : '（可多选）' }}</span>
                        <div v-if="resultSelectOption.formType === 'radio'" style="width: .32rem;"></div>
                        <button v-else class="van-picker__confirm van-haptics-feedback" @click="optionConfirm">确认</button>
                    </div>
                    <div class="bottom-small-line"></div>
                    <CheckBtn v-if="resultSelectOption.formType === 'radio'"
                        v-model:value="resultSelectOption.value"
                        :options="resultSelectOption.array"
                        round column-1
                        class="py-3 px-4"
                        activeStyleNone :clearable="false"
                        @change="optionChange"/>

                    <CheckBtn v-else
                        v-model:value="resultSelectOption.value"
                        :options="resultSelectOption.array"
                        multiple round column-1
                        class="py-3 px-4" />
                </div>
            </van-popup>
        </van-form>

        <div class='mt-5 mb-2' style="color: #595959;">是否进行检验</div>
        <van-field :border="false"
            name="isInspect"
            style="padding: 0"
            :rules="rules.requiredSelect">
            <template #input>
                <van-radio-group v-model="form.isInspect"
                    direction="horizontal"
                    shape="dot"
                    class="w-full doc-radio-group">
                    <van-radio v-for="item in store.getDict('CP00120')"
                        :key="item.value" :name="item.value"
                        label-position="left">{{item.name}}</van-radio>
                </van-radio-group>
            </template>
        </van-field>
        <InstpectCommon v-if="form.isInspect == 1"
            :disease="diseaseType"
            :imageVisible="true"
            :info="inspectInfo"
            ref="inspect"/>

        <div class='mt-5 mb-2' style="color: #595959;">是否进行检查</div>
        <van-field :border="false"
            name="isCheck"
            style="padding: 0"
            :rules="rules.requiredSelect">
            <template #input>
                <van-radio-group v-model="form.isCheck"
                    direction="horizontal"
                    shape="dot"
                    class="w-full doc-radio-group">
                    <van-radio v-for="item in store.getDict('CP00120')"
                        :key="item.value" :name="item.value"
                        label-position="left">{{item.name}}</van-radio>
                </van-radio-group>
            </template>
        </van-field>
        <CheckCommon v-if="form.isCheck == 1"
           :disease="diseaseType"
           :info="checkInfo"
           ref="check"/>
        <DoctorInfo :info="info" ref="DoctorInfo"/>
    </div>
</template>

<script>
import { useStore } from '@/doctor/store'
import { fetchDataHandle } from '@/utils/common.js'
import InstpectCommon from '../common/Instpect.vue'
import CheckCommon from '../common/Check.vue'
import DiagnosePicker from './DiagnosePicker.vue'
import CheckBtn from '@/doctor/components/checkBtn/CheckBtn.vue'
import DoctorInfo from './DoctorInfo.vue'
import dayjs from 'dayjs'

const defaultForm = (info = {}) => {
    const form = {
        id: undefined,
        residentInfoId: undefined,
        // 纳入管理日期
        manageDate: undefined,
        // 诊断名称code
        icdCode: undefined,
        diseaseName: undefined,
        // 诊断日期
        diseaseDate: undefined,
        // 诊断评估
        // 用于单选
        diagnoseAssess: undefined,
        diagnoseAssessName: undefined,
        // 高血压危险分层 出血性脑卒中
        diagnoseLevel: undefined,
        diagnoseLevelName: undefined,
        // 用于多选
        diagnoseResult: [],
        diagnoseResultName: undefined,
        // 是否需要检查
        isInspect: 2,
        // 是否需要检查
        isCheck: 2,
        diseaseType: undefined,
        checkItem: undefined,
        checkItemName: undefined,
        inspectItem: undefined,
        inspectItemName: undefined,
        source: undefined,
    }
    Reflect.ownKeys(form).forEach(key => {
        if (info[key] != undefined) {
            form[key] = info[key]
        }
    })
    return form
}

export default {
    components: {
        InstpectCommon,
        CheckCommon,
        DiagnosePicker,
        CheckBtn,
        DoctorInfo
    },
    props: {
        info: { default: () => ({}) }
    },
    data() {
        return {
            store: useStore(),
            form: defaultForm(),
            // 纳入管理日期
            dateRange: {
                min: undefined,
                max: undefined
            },
            rules: {
                requiredSelect: [{ required: true, message: '请选择' }],
                requiredInput: [{ required: true, message: '请输入' }]
            },
            // 诊断名称
            showIcd: false,
            // 诊断评估 选择配置
            resultSelectOption: {
                show: false,
                formType: '', // radio checkbox
                field: '', // diagnoseAssess diagnoseLevel diagnoseResult
                array: [],
                name: '',
                value: undefined,
                dictMap: {
                    2: 'CP00101',
                    3: 'CP00102',
                    5: 'CP00105',
                    6: 'CP00106',
                    7: 'CP00095'
                }
            },
            // 日期选择选择
            dateOption: {
                show: false,
                field: ''
            }
        }
    },
    computed: {
        diseaseType() {
            return this.info.diseaseType
        },
        // 检查项
        checkList() {
            const diagnoseInspectList = this.info.diagnoseInspectList || []
            return diagnoseInspectList.filter(e => e.projectType === 1)
        },
        // 检验项
        inspectList() {
            const diagnoseInspectList = this.info.diagnoseInspectList || []
            return diagnoseInspectList.filter(e => e.projectType === 0)
        },
        // 检验项图片
        inspectFileList() {
            return this.info.inspectFileList || []
        },
        inspectInfo() {
            const projects = [], insTypes = []
            this.inspectList.forEach(e => {
                const pList = e.inspectDetailed ? JSON.parse(e.inspectDetailed) : []
                const iList = pList.map( i => i.insType) || []
                projects.push(...pList)
                insTypes.push(...iList)
            })
            return {
                image: this.info.inspectFile || '',
                imageData: this.info.inspectFileList || [],
                items: projects,
                inspect: Array.from(new Set(insTypes))
            }
        },
        checkInfo() {
            const insTypes = [], items = []
            this.checkList.forEach(e => {
                const pList = e.inspectDetailed ? JSON.parse(e.inspectDetailed) : []
                const iList = pList.map( i => i.insType) || []
                insTypes.push(...iList)
                if (e.inspectFile) {
                    items.push({
                        itemValue: e.inspectFile,
                        itemType: 5,
                        inspectFile: e.inspectFile,
                        inspectFileList: e.inspectFileList,
                        insType: pList[0]?.insType,
                        insName: pList[0]?.insName,
                        itemCode: pList[0]?.insType + '-2'
                    })
                }
                //未上传图片并存在结论的数据
                items.push({
                    itemValue: pList[0]?.itemValue,
                    itemType: 1,
                    inspectFile: undefined,
                    inspectFileList: [],
                    insType: pList[0]?.insType,
                    insName: pList[0]?.insName,
                    itemCode: pList[0]?.itemCode
                })
            })
            return {
                items,
                check: Array.from(new Set(insTypes))
            }
        }
    },
    created() {
        this.init()
    },
    methods: {
        init() {
            const date = dayjs()
            this.form.manageDate = date.format('YYYY-MM-DD')
            // this.form._manageDate = [date.year(), date.month() + 1, date.date()]
            this.dateRange.max = new Date(date.year(), date.month(), date.date())
            this.dateRange.min = new Date(date.year() - 20, date.month(), date.date())

        },
        async submit() {
            try {
                await this.$refs.form.validate()
                if (this.form.diseaseType === 4) {
                    const diagnoseResult = this.form.diagnoseResult || []
                    if (!diagnoseResult.length && !this.form.diagnoseLevel) {
                        this.$message.info('请在 缺血性脑卒中 和 出血性脑卒中 中选择一项填写')
                        this.$refs.form.scrollToField('diagnoseResult')
                        return
                    }
                }
                this.form.diagnoseInspectList = []
                if (this.form.isInspect === 1) {
                    let { inspect: inspectItems, data, image} = await this.$refs.inspect.submit()
                    let inspectObj = {}
                    for (let item of data) {
                        if (inspectObj[item.insType] === void 0) {
                            inspectObj[item.insType] = []
                        }
                        const insItem = {
                            insType: item.insType,
                            insName: item.insName,
                            itemCode: item.itemCode,
                            itemName: item.itemName,
                            itemType: item.itemType,
                            itemValue: item.itemValue,
                            unit: item.unit
                        }
                        inspectObj[item.insType].push(insItem)
                    }
                    for (let diagType in inspectObj) {
                        let diagInspect = {
                            projectType: 0,
                            diagnoseType: diagType,
                            diagnoseName: inspectObj[diagType][0].insName,
                            inspectDetailed: JSON.stringify(inspectObj[diagType])
                        }
                        // inspectItems.push(inspectObj[diagType][0].insType)
                        this.form.diagnoseInspectList.push(diagInspect)
                    }
                    this.form.inspectItem = inspectItems
                    this.form.inspectFile = image
                }
                if (this.form.isCheck === 1) {
                    let { check: checkItems, data } = await this.$refs.check.submit()
                    let checkObj = {}, fileObj = {}
                    for (let item of data) {
                        if (item.itemType === 5 && item.itemValue !== void 0 && item.itemValue !== '') {
                            fileObj[item.insType] = item.itemValue
                        } else {
                            if (checkObj[item.insType] === void 0) {
                                checkObj[item.insType] = []
                            }
                            let checkItem = {
                                insType: item.insType,
                                insName: item.insName,
                                itemCode: item.itemCode,
                                itemName: item.itemName,
                                itemType: item.itemType,
                                itemValue: item.itemValue
                            }
                            checkObj[item.insType].push(checkItem)
                        }
                    }
                    for (let diagType in checkObj) {
                        let diagCheck = {
                            projectType: 1,
                            diagnoseType: diagType,
                            diagnoseName: checkObj[diagType][0].insName,
                            inspectDetailed: JSON.stringify(checkObj[diagType]),
                            inspectFile: fileObj[diagType]
                        }
                        // checkItems.push(checkObj[diagType][0].insType);
                        this.form.diagnoseInspectList.push(diagCheck)
                    }
                    this.form.checkItem = checkItems
                }
                const doctorInfo = await this.$refs.DoctorInfo.submit()
                let query = fetchDataHandle(this.form, {
                    diagnoseResult: 'arrToStr'
                })
                return {
                    ...query,
                    ...doctorInfo
                }
            } catch(err) {
                this.$message.info('表单校验不通过')
                const array = err || []
                if (array.length) {
                    this.$refs.form.scrollToField(array[0].name)
                }
            }
        },
        // 日期确定
        dateConfirm({ selectedValues }) {
            this.form[this.dateOption.field] = selectedValues.join('-')
            this.dateOption.show = false
        },
        // 诊断名称
        icdChange(option) {
            this.form.diseaseName = option.diseaseName
        },
        // 日期选择
        showDate(field) {
            if (field === 'manageDate' && this.info.manageDate) return
            this.dateOption.field = field
            this.dateOption.show = true
        },
        // 诊断评估 选择配置
        showOptions(field, dict, formType = 'radio') {
            this.resultSelectOption.field = field
            this.resultSelectOption.formType = formType
            this.resultSelectOption.array = this.store.getDict(dict)
            this.resultSelectOption.value = this.form[field]
            this.resultSelectOption.show = true
        },
        optionCancel() {
            this.resultSelectOption.show = false
            this.resultSelectOption.value = undefined
        },
        optionConfirm() {
            const field = this.resultSelectOption.field
            const fieldName = field + 'Name'
            this.form[field] = this.resultSelectOption.value
            console.log('this.form[field]', this.form[field])
            this.form[fieldName] = this.resultSelectOption.array.map(e => {
                return this.form[field].includes(e.value) ? e.name : ''
            }).filter(e => e).join('、')
            this.resultSelectOption.show = false
            this.resultSelectOption.value = undefined
        },
        optionChange(val, option) {
            const field = this.resultSelectOption.field
            const fieldName = field + 'Name'
            this.form[field] = val
            this.form[fieldName] = option.name
            this.resultSelectOption.show = false
            this.resultSelectOption.value = undefined
        },
        // 处理诊断评估字段回显
        fieldNameHandler() {
            const mark = this.diseaseType
            if (mark == 1) {
                this.form.diagnoseAssessName = this.store.getDictValue('CP00096', this.form.diagnoseAssess)
                this.form.diagnoseLevelName = this.store.getDictValue('CP00097', this.form.diagnoseLevel)
            } else if ([2, 3].includes(mark)) {
                this.form.diagnoseResultName = this.store.getDictValue(this.resultSelectOption.dictMap[mark], this.form.diagnoseResult)
            } else if (mark == 4) {
                this.form.diagnoseResultName = this.store.getDictValue('CP00103', this.form.diagnoseResult)
                this.form.diagnoseLevelName = this.store.getDictValue('CP00104', this.form.diagnoseLevel)
            } else if ([5, 6, 7].includes(mark)) {
                this.form.diagnoseAssessName = this.store.getDictValue(this.resultSelectOption.dictMap[mark], this.form.diagnoseAssess)
            }
        }
    },
    watch: {
        info: {
            handler(info) {
                this.form = defaultForm(info)
                this.fieldNameHandler()
            },
            immediate: true
        }
    }
}
</script>

<style lang="less" scoped>

</style>
