<template>
    <div class="screening-first-cont">
        <van-form ref='form' class="doc-form" >
            <div class='font-semibold'>筛查信息</div>
            <div class='doc-form-label' required>既往史</div>
            <van-field is-link
                v-model='form.medicalHistoryName'
                readonly
                placeholder='请选择'
                name="medicalHistory"
                :rules='rules.medicalHistory'
                @click="showMedical = true"
            />
            <van-popup v-model:show="showMedical" 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="showMedical = false">取消</button>
                        <span class="text-16" >既往史（可多选）</span>
                        <button class="van-picker__confirm van-haptics-feedback" @click="medicalConfirm">确认</button>
                    </div>
                    <div class="bottom-small-line"></div>
                    <!-- <van-checkbox-group v-model="form.medicalHistory" class="px-4 pb-4 pt-2">
                        <van-checkbox v-for="(item, index) in store.getDict('CP00118')" :key="index"
                            @click="medicalChange"
                            :name="item.value"
                            class="mb-3">{{ item.name }}</van-checkbox>
                    </van-checkbox-group> -->
                    <CheckBtn v-model:value="form.medicalHistory"
                        :options="medicalHistoryArray"
                        multiple round column-1
                        class="py-3 px-4"
                        @change="medicalChange" />
                </div>
            </van-popup>

            <div class="flex tip-box">
                <div class='doc-form-label shrink-0' required>家族史</div>
                <span class="grow text-end text-ellipsis">若一级家属(如父母)有家族病史，则请选择</span>
            </div>
            <van-field is-link
                v-model='form.familyHistoryName'
                name="familyHistory"
                readonly
                placeholder='请选择'
                :rules='rules.familyHistory'
                @click="showFamily = true"
            />
            <van-popup v-model:show="showFamily" 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="showFamily = false">取消</button>
                        <span class="text-16" >家族史（可多选）</span>
                        <button class="van-picker__confirm van-haptics-feedback" @click="familyConfirm">确认</button>
                    </div>
                    <div class="bottom-small-line"></div>
                    <!-- <van-checkbox-group v-model="form.familyHistory" class="p-4">
                        <van-checkbox v-for="(item, index) in store.getDict('CP00167').filter(e => e.value != 7)" :key="index"
                            @click="familyChange"
                            :name="item.value"
                            class="mb-3">{{ item.name }}</van-checkbox>
                    </van-checkbox-group> -->
                    <CheckBtn v-model:value="form.familyHistory"
                        :options="familyHistoryArray"
                        multiple round column-1
                        class="py-3 px-4"
                        @change="familyChange" />
                </div>
            </van-popup>

            <div class='doc-form-label'>年龄</div>
            <van-field v-model="form.currentAge"
                name="currentAge"
                type="digit"
                placeholder="请输入年龄"
                readonly
                maxlength="10"
            >
                <template #extra>
                    <span class="ml-1">岁</span>
                </template>
            </van-field>

            <div class='doc-form-label' required>身高</div>
            <van-field required
                v-model="form.height"
                name="height"
                type="number"
                placeholder="输入值10~300，1位小数"
                maxlength="10"
                :rules="rules.height"
            >
                <template #extra>
                    <span class="ml-1">cm</span>
                </template>
            </van-field>

            <div class='doc-form-label' required>体重</div>
            <van-field required
                v-model="form.weight"
                name="weight"
                type="number"
                placeholder="输入值20~500，2位小数"
                maxlength="10"
                :rules="rules.weight"
            >
                <template #extra>
                    <span class="ml-1">kg</span>
                </template>
            </van-field>

            <div class='doc-form-label'>BMI</div>
            <van-field v-model="form.bmi"
                name="bmi"
                type="number"
                placeholder="请输入"
                maxlength="10"
                readonly
            >
                <template #extra>
                    <span class="ml-1">kg/m²</span>
                </template>
            </van-field>

            <div class='doc-form-label'>腰围</div>
            <van-field v-model="form.waistline"
                name="waistline"
                type="number"
                placeholder="输入值10~150，1位小数"
                maxlength="10"
                :rules="rules.waistline"
            >
                <template #extra>
                    <span class="ml-1">cm</span>
                </template>
            </van-field>

            <div class='doc-form-label' required>是否吸烟</div>
            <van-field
                name="isSmoking"
                class="no-back"
                style="padding: 0"
                :rules="rules.isSmoking">
                <template #input>
                    <van-radio-group v-model="form.isSmoking"
                        direction="horizontal"
                        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>

            <div class="flex items-center justify-between tip-box">
                <div class='doc-form-label shrink-0' >现测血压（mmHg）</div>
                <BloodPressurePanel :pressureObj="pressureObj"/>
            </div>
            <div class="sub-text my-3" >第一次</div>
            <table class="w-full mb-2">
                <tr class="sub-text"  >
                    <td>收缩压(高压)</td>
                    <td style="width: 1em"></td>
                    <td>舒张压(低压)</td>
                </tr>
                <tr>
                    <td class="flex items-center">
                        <van-field v-model="form.pressureOneSbp"
                            name="pressureOneSbp" 
                            label=""
                            type="number"
                            placeholder="60~300，整数"
                            maxlength="10"
                            :rules="rules.pressureDbp"
                            error-message-align="left"
                            input-align="left"
                            class="table-field"
                        />
                    </td>
                    <td class="text-center">
                        <span class="divide">/</span>
                    </td>
                    <td>
                        <van-field v-model="form.pressureOneDbp"
                            name="pressureOneDbp" 
                            label=""
                            type="number"
                            placeholder="30~300，整数"
                            maxlength="10"
                            :rules="rules.pressureSbp"
                            error-message-align="left"
                            input-align="left"
                            class="table-field"
                        />
                    </td>
                </tr>
            </table>
            <BloodPressureBt :pressureObj="pressureObj" @getValue="setPressureOne">第一次测量</BloodPressureBt>
            <div class="sub-text my-3" >第二次</div>
            <table class="w-full mb-2">
                <tr class="sub-text" >
                    <td>收缩压(高压)</td>
                    <td style="width: 1em"></td>
                    <td>舒张压(低压)</td>
                </tr>
                <tr>
                    <td>
                        <van-field v-model="form.pressureTwoSbp"
                            name="pressureTwoSbp" 
                            label=""
                            type="number"
                            placeholder="60~300，整数"
                            maxlength="10"
                            :rules="rules.pressureDbp"
                            error-message-align="left"
                            input-align="left"
                            class="table-field"
                        />
                    </td>
                    
                    <td class="text-center">
                        <span class="divide">/</span>
                    </td>
                    <td>
                        <van-field v-model="form.pressureTwoDbp"
                            name="pressureTwoDbp" 
                            label=""
                            type="number"
                            placeholder="30~300，整数"
                            maxlength="10"
                            :rules="rules.pressureSbp"
                            error-message-align="left"
                            input-align="left"
                            class="table-field"
                        />
                    </td>
                </tr>
            </table>
            <BloodPressureBt :pressureObj="pressureObj" @getValue="setPressureTwo">第二次测量</BloodPressureBt>

            <div class='doc-form-label'>空腹血糖</div>
            <van-field v-model="form.fastingGlucose"
                name="fastingGlucose" 
                type="number"
                placeholder="输入值0~50，2位小数"
                maxlength="10"
                :rules="rules.fastingGlucose"
            >
                <template #extra>
                    <span class="ml-1">mmol/L</span>
                </template>
            </van-field>

            <div class='doc-form-label'>低密度脂蛋白胆固醇</div>
            <van-field v-model="form.ldlCholesterin"
                name="ldlCholesterin" 
                type="number"
                placeholder="输入值0~50，2位小数"
                maxlength="10"
                :rules="rules.ldlCholesterin"
            >
                <template #extra>
                    <span class="ml-1">mmol/L</span>
                </template>
            </van-field>

            <div class='doc-form-label'>血清总胆固醇</div>
            <van-field v-model="form.serumCholesterin"
                name="serumCholesterin"
                type="number"
                placeholder="输入值0~50，1位小数"
                maxlength="10"
                :rules="rules.serumCholesterin"
            >
                <template #extra>
                    <span class="ml-1">mmol/L</span>
                </template>
            </van-field>

            <div class='doc-form-label'>高密度脂蛋白胆固醇</div>
            <van-field v-model="form.hdlCholesterin"
                name="hdlCholesterin" 
                type="number"
                placeholder="输入值0~50，1位小数"
                maxlength="10"
                :rules="rules.hdlCholesterin"
            >
                <template #extra>
                    <span class="ml-1">mmol/L</span>
                </template>
            </van-field>

            <div class="flex tip-box">
                <div class='doc-form-label shrink-0' required>运动</div>
                <span class="grow text-end text-ellipsis">每周保持150分钟内中等或75分钟内的高强度身体活动</span>
            </div>
            <van-field
                name="exerciseIntensity"
                class="no-back"
                style="padding: 0"
                :rules="rules.exerciseIntensity">
                <template #input>
                    <van-radio-group v-model="form.exerciseIntensity"
                        direction="horizontal"
                        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>

            <div class='doc-form-label' required>高危评估结果</div>
            <van-field
                name="screenResult"
                class="no-back"
                style="padding: 0"
                :rules="rules.screenResult">
                <template #input>
                    <van-radio-group v-model="form.screenResult"
                        direction="horizontal"
                        class="w-full doc-radio-group">
                        <van-radio v-for="item in store.getDict('CP00119')"
                            :key="item.value" :name="item.value"
                            label-position="left">{{item.name}}</van-radio>
                    </van-radio-group>
                </template>
            </van-field>

            <DoctorInfo />

            <div class='doc-form-label' required>筛查日期</div>
            <van-field
                v-model="form.screenDate"
                is-link
                readonly
                name="screenDate"
                placeholder="请选择"
                @click="showScreenDate = true"
                :rules="rules.screenDate"
            />
            <van-popup v-model:show="showScreenDate" position="bottom">
                <van-date-picker v-model="form._screenDate" 
                    :min-date="screenDateRange.min"
                    :max-date="screenDateRange.max"
                    @confirm="screenDateConfirm" @cancel="showScreenDate = false" />
            </van-popup>
        </van-form>
    </div>
</template>

<script>
import { useStore } from '@/doctor/store'
import { checkboxReject, fetchDataHandle } from '@/utils/common.js'
import dayjs from 'dayjs'
import DoctorInfo from './DoctorInfo.vue'
import CheckBtn from '@/doctor/components/checkBtn/CheckBtn.vue'
import { BloodPressurePanel, BloodPressureBt } from '@/doctor/components/bloodPressure/index.js'

const defaultForm = (info = {}) => {
    const form = {
        id: undefined,
        residentInfoId: undefined,
        // 年龄
        currentAge: undefined,
        // 既往史
        medicalHistory: [],
        medicalHistoryName: undefined,
        // 身高
        height: undefined,
        // 体重
        weight: undefined,
        bmi: undefined,
        // 腰围
        waistline: undefined,
        // 是否吸烟
        isSmoking: undefined,
        // 家族史
        familyHistory: [],
        familyHistoryName: undefined,
        // 空腹血糖
        fastingGlucose: undefined,
        // 血清总胆固醇
        serumCholesterin: undefined,
        // 低密度脂蛋白胆固醇
        ldlCholesterin: undefined,
        // 高密度脂蛋白胆固醇
        hdlCholesterin: undefined,
        // 运动
        exerciseIntensity: undefined,
        // 筛查日期
        screenDate: undefined,
        _screenDate: undefined,
        // 血压第一次
        pressureOneDbp: undefined,
        pressureOneSbp: undefined,
        // 血压第二次
        pressureTwoDbp: undefined,
        pressureTwoSbp: undefined,
        // 高危评估结果（1：一般人群（小于3个指标）；2：高危人群（大于等于3个指标））
        screenResult: 1,
        // 高危项目 CP00113
        highItem: undefined,
        gender: undefined
    }
    Reflect.ownKeys(form).forEach(key => {
        if (info[key] != undefined) {
            form[key] = info[key]
        }
    })
    return form
}
export default {
    components: {
        CheckBtn,
        DoctorInfo,
        BloodPressurePanel,
        BloodPressureBt
    },
    props: {
        info: { default: () => ({}) }
    },
    inject: ['pressureObj'],
    data() {
        return {
            form: defaultForm(),
            rules: {
                medicalHistory: [{ required: true, message: '请选择' }],
                familyHistory: [{ required: true, message: '请选择' }],
                exerciseIntensity: [{ required: true, message: '请选择' }],
                isSmoking: [{ required: true, message: '请选择' }],
                screenResult: [{ required: true, message: '请选择' }],
                screenDate: [{ required: true, message: '请选择' }],
                height: [{ required: true, message: '请输入' },
                    { pattern: /^([1-9]\d{1}(?:\.\d{1})?|[1-2]\d{2}(?:\.\d{1})?|300)$/, message: '输入值在10~300内，1位小数' }],
                weight: [{ required: true, message: '请输入' },
                    { pattern: /^([2-9]\d{1}(?:\.\d{1,2})?|[1-4]\d{2}(?:\.\d{1,2})?|500)$/, message: '输入值在20~500内，2位小数' }],
                waistline: [{
                    pattern: /^([1-9]\d{1}(?:\.\d{1})?|[1][0-4]\d(?:\.\d{1})?|150)$/, message: '输入值在10~150内，1位小数', validateEmpty: false }],
                fastingGlucose: [{
                    pattern: /^(?:0(?:\.\d{1,2})?|[1-4]\d{0,1}(?:\.\d{1,2})?|[1-9]{0,1}(?:\.\d{1,2})?|50)$/, message: '输入值0~50，2位小数', validateEmpty: false }],
                serumCholesterin: [{
                    pattern: /^(?:0(?:\.\d{1})?|[1-4]\d{0,1}(?:\.\d{1})?|[1-9]{0,1}(?:\.\d{1})?|50)$$/, message: '输入值0~50，1位小数', validateEmpty: false }],
                ldlCholesterin: [{
                    pattern: /^(?:0(?:\.\d{1,2})?|[1-4]\d{0,1}(?:\.\d{1,2})?|[1-9]{0,1}(?:\.\d{1,2})?|50)$/, message: '输入值0~50，2位小数', validateEmpty: false }],
                hdlCholesterin: [{
                    pattern: /^(?:0(?:\.\d{1})?|[1-4]\d{0,1}(?:\.\d{1})?|[1-9]{0,1}(?:\.\d{1})?|50)$$/, message: '输入值0~50，1位小数', validateEmpty: false }],
                pressureDbp: [{ pattern: /^([6-9]\d{1}|[1-2]\d{2}|300)$/, message: '60~300，整数', validateEmpty: false }],
                pressureSbp: [{ pattern: /^([3-9]\d{1}|[1-2]\d{2}|300)$/, message: '30~300，整数', validateEmpty: false }],
            },
            // 既往史
            showMedical: false,
            // 家族史
            showFamily: false,
            // 筛查日期
            showScreenDate: false,
            // 筛查日期可选范围
            screenDateRange: {
                min: undefined,
                max: undefined
            },
            store: useStore()
        }
    },
    computed: {
        // BMI
        bmi() {
            const { height, weight } = this.form
            return height && weight ? (weight / (height / 100 * height / 100)).toFixed(2) : undefined
        },
        // 既往史
        medicalHistoryArray() {
            const result = []
            this.store.getDict('CP00118').forEach(e => {
                if (e.value == 9) {
                    result.unshift(e)
                    return
                }
                result.push(e)
            })
            return result
        },
        // 家族史
        familyHistoryArray() {
            const result = []
            this.store.getDict('CP00167').forEach(e => {
                if (e.value == 9) {
                    result.unshift(e)
                    return
                }
                result.push(e)
            })
            return result
        }
    },
    methods: {
        init() {
            const date = dayjs()
            this.form.screenDate = date.format('YYYY-MM-DD')
            this.form._screenDate = [date.year(), date.month() + 1, date.date()]
            this.screenDateRange.max = new Date(date.year(), date.month(), date.date())
            this.screenDateRange.min = new Date(date.year() - 20, date.month(), date.date())
        },
        submit() {
            return this.$refs.form.validate()
        },
        // 既往史
        medicalConfirm() {
            this.form.medicalHistoryName = this.store.getDict('CP00118').map(e => {
                return this.form.medicalHistory.includes(e.value) ? e.name : ''
            }).filter(e => e).join('、')
            this.showMedical = false
        },
        medicalChange(val) {
            this.form.medicalHistory = checkboxReject(this.form.medicalHistory, [9])
        },
        // 家族史
        familyConfirm() {
            this.form.familyHistoryName = this.store.getDict('CP00167').map(e => {
                return this.form.familyHistory.includes(e.value) ? e.name : ''
            }).filter(e => e).join('、')
            this.showFamily = false
        },
        familyChange() {
            this.form.familyHistory = checkboxReject(this.form.familyHistory, [9])
        },
        // 筛查日期
        screenDateConfirm({ selectedValues }) {
            this.form.screenDate = selectedValues.join('-')
            this.showScreenDate = false
        },
        resultHandle() {
            const {currentAge, height = 0, weight = 0, waistline, familyHistory = [], isSmoking, gender,
                pressureOneSbp, pressureOneDbp, pressureTwoSbp, pressureTwoDbp, fastingGlucose, ldlCholesterin, serumCholesterin} = this.form
            let list = []
            if (currentAge >= 50) {
                list.push(1)
            }
            let bmi = parseFloat(this.bmi)
            if ((bmi >= 24)||
                (gender == 2 && waistline >=80) ||
                (gender == 1 && waistline >=85) ){
                list.push(2)
            }
            if (isSmoking == 1) {
                list.push(3)
            }
            if (familyHistory && familyHistory.length && (familyHistory.includes(1) || familyHistory.includes(2) ||
                familyHistory.includes(3) || familyHistory.includes(4) || familyHistory.includes(5) || familyHistory.includes(6))) {
                list.push(4)
            }
            if ((pressureOneSbp >= 130 || pressureTwoSbp >= 130) ||
                (pressureOneDbp >= 85 || pressureTwoDbp >= 85)
            ) {
                list.push(5)
            }
            if (fastingGlucose >= 6.1) {
                list.push(6)
            }
            // if (ldlCholesterin >= 3.4) {
            //     list.push(7)
            // }
            if (serumCholesterin >= 5.2) {
                list.push(7)
            }
            list =  Array.from(new Set(list))
            this.form.highItem = list
            if (list.length >= 3){
                this.form.screenResult = 2
            }else {
                this.form.screenResult = 1
            }
        },
        setPressureOne(val) {
            if (!val) return
            this.form.pressureOneSbp = val.systolicPressure
            this.form.pressureOneDbp = val.diastolicPressure
        },
        setPressureTwo(val) {
            if (!val) return
            this.form.pressureTwoSbp = val.systolicPressure
            this.form.pressureTwoDbp = val.diastolicPressure
        }
    },
    watch: {
        info: {
            handler(info) {
                this.form = defaultForm(info)
            },
            immediate: true
        },
        bmi: {
            handler() {
                this.form.bmi = this.bmi
            },
            immediate: true
        }
    }
}
</script>

<style lang="less" scoped>
table {
    text-align: left;
    >tr {
        >td {
            padding-bottom: 4px;
        }
        &:last-child {
            >td {
                padding-bottom: 0;
            }
        }
    }
    .divide {
        transform: translateY(2px);
        padding: 0 2px;
        .sub-text()
    }
}
.sub-text {
    color: #595959;
}
</style>
