<template>
    <div class="receiveApply">
        <!-- 头部 -->
        <van-nav-bar fixed title="叶酸领取申请">
            <template #left>
                <img src="../../assets/images/back.png" alt="" @click="goBack"/>
            </template>
        </van-nav-bar>
        <!-- 警告提示部分 -->
        <div class="warning">
            <img src="../../assets/images/warning.png" alt=""/>
            <span>请完整准确填写下列内容，所有内容只用于本次领取申请</span>
        </div>
        <!-- 表单部分 -->
        <div class="form_block">
            <div class="item_box">
                <p style="font-size: 15px"><span>*</span>申领单位：{{ applyUnitInfo.unitName }}</p>
            </div>
            <div class="title_info">
                <div class="line"></div>
                <div class="title">女方信息</div>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field v-model.trim="formData.womanName" label="姓名" placeholder="请输入女方姓名"/>
            </div>
            <div class="tags">
                <span>
                    <span class="sign">*</span>
                    <span>证件类型</span>
                </span>
                <div>
                    <van-tag plain @click="hanleTags1(1)"
                             :class="formData.womenCertificateType === 1 ? 'active' : ''">身份证
                    </van-tag>
                    <van-tag plain @click="hanleTags1(2)"
                             :class="formData.womenCertificateType === 2 ? 'active' : ''">护照
                    </van-tag>
                    <van-tag plain @click="hanleTags1(3)"
                             :class="formData.womenCertificateType === 3 ? 'active' : ''">无证件
                    </van-tag>
                </div>
            </div>
            <div class="item_box" v-if="formData.womenCertificateType!=3">
                <span>*</span>
                <van-field v-model.trim="formData.womenIdCard" label="证件号码" placeholder="请输入证件号码"
                           @change="womenIdCardChange"/>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field v-model="formData.birthDate" label="出生日期" placeholder="出生日期" disabled
                           @click="birthDateShow=true"/>
                <van-popup v-model="birthDateShow" position="bottom">
                    <van-datetime-picker
                            type="date"
                            v-model="formData.birthDateObj"
                            title="请选择出生日期"
                            @confirm="birthDateConfirm"
                            @cancel="birthDateShow = false"
                            :min-date="minDate"
                            :max-date="maxDate"
                    />
                </van-popup>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field type="number" v-model.trim="formData.height" @blur="onBlur(1,formData.height)" label="身高(cm)"
                           placeholder="请输入身高,范围100cm-200cm"/>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field type="number" v-model.trim.toFixed(2)="formData.weight" @blur="onBlur(2,formData.weight)"
                           label="体重(kg)" placeholder="请输入体重,1000以内数值"/>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field type="number" v-model.trim.toFixed(2)="formData.bmi" disabled
                           label="BMI"/>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field type="number" v-model="formData.provideNumber"
                           label="领取数量(瓶)" placeholder="请输入领取数量,1-999之间"/>
            </div>
            <div class="split"></div>
            <div class="title_info">
                <div class="line"></div>
                <div class="title">其他信息</div>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field type="number" v-model.trim="formData.telephone" label="联系电话" placeholder="请输入联系电话"/>
            </div>
            <div class="item_box">
                <span>*</span>
                <van-field
                        is-link
                        readonly
                        label="现住地址"
                        placeholder="点击选择"
                        @click="showPopup = true"
                />
            </div>
            <div class="item_box" style="font-size: 14px;margin-left: 20px" @click="showPopup = true">
                {{ formData.presentName }}
            </div>
            <van-popup v-model="showPopup" position="bottom" round>
                <!--                <van-area v-model="formData.presentCode" title="地区" :area-list="areaList" @confirm="handleConfirm"-->
                <!--                          @cancel="showPopup = false"/>-->
                <van-cascader
                        v-model="formData.presentCode"
                        title="请选择现住地址"
                        :options="optionsList"
                        @close="showPopup = false"
                        @change="areaChange"
                        @finish="areaFinish"
                />
            </van-popup>
            <div class="item_box">
                <span>*</span>
                <van-field v-model.trim="formData.nowAddress" label="详细地址" placeholder="请输入详细地址"/>
            </div>
            <div class="item_box border_none">
                <span>*</span>
                <van-field
                        is-link
                        readonly
                        label="签名知情同意书"
                        placeholder="去签名"
                        @click="handleRouter"
                        v-model="formData.isSignedName"
                />
            </div>
            <div class="split"></div>
            <div class="submit_btn_block">
                <van-button @click="handleSubmit">提交申请</van-button>
            </div>
        </div>
    </div>
</template>
<script>
import {isEmpty, validateCard, validatePhone, getDateStr} from '../../utils/common'
import {Dialog} from 'vant'
import {addReceiveApply, getChildAreaByParentCode} from '@/axios/api'

export default {
    data() {
        return {
            // 表单信息
            formData: {
                birthDate: undefined,
                womanName: "",
                womenCertificateType: 1,
                presentName: undefined,
                height: undefined,
                weight: undefined,
                bmi: undefined,
                question: '',
                telephone: '',
                recommendEat: "",
                birthDateObj: new Date(), presentCode: '', womenIdCard: '', nowAddress: '', provideNumber: undefined
            },
            optionsList: [],
            showPopup: false,
            scrollPosition: 0,
            applyUnitInfo: {unitName: ""},
            birthDateShow: false,
            minDate: new Date(1950, 0, 1),
            maxDate: new Date(),
            indexArr: [],
        }
    },
    created() {
        this.getChildArea(0, 0);
    },
    watch: {
        'formData.height': {
            deep: true,
            handler: function (newV, oldV) {
                this.heightWeightChange();
            }
        },
        'formData.weight': {
            deep: true,
            handler: function (newValue, oldValue) {
                this.heightWeightChange();
            }
        }
    },
    activated() {
        let applyUnitInfo = JSON.parse(sessionStorage.getItem('applyUnitInfo'));
        if (applyUnitInfo) {
            this.applyUnitInfo = applyUnitInfo;
        }
        if (!this.$route.meta.isBack) {
            sessionStorage.removeItem('esignImg');
            this.getUserInfo();
        } else {
            this.getIsEsign();
            window.scrollTo(0, this.scrollPosition);
        }
    },
    methods: {
        getChildArea(areaCode, areaLevel) {
            getChildAreaByParentCode(areaCode).then(res => {
                if (res.code === 'SUCCESS') {
                    let optionsList = [];
                    let areaList = res.data;
                    if (areaList != null) {
                        let index = 0;
                        let length = this.indexArr.length;
                        areaList.forEach(area => {
                            let item = {
                                text: area.areaName,
                                value: area.areaCode,
                                index: index,
                                areaLevel: area.areaLevel,
                                children: []
                            };
                            if (length == 4) {
                                delete item.children;
                            }
                            optionsList.push(item)
                            index++;
                        })
                        if (areaLevel == 0) {
                            this.optionsList = optionsList;
                        } else {
                            if (this.indexArr.length == 1) {
                                this.optionsList[this.indexArr[0]].children = optionsList;
                            }
                            if (this.indexArr.length == 2) {
                                this.optionsList[this.indexArr[0]].children[this.indexArr[1]].children = optionsList;
                            }
                            if (this.indexArr.length == 3) {
                                this.optionsList[this.indexArr[0]].children[this.indexArr[1]].children[this.indexArr[2]].children = optionsList;
                            }
                            if (this.indexArr.length == 4) {
                                this.optionsList[this.indexArr[0]].children[this.indexArr[1]].children[this.indexArr[2]].children[this.indexArr[3]].children = optionsList;
                            }
                        }
                    }
                }
            }).catch(res => {
            })
        },
        areaChange(val) {
            this.formData.presentName = val.selectedOptions.map((item) => item.text).join('/');
            let indexArr = [];
            val.selectedOptions.forEach(item => {
                indexArr.push(item.index);
            });
            if (indexArr.length == 5) {
                this.showPopup = false;
                return;
            }
            console.log(this.formData)
            this.indexArr = indexArr;
            this.getChildArea(val.value, val.areaLevel);
        }
        ,
        areaFinish(val) {
            this.formData.presentName = val.selectedOptions.map((item) => item.text).join('/');
        }
        ,
        //计算BMI值
        heightWeightChange() {
            let height = null, weight = null;
            if (this.formData.height) {
                height = Number(this.formData.height);
            }
            if (this.formData.weight) {
                weight = Number(this.formData.weight);
            }
            if (height != null && height != 0) {
                if (weight != null) {
                    this.formData.bmi = (weight / ((height / 100) * (height / 100))).toFixed(2);
                }
            }
        }
        ,
        onBlur(type, value) {
            if (value) {
                if (type == 1) {
                    this.formData.height = Number(value).toFixed(2);
                } else {
                    this.formData.weight = Number(value).toFixed(2);
                }
            }
        }
        ,
        womenIdCardChange() {
            if (!this.formData.womenIdCard) {
                return
            }
            let womenIdCard = this.formData.womenIdCard.trim();
            this.formData.womenIdCard = womenIdCard;
            if (this.formData.womenCertificateType == 1) {
                let length = womenIdCard.length;
                if (length == 15 | length == 18) {
                    let year = this.formData.womenIdCard.substring(6, 10);
                    let moth = this.formData.womenIdCard.substring(10, 12);
                    let day = this.formData.womenIdCard.substring(12, 14);
                    this.formData.birthDate = year + "-" + moth + "-" + day;
                    this.formData.birthDateObj = new Date(Number(year), Number(moth) - 1, Number(day));
                }
            }
        }
        ,
        birthDateConfirm(date) {
            this.birthDateShow = false;
            this.formData.birthDate = getDateStr(date);
        }
        ,
        // 返回
        goBack() {
            this.$router.push('provideUnit');
        }
        ,
        // 选择tags标签
        hanleTags1(val) {
            this.formData.womenCertificateType = val;
        },
        // 地区选择确定按钮
        handleConfirm(val) {
            this.showPopup = false;
            this.formData.presentName = val.map((item) => item.name).join('/');
            this.formData.presentCode = val[2].code;
        }
        ,
        // 签名知情同意书
        handleRouter() {
            this.$router.push('informedConsentForm');
        }
        ,
        // 提交申请
        handleSubmit() {
            if (isEmpty(this.formData.womanName)) {
                this.$toast.tips('请输入女方姓名');
                return false;
            }
            if (isEmpty(this.formData.womenCertificateType)) {
                this.$toast.tips('请选择女方证件类型');
                return false;
            } else {
                if (this.formData.womenCertificateType != 3) {
                    if (isEmpty(this.formData.womenIdCard)) {
                        this.$toast.tips('请输入女方证件号码');
                        return false;
                    } else {
                        if (validateCard(this.formData.womenCertificateType, this.formData.womenIdCard)) {
                            this.$toast.tips('请输入正确的证件号码');
                            return false;
                        }
                        if (this.formData.womenIdCard.length > 50) {
                            this.$toast.tips('证件号码不得超过50位');
                            return false;
                        }
                    }
                } else {
                    this.formData.womenIdCard = null;
                }
            }
            if (isEmpty(this.formData.height) || this.formData.height < 100 || this.formData.height > 200) {
                this.$toast.tips('请输入身高,范围100cm-200cm');
                return false;
            }
            if (isEmpty(this.formData.weight) || this.formData.weight < 0 || this.formData.weight > 1000) {
                this.$toast.tips('请输入体重，1000以内的数值');
                return false;
            }
            if (isEmpty(this.formData.provideNumber)) {
                this.$toast.tips('请输入领取数量');
                return false;
            }
            if (this.formData.provideNumber <= 0 || this.formData.provideNumber > 999) {
                this.$toast.tips('领取数量在1-999之间');
                return false;
            }
            if (isEmpty(this.formData.birthDate)) {
                this.$toast.tips('请输入出生日期');
                return false;
            }
            if (isEmpty(this.formData.telephone)) {
                this.$toast.tips('请输入联系电话');
                return false;
            }
            if (validatePhone(this.formData.telephone)) {
                this.$toast.tips('请输入正确的电话号码');
                return false;
            }
            if (isEmpty(this.formData.presentCode)) {
                this.$toast.tips('请选择现住地址');
                return false;
            }
            if (isEmpty(this.formData.nowAddress)) {
                this.$toast.tips('请输入详细地址');
                return false;
            }
            if (isEmpty(this.formData.isSignedName)) {
                this.$toast.tips('请先签订知情同意书');
                return false;
            }
            if (this.formData.womanName.length > 15) {
                this.$toast.tips('姓名不得超过15个字');
                return false;
            }
            if (this.formData.nowAddress.length > 100) {
                this.$toast.tips('详细地址不得超过100个字');
                return false;
            }
            Dialog.confirm({
                title: '提示',
                message: '确定要提交该申请么？',
            }).then(() => {
                let createUnitId = JSON.parse(sessionStorage.getItem('applyUnitInfo')).unitId;
                let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
                let applySignId = sessionStorage.getItem('esignImgId');
                let params = {
                    nowAddress: this.formData.nowAddress,
                    telephone: this.formData.telephone,
                    womenIdCard: this.formData.womenIdCard,
                    womanName: this.formData.womanName,
                    residentId: userInfo.userId,
                    residentMobile: userInfo.account,
                    createUnitId: createUnitId,
                    birthDate: this.formData.birthDate,
                    height: this.formData.height,
                    weight: this.formData.weight,
                    womenCertificateType: this.formData.womenCertificateType,
                    presentCode: this.formData.presentCode,
                    applySignId: applySignId,
                    question: this.formData.question,
                    recommendEat: this.formData.recommendEat,
                    provideNumber: this.formData.provideNumber,
                    bmi: 0,
                };
                let height = null, weight = null;
                if (this.formData.height) {
                    height = Number(this.formData.height);
                }
                if (this.formData.weight) {
                    weight = Number(this.formData.weight);
                }
                if (weight != 0) {
                    params.bmi = (weight / ((height / 100) * (height / 100))).toFixed(2);
                }
                if (!params.question && this.formData.bmi < 28) {
                    params.recommendEat = "1颗/天(0.4mg/天)";
                }
                this.$toast.submit();
                addReceiveApply(params).then(res => {
                    if (res.code === 'SUCCESS') {
                        this.$toast.success('操作成功');
                        this.$router.push('receiveDetail');
                    }
                }).catch(() => {
                    this.$toast.close();
                });
            }).catch(() => {
                return false;
            });
        }
        ,
        getIsEsign() {
            let imgUrl = window.sessionStorage.getItem('esignImg');
            if (isEmpty(imgUrl)) {
                this.formData.isSignedName = '';
            } else {
                this.formData.isSignedName = '已签名';
                this.formData.isSigned = 1;
                this.$forceUpdate();
            }
        }
        ,
        getUserInfo() {
            let lastRecord = JSON.parse(sessionStorage.getItem("lastRecord"));
            if (!lastRecord) {
                return;
            }
            let {
                question, recommendEat, presentCode, womenCertificateType, womanName, womenIdCard,
                birthDate, height, weight, bmi, telephone, nowAddress, provideNumber, presentCodeName
            } = lastRecord;
            if (!womenCertificateType) {
                return;
            }
            this.formData.question = question;
            this.formData.recommendEat = recommendEat;
            this.formData.womanName = womanName;
            this.formData.womenCertificateType = womenCertificateType;
            this.formData.womenIdCard = womenIdCard;
            this.formData.birthDate = birthDate;
            this.formData.height = height;
            this.formData.weight = weight;
            this.formData.bmi = bmi;
            this.formData.telephone = telephone;
            this.formData.nowAddress = nowAddress;
            this.formData.provideNumber = provideNumber;
            this.formData.presentName = presentCodeName;
            this.formData.presentCode = presentCode;
            if (!presentCodeName) {
                this.formData.presentCode = null;
            }
            if (this.formData.birthDate) {
                let dateArr = this.formData.birthDate.split("-");
                this.formData.birthDateObj = new Date(Number(dateArr[0]), Number(dateArr[1]) - 1, Number(dateArr[2]));
            }
        }
        ,
    },
    beforeRouteEnter(to, from, next) {
        if (from.name === 'informedConsentForm') {
            to.meta.isBack = true;
        } else {
            to.meta.isBack = false;
        }
        next();
    }
    ,
    beforeRouteLeave(to, from, next) {
        this.scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
        next();
    }
    ,
}
</script>
<style lang="less" scoped>
.receiveApply {
  padding-top: 44px;

  .warning {
    height: 32px;
    background-color: #FFF9D6;
    color: #EC6808;
    font-size: 12px;
    display: flex;
    align-items: center;

    img {
      margin: 0 8px 0 16px;
    }
  }

  .tags {
    height: 54px;
    display: flex;
    justify-content: space-between;
    margin: 0 16px;
    padding: 16px 0;
    border-bottom: 1px solid #D9D9D9;
    box-sizing: border-box;
    font-size: 14px;
    color: #262626;

    .sign {
      color: red;
      margin-right: 2px;
    }
  }
}

.item_box {
  height: 54px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #D9D9D9;
  margin: 0 16px;

  span {
    height: 16px;
    color: red;
    margin-right: 2px;
  }
}
</style>