<template>
  <div class="replacereport">
    <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-model="name" name="姓名" label="姓名" left-icon="user-o" clearable required placeholder="输入姓名">
        </van-field>
        <van-field v-model="phone" name="手机号码" label="手机号码" left-icon="phone-o" clearable required placeholder="输入手机号码"
          :rules="[
            { pattern, required: true, message: '请填写正确的手机号码' },
          ]">
        </van-field>
        <van-field v-model="idCard" name="身份证号码" label="身份证号码" left-icon="paid" clearable required placeholder="输入身份证号码"
          :rules="[{ required: true, message: '请填写正确的身份证号码' }]">
        </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 class="button">
      <van-button type="info" size="normal" block @click="upload">代他人出行登记</van-button>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import axios from "axios";
import { encryptByDES, decryptByDES } from "@/utils/utils";
import { Field, Button, CellGroup, Form, Image, Toast, Popup, Cascader, Picker } from "vant";
// import { epidemicQuickMarkUpload } from "@/api/epidemic";

Vue.use(Field).use(Button).use(CellGroup).use(Form).use(Image).use(Toast).use(Popup).use(Cascader).use(Picker);
export default {
  data() {
    return {
      area: "",
      name: "",
      name1: "",
      phone: "",
      idCard: "",
      address: "",
      place: "",
      userInfo: {},
      permitCode: "",
      pattern:
        /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/,
      realInfo: "",
      healthType: '',
      isolatedState: '',
      riskArea: '',
      isPushType: '',
      push: {
        area: '',
        area1: '',
        areaName: '',
        cityName: '',
        villageName: '',
        streetName: '',
        communityName: '',
        concatAreaId: '',
        concatAreaName: '',
        reason: '',
        reasonId: '',
      },
      TreeProvince: [],
      streetList: [],
      communityList: [],
      reasonList: [{
        name: '省外来镇',
        id: 1
      }, {
        name: '省内来镇',
        id: 2
      },],
      cascaderShow: false,
      communityShow: false,
      reasonShow: false,
      fieldNames: {
        text: 'name',
        value: 'value',
        children: 'children',
      }
    };
  },
  methods: {
    // 获取个人信息
    getUserInfo(res) {
      sessionStorage.setItem("ZJCD-UserInfo", res);
      this.userInfo = JSON.parse(res);
    },
    // 提交上报
    upload() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "加载中...",
      });
      let params = {
        appId: "1234",
        areaName: this.area,
        idCard: this.idCard ? encryptByDES(this.idCard, "MnuYbhGv") : "",
        reverseGeoCoding: this.address,
        placeType: this.place,
        realUserName: this.userInfo?.realName ? this.userInfo.realName : (this.name1 ? this.name1 : ''),
        mobile: this.userInfo?.mobileNo ? this.userInfo.mobileNo : "",
        realUserId: this.userInfo?.userId,
        uploadMobile: this.phone,
        uploadName: this.name,
        permitCode: this.permitCode,
        uploadType: 1,
      };
      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) => {
              console.log(res)
              this.isolatedState = res.data.data ? res.data.data : ''
              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.uploadName
              //   }
              // }).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 : ''
              this.healthType = '1'
              // 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 {
              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.idCard ? encryptByDES(this.idCard, "MnuYbhGv") : "",
                          name: 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(() => {
              console.log(111)
              this.isolatedState = 0
              this.riskArea = ''
              this.upLoad()
            })
          }
        } else {
          this.$toast.clear();
          this.$dialog
            .confirm({
              message: "请填写完成个人信息",
              showCancelButton: false,
            })
            .then(() => {
              return;
            });
        }  
      }
      
    },
    goMap() {
      sessionStorage.setItem('fillInfo', JSON.stringify({ name: this.name, mobileNo: this.phone, 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 = {
        appId: "1234",
        areaName: this.area,
        idCard: this.idCard ? encryptByDES(this.idCard, "MnuYbhGv") : "",
        reverseGeoCoding: this.address,
        placeType: this.place,
        realUserName: this.userInfo?.realName ? this.userInfo.realName : (this.name1 ? this.name1 : ''),
        mobile: this.userInfo?.mobileNo ? this.userInfo.mobileNo : "",
        realUserId: this.userInfo?.userId,
        uploadMobile: this.phone,
        uploadName: this.name,
        permitCode: this.permitCode,
        uploadType: 1,
        healthType: this.healthType ? this.healthType : '1',
        isolatedState: this.isolatedState ? this.isolatedState : '0',
        riskArea: this.riskArea ? this.riskArea : '',
        userType: 0,
        // 推送字段
        boardinglocation: this.push.address,
        note: this.push.remarks,
        province: this.push.areaName,
        city: this.push.cityName,
        village: this.push.villageName,
        pushType: this.isPushType,
        reason: this.push.reasonId,
        regionId: this.push.concatAreaId,
        regionName: this.push.concatAreaName,
        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();
      }).catch((err) => {
          console.log(err)
          this.$toast.clear();
          this.$toast("提交失败，请稍后重试");
      });
    },
    // 上报成功
    jump() {
      this.$router.push({
        name: "ReportDetails",
        query: {
          name: this.name,
          address: this.address,
          phone: this.phone,
          idCard: this.idCard,
          place: this.place,
          healthType: this.healthType ? this.healthType : '1',
          isolatedState: this.isolatedState
        },
      });
    },
  },
  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.phone = 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)
    }
    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");
    }
    let res = sessionStorage.getItem("ZJCD-UserInfo");
    this.userInfo = JSON.parse(res);
    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.name1 = this.$route.query.name1;
    this.isPushType = this.$route.query.isPushType;
    this.initTreeProvince()
  },
};
</script>

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

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

.button {
  padding: 15px 40px;
  margin-bottom: 30px;
}
</style>