<template>
    <div>
        <div class="report">
            <BaiDuMap ref="baidu" v-show="false"> </BaiDuMap>
            <div class="banner">
                <img src="./img/banner.png" alt="" />
            </div>
            <van-form>
                <van-cell-group>
                    <div style="font-size: 14px;padding: 10px;font-weight:600;border-left:4px solid #EB4E3F">申报人信息</div>
                    <van-field v-if="realInfo" v-model="userInfo.realName" name="姓名" label="姓名" left-icon="user-o"
                        clearable readonly required placeholder="输入您的姓名">
                    </van-field>
                    <van-field v-if="realInfo" v-model="mobileNo" name="手机号码" label="手机号码" left-icon="phone-o" clearable
                        readonly required placeholder="输入您的手机号码">
                    </van-field>
                    <van-field v-if="realInfo" v-model="idCard" name="身份证号码" label="身份证号码" left-icon="paid" clearable
                        readonly required placeholder="输入您的身份证号码">
                    </van-field>
                    <van-field v-if="!realInfo" v-model="name" name="姓名" label="姓名" left-icon="user-o" clearable
                        required placeholder="输入您的姓名">
                    </van-field>
                    <van-field v-if="!realInfo" v-model="mobileNo" name="手机号码" label="手机号码" left-icon="phone-o"
                        clearable required placeholder="输入您的手机号码">
                    </van-field>
                    <van-field v-if="!realInfo" v-model="idCard" name="身份证号码" label="身份证号码" left-icon="paid" clearable
                        required placeholder="输入您的身份证号码">
                    </van-field>
                    <van-field v-model="place" name="场所类型" label="场所类型" left-icon="home-o" clearable readonly required
                        placeholder="输入您的场所类型">
                    </van-field>
                    <van-field v-model="area" name="所在地市辖区" label="所在地市辖区" left-icon="hotel-o" clearable readonly
                        required placeholder="请填写当前所在地市辖区" />
                    <van-field v-model="address" name="位置信息" label="位置信息" left-icon="location-o" clearable readonly
                        required placeholder="输入您的位置信息">
                    </van-field>
                    <div v-if="isPushType == 1"
                        style="font-size: 14px;padding: 10px;font-weight:600;border-left:4px solid #EB4E3F">抵镇目的地</div>
                    <van-field v-if="isPushType == 1" v-model="push.area" is-link readonly label="来源地"
                        placeholder="请选择来源地" required @click="cascaderShow = true" />
                    <van-popup v-model="cascaderShow" round position="bottom">
                        <van-cascader v-model="push.area" title="请选择来源地" :options="TreeProvince"
                            :field-names="fieldNames" @change="onChange" @close="cascaderShow = false"
                            @finish="onFinish" />
                    </van-popup>
                    <van-field v-if="isPushType == 1" v-model="push.streetName" is-link readonly label="目的地"
                        placeholder="请选择目的地" required @click="goMap" />
                    <van-field v-if="isPushType == 1 && push.streetName" v-model="push.communityName" is-link readonly
                        label="目的社区" placeholder="请选择目的社区" required @click="communityShow = true" />
                    <van-popup v-model="communityShow" position="bottom" round>
                        <van-picker show-toolbar :columns="
                            communityList.map((item) => {
                                return item.name;
                            })
                        " title="目的社区" @cancel="communityShow = false" @confirm="communityConfirm" />
                    </van-popup>
                    <van-field v-if="isPushType == 1" v-model="push.reason" is-link readonly label="申报原因"
                        placeholder="请选择申报原因" required @click="reasonShow = true" />
                    <van-popup v-model="reasonShow" position="bottom" round>
                        <van-picker show-toolbar :columns="
                            reasonList.map((item) => {
                                return item.name;
                            })
                        " title="申报原因" @cancel="reasonShow = false" @confirm="reasonConfirm" />
                    </van-popup>
                    <van-field v-if="isPushType == 1" v-model="push.remarks" name="备注信息" label="备注信息" clearable
                        placeholder="输入您的备注信息" />
                </van-cell-group>
            </van-form>
            <div style="color: #EB4E3F; margin-top: 5px; font-size: 14px; line-height: 1.5">
                *提交前请先仔细核对个人信息，信息不准确将会导致获取通行码有误！
            </div>
            <div class="button">
                <van-button type="info" size="normal" @click="upload" block>个人出行登记</van-button>
            </div>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import { encryptByDES, decryptByDES } from "@/utils/utils";
import Vue from "vue";
import { Field, Button, CellGroup, Form, Overlay, Popup, Cascader, Picker } from "vant";
import BaiDuMap from "@/components/baidumap/Main.vue";
import { addPermitStatistics, saveCacheUser, queryCacheUser } from "@/api/epidemic";
Vue.use(Field).use(Button).use(CellGroup).use(Form).use(Overlay).use(Popup).use(Cascader).use(Picker);
export default {
    components: {
        BaiDuMap,
    },
    data() {
        return {
            area: "",
            address: "",
            place: "",
            userInfo: {},
            permitCode: "",
            name: "",
            name1: "",
            mobileNo: "",
            idCard: "",
            realInfo: '',
            healthType: '',
            isolatedState: '',
            riskArea: '',
            isPushType: '',
            push: {
                area: '',
                area1: '',
                areaName: '',
                cityName: '',
                villageName: '',
                streetName: '',
                communityName: '',
                concatAreaId: '',
                concatAreaName: '',
                reason: '',
                reasonId: '',
                remarks: '',
                hsjc: '',
            },
            TreeProvince: [],
            streetList: [],
            communityList: [],
            reasonList: [{
                name: '省外来镇',
                id: 1
            }, {
                name: '省内来镇',
                id: 2
            },],
            cascaderShow: false,
            communityShow: false,
            reasonShow: false,
            fieldNames: {
                text: 'name',
                value: 'value',
                children: 'children',
            }
        };
    },
    methods: {
        tongji() {
            this.$router.push({
                name: 'ReportDetail',
                query: {
                    permitCode: this.permitCode
                }
            })
        },
        // 扫码次数
        init() {
            let params = {
                code: this.permitCode,
                userId: this.userInfo.userId,
            };
            addPermitStatistics(params).then((res) => {
                console.log(res);
            });
        },
        // 提交上报
        upload() {
            this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
                message: "加载中...",
            });
            let params = {}
            if (this.realInfo) {
                params.appId = "1234";
                params.areaName = this.area;
                params.idCard = this.userInfo.idCardNo;
                params.reverseGeoCoding = this.address;
                params.permitCode = this.permitCode;
                params.placeType = this.place;
                params.mobile = this.userInfo.mobileNo;
                params.realUserName = this.userInfo.realName;
                params.realUserId = this.userInfo.userId;
                params.uploadMobile = this.userInfo.mobileNo;
                params.uploadName = this.userInfo.realName;
                params.uploadType = 0;
            } else {
                params.appId = "1234";
                params.areaName = this.area;
                params.idCard = this.userInfo.idCardNo ? this.userInfo.idCardNo : this.idCard ? encryptByDES(this.idCard, "MnuYbhGv") : '';
                params.reverseGeoCoding = this.address;
                params.permitCode = this.permitCode;
                params.placeType = this.place;
                params.mobile = this.userInfo.mobileNo;
                params.realUserName = this.name;
                params.realUserId = this.userInfo.userId;
                params.uploadMobile = this.mobileNo;
                params.uploadName = this.name;
                params.uploadType = 0;
            }

            if (this.isPushType == 1 && (!this.push.area || !this.push.streetName || !this.push.communityName || !this.push.reason)) {
                this.$toast.clear();
                this.$dialog.confirm({
                    message: "请填写完整抵镇目的地",
                    showCancelButton: false,
                }).then(() => {
                    return;
                });
            } else {
                if (params.uploadName && params.uploadMobile && params.idCard) {
                    let regTest =
                        /^13[0-9]{1}[0-9]{8}$|15[^4]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0-8]{1}[0-9]{8}$|14[5-9]{1}[0-9]{8}$|16[6]{1}[0-9]{8}$|19[8-9]{1}[0-9]{8}$/;
                    if (!regTest.test(params.uploadMobile)) {
                        this.$toast.clear();
                        this.$dialog.confirm({
                            message: "手机号码格式不对",
                            showCancelButton: false,
                        })
                            .then(() => {
                                return;
                            });
                    }
                    let regTest1 = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
                    if (!regTest1.test(decryptByDES(params.idCard, "MnuYbhGv"))) {
                        this.$toast.clear();
                        this.$dialog.confirm({
                            message: "身份证格式不对",
                            showCancelButton: false,
                        })
                            .then(() => {
                                return;
                            });
                    } else {
                        axios({
                            url: 'https://appointment.smart-zj.cn/applet/applet/epidemic/queryUserOrigin',
                            methods: 'get',
                            header: {
                                "Content-Type": "application/json",
                            },
                            params: {
                                idCard: params.idCard
                            }
                        }).then((res) => {
                            this.isolatedState = res.data.data ? res.data.data : '0'
                            this.riskArea = res.data.message ? res.data.message : ''
                            // axios({
                            //     url: 'https://appointment.smart-zj.cn/applet/applet/epidemic/queryHealthCodeColor',
                            //     methods: 'get',
                            //     headers: {
                            //         "Content-Type": "application/json",
                            //     },
                            //     params: {
                            //         idCard: params.idCard,
                            //         name: params.realUserName
                            //     }
                            // }).then((res) => {
                            //     if (res.data.status == 550) {
                            //         this.$toast.clear();
                            //         this.$dialog.confirm({
                            //             message: "请填写正确的身份信息",
                            //             showCancelButton: false,
                            //         })
                            //     } else {
                            //         this.healthType = res.data.data.levelData ? res.data.data.levelData : ''
                            //         if (res.data.data.code == 407) {
                            //             this.$toast.clear();
                            //             this.$dialog.confirm({
                            //                 message: "请先更新苏康码再进行填报",
                            //                 showCancelButton: false,
                            //             })
                            //         } else if (res.data.data.code == 404) {
                            //             this.$toast.clear();
                            //             this.$dialog.confirm({
                            //                 message: "请先申领苏康码再进行填报",
                            //                 showCancelButton: false,
                            //             })
                            //         } else {
                            this.healthType = '1'
                            if (this.isPushType == 1) {
                                axios({
                                    url: 'https://appointment.smart-zj.cn/applet/applet/epidemic/queryExamineResult',
                                    methods: 'get',
                                    headers: {
                                        "Content-Type": "application/json",
                                    },
                                    params: {
                                        idCard: this.userInfo.idCardNo ? this.userInfo.idCardNo : this.idCard ? encryptByDES(this.idCard, "MnuYbhGv") : '',
                                        name: this.userInfo.realName ? this.userInfo.realName : this.name
                                    }
                                }).then((res) => {
                                    if (res.data.status == 100) {
                                        this.push.hsjc = res.data?.data?.isFortyEight ? 1 : 2
                                        this.upLoad()
                                    } else {
                                        this.$toast.clear();
                                        this.$dialog.confirm({
                                            message: "请填写正确的个人信息",
                                            showCancelButton: false,
                                        })    
                                    }
                                }).catch(() => {
                                    this.$toast.clear();
                                    this.$dialog.confirm({
                                        message: "请填写正确的个人信息",
                                        showCancelButton: false,
                                    })
                                })
                            } else {
                                this.upLoad()
                            }
                            //         }
                            //     }
                            // }).catch(err => {
                            //     if (err.data.status == 500) {
                            //         this.upLoad()
                            //     } else {
                            //         this.$toast.clear();
                            //         this.$dialog.confirm({
                            //             message: "服务异常，请稍后重试",
                            //             showCancelButton: false,
                            //         })
                            //     }
                            // })
                        }).catch(() => {
                            this.$toast.clear();
                            this.$dialog.confirm({
                                message: "请填写正确的个人信息",
                                showCancelButton: false,
                            })
                        })
                    }
                } else {
                    this.$toast.clear();
                    this.$dialog.confirm({
                        message: "请填写完整申报人信息",
                        showCancelButton: false,
                    }).then(() => {
                        return;
                    });
                }
            }

        },
        goMap() {
            sessionStorage.setItem('fillInfo', JSON.stringify({ name: this.name, mobileNo: this.mobileNo, idCard: this.idCard, push: this.push }))
            this.$router.push({ name: "CurrentMap" });
        },
        initTreeProvince() {
            axios({
                url: 'https://appointment.smart-zj.cn/applet/applet/epidemic/getTreeProvince',
                method: 'get',
                headers: {
                    'Content-Type': "application/json",
                },
            }).then((res) => {
                console.log('res---省市区', res)
                if (res.data.status == 100 && res.data.data.length > 0) {
                    this.TreeProvince = res.data.data
                }
            })
        },
        onChange({ selectedOptions }) {
            if (selectedOptions.length == 2) {
                if (selectedOptions[1].children.length == 0) {
                    this.cascaderShow = false;
                    this.push.area = selectedOptions.map((option) => option.name).join('');
                    this.push.areaName = selectedOptions[0].name
                    this.push.cityName = selectedOptions[1].name
                    this.push.villageName = ''
                }
            }
        },
        // 全部选项选择完毕后，会触发 finish 事件
        onFinish({ selectedOptions }) {
            console.log(selectedOptions)
            this.cascaderShow = false;
            this.push.area = selectedOptions.map((option) => option.name).join('');
            this.push.areaName = selectedOptions[0].name
            this.push.cityName = selectedOptions[1].name
            this.push.villageName = selectedOptions[2].name
        },
        getLocationInfo(lat, lng) {
            axios({
                url: `/appointment/queryUserArea`,
                method: 'post',
                headers: {
                    'Content-Type': "application/json",
                },
                params: {
                    lat, lng
                },
                responseType: 'json'
            }).then((res) => {
                console.log('res--', res)
                if (res.data.code === 201) {
                    this.$toast('您当前未定位到镇江市范围内，请重新尝试！')
                } else {
                    if (res.data.code !== 200) {
                        this.$toast('定位获取失败，请手动选择！')
                        return false
                    }
                    console.log(res.data.data)
                    this.push.streetName = res.data.data.name
                    this.push.communityName = ''
                    this.communityList = []
                    this.getListXzqh(res.data.data.name, lat, lng)
                }
            })
        },
        getListXzqh(areaName, lat, lng) {
            axios({
                url: 'https://appointment.smart-zj.cn/applet/applet/epidemic/getListXzqh',
                method: 'get',
                headers: {
                    'Content-Type': "application/json",
                },
                params: { areaName, lat, lng }
            }).then((res) => {
                this.communityList = res.data.data
                if (this.communityList.length > 0) {
                    this.communityList.map((item) => {
                        if (item.flag == true) {
                            this.push.communityName = item.name;
                            this.push.concatAreaId = item.id;
                            this.push.concatAreaName = item.concatAreaName;
                        }
                    })
                }
                sessionStorage.removeItem("location");
                sessionStorage.removeItem("fillInfo");
            })
        },
        communityConfirm(value, index) {
            this.push.communityName = value;
            this.push.concatAreaName = this.communityList[index].concatAreaName;
            this.push.concatAreaId = this.communityList[index].concatAreaId
            this.communityShow = false;
        },
        reasonConfirm(value, index) {
            console.log(value)
            this.push.reason = value
            this.push.reasonId = this.reasonList[index].id
            this.reasonShow = false;
        },
        upLoad() {
            let params = {}
            if (this.realInfo) {
                params.appId = "1234";
                params.areaName = this.area;
                params.idCard = this.userInfo.idCardNo;
                params.reverseGeoCoding = this.address;
                params.permitCode = this.permitCode;
                params.placeType = this.place;
                params.mobile = this.userInfo.mobileNo;
                params.realUserName = this.userInfo.realName;
                params.realUserId = this.userInfo.userId;
                params.uploadMobile = this.userInfo.mobileNo;
                params.uploadName = this.userInfo.realName;
                params.uploadType = 0;
                params.healthType = this.healthType ? this.healthType : '1';
                params.isolatedState = this.isolatedState ? this.isolatedState : '0'
                params.riskArea = this.riskArea ? this.riskArea : ''
                params.userType = 0;
                // 推送字段
                params.boardinglocation = this.push.address;
                params.note = this.push.remarks;
                params.province = this.push.areaName;
                params.city = this.push.cityName;
                params.village = this.push.villageName;
                params.pushType = this.isPushType;
                params.reason = this.push.reasonId;
                params.regionId = this.push.concatAreaId;
                params.regionName = this.push.concatAreaName;
                params.xdhszmState = this.push.hsjc;
            } else {
                params.appId = "1234";
                params.areaName = this.area;
                params.idCard = this.userInfo.idCardNo ? this.userInfo.idCardNo : this.idCard ? encryptByDES(this.idCard, "MnuYbhGv") : '';
                params.reverseGeoCoding = this.address;
                params.permitCode = this.permitCode;
                params.placeType = this.place;
                params.mobile = this.userInfo.mobileNo;
                params.realUserName = this.name;
                params.realUserId = this.userInfo.userId;
                params.uploadMobile = this.mobileNo;
                params.uploadName = this.name;
                params.uploadType = 0;
                params.healthType = this.healthType ? this.healthType : '1';
                params.isolatedState = this.isolatedState ? this.isolatedState : '0'
                params.riskArea = this.riskArea ? this.riskArea : ''
                params.userType = 0;
                // 推送字段
                params.boardinglocation = this.push.address;
                params.note = this.push.remarks;
                params.province = this.push.areaName;
                params.city = this.push.cityName;
                params.village = this.push.villageName;
                params.pushType = this.isPushType;
                params.reason = this.push.reasonId;
                params.regionId = this.push.concatAreaId;
                params.regionName = this.push.concatAreaName;
                params.xdhszmState = this.push.hsjc;
            }
            axios({
                url: 'https://appointment.smart-zj.cn/applet/applet/epidemic/uploadUserInfo',
                method: 'post',
                headers: {
                    'Content-Type': "application/json",
                },
                data: params
            }).then(() => {
                this.$toast.clear();
                this.$toast("提交成功");
                this.jump();
                saveCacheUser({
                    idCard: this.userInfo.idCardNo ? this.userInfo.idCardNo : this.idCard ? encryptByDES(this.idCard, "MnuYbhGv") : '',
                    mobile: this.userInfo.mobileNo,
                    name: this.userInfo.realName ? this.userInfo.realName : this.name,
                    uid: this.userInfo.userId
                }).then(() => {
                }).catch(() => {
                })
            }).catch((err) => {
                console.log(err)
                this.$toast.clear();
                this.$toast("提交失败，请稍后重试");
            });
        },
        // 上报成功
        jump() {
            this.$router.push({
                name: "ReportDetails",
                query: {
                    name: this.userInfo.realName ? this.userInfo.realName : this.name,
                    address: this.address,
                    place: this.place,
                    phone: this.userInfo.mobileNo ? this.userInfo.mobileNo : this.mobileNo,
                    idCard: this.userInfo.idCardNo ? decryptByDES(this.userInfo.idCardNo, "MnuYbhGv") : this.idCard,
                    code: 1,
                    healthType: this.healthType ? this.healthType : '1',
                    isolatedState: this.isolatedState
                },
            });
        },
        // 返回首页
        back() {
            if (window.android !== undefined) {
                window.android.backHome();
            } else {
                window.webkit && window.webkit.messageHandlers.backHome.postMessage("");
            }
        },
        // 初始化获取userInfo
        JSBgetUserInfo() {
            if (window.android !== undefined) {
                const res = window.android.getUserInfo(); // 这是一个json字符串
                sessionStorage.setItem("ZJCD-UserInfo", res);
                if (!JSON.parse(res).idCardNo) {
                    this.realInfo = false
                    this.userInfo = JSON.parse(res);
                    this.mobileNo = JSON.parse(res).mobileNo ? JSON.parse(res).mobileNo : '';

                    queryCacheUser({}).then((res) => {
                        if (res.data) {
                            this.name = res.data.name;
                            this.name1 = res.data.name;
                            this.idCard = decryptByDES(res.data.idCard, "MnuYbhGv");
                            this.mobileNo = res.data.mobile;
                        }
                    })
                } else {
                    this.realInfo = true;
                    this.userInfo = JSON.parse(res);
                    this.encryption();

                }
            } else if (window.webkit) {
                window.webkit &&
                    window.webkit.messageHandlers.getUserInfo.postMessage("getUserInfo");
            } else {
                window.receiveLocation(
                    JSON.stringify({ code: 0, data: { lat: 39.983744, lng: 116.276063 } })
                );
                this.$toast("请先登录镇合意app");
            }
        },
        getUserInfo(res) {
            sessionStorage.setItem("ZJCD-UserInfo", res);
            if (!JSON.parse(res).idCardNo) {
                this.realInfo = false
                this.userInfo = JSON.parse(res);
                this.mobileNo = JSON.parse(res).mobileNo ? JSON.parse(res).mobileNo : '';
                queryCacheUser({}).then((res) => {
                    if (res.data) {
                        this.name = res.data.name;
                        this.name1 = res.data.name;
                        this.idCard = decryptByDES(res.data.idCard, "MnuYbhGv");
                        this.mobileNo = res.data.mobile;
                    }
                })
            } else {
                this.realInfo = true;
                this.userInfo = JSON.parse(res);
                this.encryption();
            }
        },
        // 手机号加密 身份证号加密 脱敏处理
        encryption() {
            let phone = JSON.parse(JSON.stringify(this.userInfo.mobileNo));
            let reg = /(\d{3})\d{4}(\d{4})/;
            phone = phone.replace(reg, "$1****$2");
            this.mobileNo = phone;
            let card = decryptByDES(this.userInfo.idCardNo, "MnuYbhGv");
            this.idCard = card.replace(/^(.{3})(?:\d+)(.{4})/, '$1***********$2')
        },
    },
    mounted() {
        window.getUserInfo = this.getUserInfo;
    },
    created() {
        if (JSON.parse(sessionStorage.getItem("location"))) {
            this.location = JSON.parse(sessionStorage.getItem("location")).address;
            this.lat = JSON.parse(sessionStorage.getItem("location")).location.lat;
            this.lng = JSON.parse(sessionStorage.getItem("location")).location.lng;
            this.name = JSON.parse(sessionStorage.getItem("fillInfo")).name;
            this.mobileNo = JSON.parse(sessionStorage.getItem("fillInfo")).mobileNo;
            this.idCard = JSON.parse(sessionStorage.getItem("fillInfo")).idCard;
            this.push = JSON.parse(sessionStorage.getItem("fillInfo")).push;
            this.getLocationInfo(this.lat, this.lng)
        }
        this.area = this.$route.query.area;
        this.address = this.$route.query.address;
        this.place = this.$route.query.place;
        this.permitCode = this.$route.query.permitCode;
        this.isPushType = this.$route.query.isPushType;
        this.JSBgetUserInfo();
        this.init();
        this.initTreeProvince()
    },
};
</script>

<style lang="stylus" scoped>
.report{
    height: 100vh;
    overflow: auto;
}
.banner {
  width: 100%;
  height: 300px;
  padding: 0 0 20px 0;

  img {
    width: 100%;
    height: 100%;
  }
}

.button {
  display: flex;
  justify-content: space-around;
  padding: 15px 40px;
  margin-bottom: 30px;
}
.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 70%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    border-radius: 10px;
  }
</style>