<template>
    <nav-bar :navbar-data="navbarData"></nav-bar>
    <form id="form" @submit.stop="formSubmit">
        <view class="container"
            :style="{ marginTop: height +'px', minHeight: 'calc(100vh - '+ height + 'px)' }">
            <view class="skeleton-box" v-if="pageLoading">
                <van-skeleton title row="4" />
                <van-skeleton title avatar avatar-size="50px" row="4" />
                <van-skeleton title row="4" />
                <van-skeleton title avatar avatar-size="50px" row="4" />
            </view>
            <view v-else>
                <view class="questionnaire-header">
                    <view class="questionnaire-title">{{ questionnaireDetail.title }}</view>
                    <view class="questionnaire-desc">{{ questionnaireDetail.explain }}</view>
                </view>
                <view class="questionnaire-content">
                    <questionnaire-option :detailData="questionnaireDetail.detail" :listData="questionnaireDetail.detail"
                        :pIndex="[]" :show="true" @optionchange="childChange" />
                </view>
                <button class="btn" formType="submit">提交</button>
            </view>
        </view>
    </form>
</template>

<script>
import $http from "@/utils/https";
import Util from '@/utils/utils';
import httpConfig from '@/utils/httpConfig'
import navBar from '@/components/navBar/index'
import VanButton from '@/components/button/index'
import VanSkeleton from '@/components/skeleton/index'
import QuestionnaireOption from '../../components/questionnaire-option/index'
const app = getApp();
let questionnaireObj = [];
export default {
    components: {
        'nav-bar': navBar,
        'van-button': VanButton,
        'van-skeleton': VanSkeleton,
        'questionnaire-option': QuestionnaireOption
    },
    data() {
        return {
            pageLoading: true,
            height: app.globalData.height,
            windowHost: httpConfig && httpConfig.ipDeault,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: "调查问卷"
            },
            userData: null,
            questionnaireCode: '', //  'NewPneumoniaPR', // 'Test', // 'PaperTrip'
            hospCode: '',
            questionnaireDetail: null,
            questionnaireIndexs: [], // 
            showProvinceCity: false, // 是否显示省市区街道选择
            linkDynamicVal: [0, 0, 0, 0],
            linkDynamicData: [], // 联动数据集
            provinceData: ['请选择'], // 省
            cityData: ['请选择'], // 市
            countryData: ['请选择'], // 区
            areaData: [], // 街道
            questionnaireObj: {}
        }
    },
    onLoad(options) {
        this.userData = this.$cache.get('userData')
        if (options.hasOwnProperty('code')) {
            this.questionnaireCode = options.code
        } else {
            Util.showToast('问卷Code为空，请关闭页面，重新扫码', 'none', 3000)
            return
        }
        if (options.hasOwnProperty('hospCode')) {
            this.hospCode = options.hospCode
        }
        this.getFormInfo()
    },
    onShow: function () {
        const self = this
        let pages = getCurrentPages()
        let prevPage = pages[pages.length - 1]
        if (prevPage.__data__.hasOwnProperty('refreshStatus')) {
            const refreshStatus = prevPage.__data__.refreshStatus
            Util.showToast(refreshStatus ? '是' : '否')
            if (refreshStatus) {
                uni.showLoading({
                    title: '数据加载中...',
                })
                self.setData({
                    pageLoading: true,
                    questionnaireDetail: null
                }, function () {
                    self.getFormInfo()
                        .then(res => {
                            setTimeout(() => {
                                uni.hideLoading()
                                self.setData({
                                    pageLoading: false
                                })
                            }, 1500)
                        })
                        .catch(err => {
                            setTimeout(() => {
                                uni.hideLoading()
                                self.setData({
                                    pageLoading: false
                                })
                            }, 1500)
                        })
                })
            }
        }
    },
    methods: {
        // 提交表单
        formSubmit: async function (e) {
            const questionnaireDetailData = this.questionnaireDetail.detail
            questionnaireObj.splice(0, questionnaireObj.length)
            const bol = this.getChooseData(questionnaireDetailData)
            let dataObj = []
            if (bol) {
                questionnaireObj.map((item, index) => {
                    dataObj[index] = item
                })
                app.globalData.questionnaireResultData = dataObj
                app.globalData.questionnaireDetail = this.questionnaireDetail
                this.submitQuestionnaire(dataObj)
            }
        },
        // 递归获取填写数据并验证
        getChooseData: function (itemData) {
            const self = this
            for (let i = 0; i < itemData.length; i++) {
                let item = itemData[i]
                if (item.detailRequired == 'Y' && !item.resultValue) {
                    Util.showToast((['Radio', 'Checkbox', 'Select'].indexOf(item.detailTypeCode) > -1 ? '请选择' : '请输入') + item.detailDesc, 'none', 3000)
                    return false
                }
                if (item.detailPropertiesCode == 'mobile' && !/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(item.resultValue)) {
                    Util.showToast("联系电话格式不对",'none',3000)
                    return false
                } else if (item.detailPropertiesCode == "IDCard" && !/[1-9]\d{14}|[1-9]\d{17}|[1-9]\d{16}x/.test(item.resultValue)) { // 身份证号
                    Util.showToast("身份证号格式不对",'none',3000)
                    return false
                }
                if (item.hasOwnProperty('resultValue') && item.resultValue) {
                    questionnaireObj.push({
                        detailID: item.detailID,
                        detailValue: item.resultValue.constructor === Array ? item.resultValue : [item.resultValue]
                    })
                }
                if (item.hasOwnProperty('detailItem') && item.checked) {
                    let bol = self.getChooseData(item.detailItem.item)
                    if (!bol) {
                        return false
                    }
                }
            }
            return true
        },
        submitQuestionnaire(dataObj) {
            const self = this
            const {
                questionnaireDetail
            } = self
            const userData = this.$cache.get('userData')
            return new Promise((resolve, reject) => {
                let data = {
                    params: [{
                        "id": questionnaireDetail.id,
                        "code": questionnaireDetail.questionnaireCode,
                        "hospCode": questionnaireDetail.hospCode,
                        "patNo": "",
                        "ipAddress": userData.ipAddress,
                        "detail": [dataObj]
                    }]
                }
                uni.showLoading({
                    title: '数据提交中...',
                })
                $http.post("urlS", self, {
                    // namespace: "Y",
                    code: "03010007",
                    data: data,
                    success: function (res) {
                        setTimeout(function () {
                            if (uni.hideLoading(), +res.errorCode === 0) {
                                uni.showToast({
                                    title: res.errorMessage,
                                    duration: 2e3,
                                    success() {
                                        uni.navigateTo({
                                            url: '/pages/index/pages/questionnaire/result/result?status=success'
                                        })
                                    }
                                })
                            } else {
                                uni.navigateTo({
                                    url: '/pages/index/pages/questionnaire/result/result?status=fail'
                                })
                            }
                            resolve(true)
                        }, 2000)
                    },
                    fail(err) {
                        uni.hideLoading()
                        reject(err)
                    }
                })
            })
        },

        // 获取表单项信息
        getFormInfo() {
            const self = this
            return new Promise((resolve) => {
                const {
                    questionnaireCode
                } = this
                const userData = uni.getStorageInfoSync('userData')
                let data = {
                    "params": [{
                        code: questionnaireCode,
                        hospCode: userData && userData.hisHospID ? userData.hisHospID : ""
                    }]
                };
                uni.showLoading({
                    title: '数据加载中...',
                })
                $http.post("urlS", self, {
                    // namespace: "Y",
                    code: "03010006",
                    data: data,
                    success: function (res) {
                        if (uni.hideLoading(), +res.errorCode === 0 && res.result) {
                            let resultData = res.result
                            for (let i = 0; i < res.result.detail.length; i++) {
                                resultData.detail[i] = self.dealInitData(resultData.detail[i])
                            }
                            self.questionnaireDetail = resultData
                            setTimeout(function () {
                                self.pageLoading = false
                            }, 500)
                            resolve(res.result);
                        } else {
                            uni.hideLoading()
                            resolve(false)
                        }
                    },
                    fail(err) {
                        uni.hideLoading()
                        setTimeout(function () {
                            self.pageLoading = false
                        }, 500)
                        reject(err)
                    }
                })
            })
        },
        dealInitData(itemData) {
            const self = this
            // Select
            if (itemData.detailTypeCode == 'Select') {
                itemData['resultIndex'] = 0
                itemData['resultValue'] = itemData.detailItem.item[0].itemValue
            }
            if (itemData.hasOwnProperty('detailItem')) {
                itemData.detailItem.item.map(item => {
                    // Radio checkbox
                    if (item.hasOwnProperty('detailItem')) {
                        item.detailItem.item.map(data => {
                            if (data.hasOwnProperty('isGuanlian') && data.isGuanlian == 'Y') {
                                data['checked'] = false
                            }
                            return data
                        })
                        self.childInitData(item.detailItem.item)
                    }
                    return item
                })
            }
            return itemData
        },
        childInitData(childItemData) {
            const self = this
            return childItemData.map(item => {
                // Select
                if (item.detailTypeCode == 'Select') {
                    item['resultIndex'] = 0
                }
                // Radio checkbox
                if (item.hasOwnProperty('detailItem')) {
                    item.detailItem.item.map(data => {
                        if (data.hasOwnProperty('isGuanlian') && data.isGuanlian == 'Y') {
                            data['checked'] = false
                        }
                        return data
                    })
                    self.childInitData(item.detailItem.item)
                }
                return item
            })
        },
        childChange(e) {
            const {
                detailData
            } = e.detail
            const questionnaireDetail = this.questionnaireDetail
            questionnaireDetail.detail = detailData
            this.setData({
                questionnaireDetail
            })
        },
    }
}
</script>