<template>
    <div class="submit">
        <div class="card-box1">
            <div class="top-box1">
                <div class="icon"></div>
                <div class="title">实名信息</div>
            </div>
            <div class="bottom-box1">
                <van-cell-group>
                    <van-field v-model="form.name" name="姓名" input-align="right" label="姓名" clearable required
                        placeholder="输入您的姓名">
                    </van-field>
                    <van-field v-model="form.mobile" name="手机号码" input-align="right" label="手机号码" clearable required
                        placeholder="输入您的手机号码">
                    </van-field>
                    <van-field v-model="idCard" name="身份证号" input-align="right" label="身份证号" clearable required
                        placeholder="输入您的身份证号">
                    </van-field>
                </van-cell-group>
            </div>
        </div>
        <div class="card-box1">
            <div class="top-box1">
                <div class="icon"></div>
                <div class="title">居住信息</div>
            </div>
            <div class="bottom-box1">

                <van-cell-group>
                    <van-field label="街道地址" v-model="form.addressArea" input-align="right" readonly @click="goMap"
                        required placeholder="请选择街道地址">
                        <template #right-icon>
                            <van-icon style="display: flex; align-items: center" color="#eb4e3f" name="location" />
                        </template>
                    </van-field>
                    <van-cell v-if="form.addressArea" input-align="right" title="所在社区" @click="show = true" is-link
                        required arrow-direction="down">
                        <template #default>
                            <span v-if="form.village">{{ form.village }}</span>
                            <span v-else class="cell-placeholder">请选择社区</span>
                        </template>
                    </van-cell>
                    <van-popup v-model="show" position="bottom" round>
                        <van-picker value-key="name" title="社区" show-toolbar :columns="areaList" @confirm="onConfirm"
                            @cancel="show = false" />
                    </van-popup>
                    <van-cell v-if="form.village" input-align="right" title="所属网格" @click="netShow = true" is-link
                        required arrow-direction="down">
                        <template #default>
                            <span v-if="form.networkType">{{ form.networkType }}</span>
                            <span v-else class="cell-placeholder">请选择网格</span>
                        </template>
                    </van-cell>
                    <van-popup v-model="netShow" position="bottom" round>
                        <van-picker value-key="networkType" title="网格" show-toolbar :columns="netWorkList"
                            @confirm="netConfirm" @cancel="netShow = false" />
                    </van-popup>
                    <van-field v-model="form.detailAddress" input-align="right" label="常住详细地址" type="textarea" required
                        placeholder="XX小区xx幢xx室" />
                </van-cell-group>
            </div>
        </div>
        <div class="card-box1">
            <div class="top-box1">
                <div class="icon"></div>
                <div class="title">人像采集</div>
            </div>
            <div class="bottom-box1">
                <van-field label="证件照" required>
                    <template #input>
                        <van-uploader :after-read="afterRead" v-model="fileList" :max-count="1" />
                    </template>
                </van-field>
            </div>
        </div>
        <van-button class="button" @click="submit()">提交</van-button>

    </div>
</template>

<script>
import axios from 'axios'
import { uploadFile, addUserPermitCode, updateUserPermitCode } from "@/api/reverse.js";
import { encryptByDES, decryptByDES } from "@/utils/utils";

import Vue from 'vue';
import { Button, Field, CellGroup, Icon, Cell, Popup, Picker, Uploader } from 'vant';
Vue.use(Button).use(Field).use(CellGroup).use(Icon).use(Cell).use(Popup).use(Picker).use(Uploader);
export default {
    data() {
        return {
            form: {
                addressArea: '',
                code: '',
                detailAddress: '',
                idCard: '',
                lat: '',
                lng: '',
                mobile: '',
                name: '',
                networkId: '', // 从网格来
                networkMobile: '',
                networkName: '',
                networkType: '',
                picture: '',
                uid: '',
                userType: 0,
                village: '',
            },
            idCard: '',
            show: false,
            netShow: false,
            // 行政区划列表
            areaList: [],
            // 网格列表
            netWorkList: [],
            fileList: [],
            userInfo: {},
            type: ''
        }
    },
    methods: {
        goMap() {
            this.form.fileList = this.fileList
            this.form.idCard = this.idCard
            this.$router.push({ name: "CurrentMap" });
            this.form.idCard = encryptByDES(JSON.parse(JSON.stringify(this.idCard)), "MnuYbhGv");
            sessionStorage.setItem('form', JSON.stringify(this.form))
        },
        onConfirm(value) {
            this.netWorkList = value.list
            this.form.village = value.name
            // 默认选中一个网格
            this.form.networkType = null
            this.form.networkId = null
            this.show = false
        },
        netConfirm(value) {
            this.form.networkId = value.id // 从网格来
            this.form.networkMobile = value.networkMobile
            this.form.networkName = value.name
            this.form.networkType = value.networkType
            this.netShow = false
        },
        afterRead(file) {
            console.log(file);
            file.status = "uploading";
            file.message = "上传中...";
            let param = new FormData();
            param.append("file", file.file);
            this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
                message: "上传图片中..."
            });
            uploadFile(param)
                .then(res => {
                    this.$toast.clear();
                    if (res.code == 200) {
                        file.status = "done";
                        file.message = "上传成功";
                        file.url = res.data;
                        console.log(this.fileList[0].url)
                    }
                })
                .catch(err => {
                    console.log(err);
                    file.status = "failed";
                    file.message = "上传失败";
                });
        },
        getList(latlng, type) {
            const a = this.$toast.loading({
                duration: 0,
                message: '加载中...',
                forbidClick: true
            })
            console.log(type)
            axios({
                url: '/appointment/queryUserArea',
                method: 'post',
                headers: {
                    'Content-Type': "application/json",
                },
                params: latlng,
                responseType: 'json'
            }).then((res) => {
                console.log(res)
                a.clear()
                if (res.data.code === 201) {
                    this.$toast('您当前未定位到镇江市范围内，请重新尝试！')
                } else {
                    if (res.data.code !== 200) {
                        this.$toast('定位获取失败，请手动选择！')
                        return false
                    }
                    console.log(res.data.data, this.form.village)
                    // 如果存在社区，选择跟社区名字一致的
                    if (type === 'edit') {
                        this.areaList = res.data.data.list
                        // 网格更改
                        this.netWorkList = res.data.data.list.find(
                            (el) => el.name == this.form.village
                        ).list
                    } else if (type === 'update') {
                        this.areaList = res.data.data.list
                        // 街道
                        this.form.addressArea = res.data.data.name
                        const obj = res.data.data.list.find(item => item.state === 0)
                        this.form.village = obj ? obj.name : res.data.data.list[0].name
                        this.netWorkList = obj ? obj.list : res.data.data.list[0].list
                        const obj1 = this.netWorkList.find(item => item.state === 0)
                        const obj2 = obj1 || this.netWorkList[0]
                        this.form.networkId = obj2.id // 从网格来
                        this.form.networkMobile = obj2.networkMobile
                        this.form.networkName = obj2.name
                        this.form.networkType = obj2.networkType
                    }
                    // 街道值
                    // this.form.addressArea = res.data.name
                }
            }).catch(() => {
                a.clear()
            })
        },
        submit() {
            console.log(this.$route.query.type)
            this.form.picture = this.fileList[0]?.url
            this.form.uid = this.userInfo.userId
            this.form.userType = this.type;
            console.log(this.form)
            if (!this.form.name) {
                return this.$toast('请填写姓名')
            }
            if (!this.idCard) {
                return this.$toast('请填写身份证号')
            }
            if (
                !/(^[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]$)/.test(
                    this.idCard
                )
            ) {
                return this.$toast('请输入正确的身份证')
            }
            if (!this.form.mobile) {
                return this.$toast('请填写手机号码')
            }
            if (!/^1[3456789]\d{9}$/.test(this.form.mobile)) {
                return this.$toast('请输入正确的手机号码')
            }
            if (!this.form.addressArea) {
                return this.$toast('请填写常住地址')
            }
            if (!this.form.village) {
                return this.$toast('请填写所在社区')
            }
            // if (!this.form.networkType) {
            //   return this.$toast("请填写所在网格");
            // }
            if (!this.form.detailAddress) {
                return this.$toast('请填写常住详细地址')
            }
            if (!this.form.picture) {
                return this.$toast('请上传证件照')
            }
            const a = this.$toast.loading({
                duration: 0,
                message: '加载中...',
                forbidClick: true
            })
            // this.form.idCard = JSON.parse(JSON.stringify(this.idCard))
            this.form.idCard = encryptByDES(JSON.parse(JSON.stringify(this.idCard)), "MnuYbhGv");
            // axios({
            //     url: 'https://appointment.smart-zj.cn/applet/applet/epidemic/queryHealthCodeColor',
            //     methods: 'get',
            //     headers: {
            //         "Content-Type": "application/json",
            //     },
            //     params: {
            //         idCard: this.form.idCard,
            //         name: this.form.name
            //     }
            // }).then((res) => {
            //     // alert(JSON.stringify(res))
            //     if (res.data.status == 550) {
            //         a.clear();
            //         this.$dialog.confirm({
            //             message: "请填写正确的身份信息",
            //             showCancelButton: false,
            //         })
            //     } else {
            //         if (res.data.data.code == 407) {
            //             a.clear();
            //             this.$dialog.confirm({
            //                 message: "请先更新苏康码再进行填报",
            //                 showCancelButton: false,
            //             })
            //         } else if (res.data.data.code == 404) {
            //             a.clear();
            //             this.$dialog.confirm({
            //                 message: res.data.data.maessage || "请先申领苏康码再进行填报",
            //                 showCancelButton: false,
            //             })
            //         } else {
                        if (JSON.parse(sessionStorage.getItem("code"))) {
                            this.form.code = JSON.parse(sessionStorage.getItem("code"))
                            updateUserPermitCode(this.form).then((res) => {
                                a.clear()
                                if (res.code == 200) {
                                    this.$toast.success(res.data)
                                    if (this.type == 0) {
                                        this.$router.replace({ name: 'ReverseGrDetail' })
                                    } else {
                                        this.$router.replace({ name: 'ReverseJrList' })
                                    }
                                }
                            }).catch((err) => {
                                a.clear()
                                this.$toast.file(err.message)
                            })
                        } else {
                            addUserPermitCode(this.form).then((res) => {
                                a.clear()
                                if (res.code == 200) {
                                    this.$toast.success(res.data)
                                    if (this.type == 0) {
                                        this.$router.replace({ name: 'ReverseGrDetail' })
                                    } else {
                                        this.$router.replace({ name: 'ReverseJrList' })
                                    }
                                }
                            }).catch((err) => {
                                a.clear()
                                this.$toast.file(err.message)
                            })
                        }
            //         }
            //     }
            // }).catch(err => {
            //     if (err.data.status == 500) {
            //         if (JSON.parse(sessionStorage.getItem("code"))) {
            //             this.form.code = JSON.parse(sessionStorage.getItem("code"))
            //             updateUserPermitCode(this.form).then((res) => {
            //                 a.clear()
            //                 if (res.code == 200) {
            //                     this.$toast.success(res.data)
            //                     if (this.type == 0) {
            //                         this.$router.replace({ name: 'ReverseGrDetail' })
            //                     } else {
            //                         this.$router.replace({ name: 'ReverseJrList' })
            //                     }
            //                 }
            //             }).catch((err) => {
            //                 a.clear()
            //                 this.$toast.file(err.message)
            //             })
            //         } else {
            //             addUserPermitCode(this.form).then((res) => {
            //                 a.clear()
            //                 if (res.code == 200) {
            //                     this.$toast.success(res.data)
            //                     if (this.type == 0) {
            //                         this.$router.replace({ name: 'ReverseGrDetail' })
            //                     } else {
            //                         this.$router.replace({ name: 'ReverseJrList' })
            //                     }
            //                 }
            //             }).catch((err) => {
            //                 a.clear()
            //                 this.$toast.file(err.message)
            //             })
            //         }
            //     } else {
            //         a.clear()
            //         this.$dialog.confirm({
            //             message: "服务异常，请稍后重试",
            //             showCancelButton: false,
            //         })
            //     }
            // })
        },
        // 初始化获取userInfo
        JSBgetUserInfo() {
            if (window.android !== undefined) {
                const res = window.android.getUserInfo(); // 这是一个json字符串
                sessionStorage.setItem("ZJCD-UserInfo", res);
                this.userInfo = JSON.parse(res);
            } 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);
            this.userInfo = JSON.parse(res);
        },
    },
    created() {
        this.type = JSON.parse(sessionStorage.getItem("type"))
        // alert(this.type)
        if (JSON.parse(sessionStorage.getItem("location"))) {
            // this.form.addressArea = JSON.parse(sessionStorage.getItem("location")).address;
            this.form.lat = JSON.parse(sessionStorage.getItem("location")).location.lat + '';
            this.form.lng = JSON.parse(sessionStorage.getItem("location")).location.lng + '';
            // alert(JSON.stringify(JSON.parse(sessionStorage.getItem("location")).location))
            this.getList(JSON.parse(sessionStorage.getItem("location")).location, 'update')
        }
        if (JSON.parse(sessionStorage.getItem("form"))) {
            console.log(JSON.parse(sessionStorage.getItem("form")))
            this.form.name = JSON.parse(sessionStorage.getItem("form")).name;
            this.form.mobile = JSON.parse(sessionStorage.getItem("form")).mobile;
            this.form.detailAddress = JSON.parse(sessionStorage.getItem("form")).detailAddress;
            // this.idCard = JSON.parse(sessionStorage.getItem("form")).idCard;
            this.idCard = decryptByDES(JSON.parse(sessionStorage.getItem("form")).idCard, "MnuYbhGv");
            if (JSON.parse(sessionStorage.getItem("form")).fileList) {
                this.fileList = JSON.parse(sessionStorage.getItem("form")).fileList;
            } else {
                this.fileList.push({ url: JSON.parse(sessionStorage.getItem("form")).picture })
            }
            console.log(this.idCard)
        }
        if (JSON.parse(sessionStorage.getItem("address"))) {
            this.form.lat = JSON.parse(sessionStorage.getItem("address")).lat
            this.form.lng = JSON.parse(sessionStorage.getItem("address")).lng
            // alert(JSON.stringify(JSON.parse(sessionStorage.getItem("address"))))
            this.getList(JSON.parse(sessionStorage.getItem("address")), 'update')
        }
        console.log(this.fileList)
        this.JSBgetUserInfo();
    },
    mounted() {
        window.getUserInfo = this.getUserInfo;
    },
}
</script>

<style lang="stylus" scoped>
.submit{
    display: flex;
    flex-direction: column;
    padding: 20px;
    box-sizing: border-box;
    align-items: center;
    overflow: scroll;
    .card-box1{
        width: 100%;
        background: #FFFFFF;
        box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.06);
        border-radius: 8px;
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        padding: 20px;
        box-sizing: border-box;
        .top-box1{
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            .icon{
                width: 4px;
                height: 24px;
                background: #EB4E3F;
                box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.06);
                border-radius: 2px;
            }
            .title{
                font-size: 28px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 600;
                color: #333333;
                text-shadow: 0px 2px 12px rgba(0, 0, 0, 0.06);
                margin-left: 15px;
            }
        }
        .bottom-box1{
            height 100%;
        }
    }
    .button{
        margin: 30px 0;
        width: 608px;
        height: 88px;
        background: linear-gradient(311deg, #EB4E3F 0%, #FF8138 100%);
        box-shadow: 0px 15px 18px -2px rgba(235, 78, 63, 0.2);
        border-radius: 49px;
        color: #fff;
    }
}
</style>