<template>
  <div class="insurance-detection-appoint">
    <page-model
      v-if="picaWechat != 'wechat'"
      ref="PageModel"
      :header-info="headerInfo"
    />
    <div class="wrap">
      <!-- <div class="title-1">
        检测预约
      </div>
      <div class="title-2">
        及时接受检测结果检测报告
      </div> -->
      <div class="choose-section">
        <van-form
          ref="dectionForm"
          validate-first
        >
          <van-field
            name="checkboxGroup"
            label="检测项目"
            required
          >
            <template #input>
              <span style="font-weight:600">{{ dectionForm.detectName }}</span>
            </template>
          </van-field>
          <van-field
            label="受检人信息"
            required
            disabled

            class="appoint-form-title"
          />
          <van-field
            v-model="dectionForm.beneficiaryName"
            label="受检人"
            :disabled="isDisabled"
            clearable
            class="appoint-form-items"
            placeholder="请输入受检人姓名"
            :rules="[{ required: true, message: '请输入受检人姓名' },{
                       pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/,
                       message: '请输入正确格式',
                     },
                     {
                       pattern: /^.{2,20}$/,
                       message: '受检人姓名请填写2-20位',
                     },]"
          />
          <van-field
            v-model="dectionForm.beneficiaryPhone"
            class="appoint-form-items"
            :disabled="isDisabled"
            label="手机号"
            clearable
            placeholder="请输入受检人手机号"
            :rules="[{ required: true, message: '请输入受检人手机号' },
                     {
                       pattern: /^([1][3,4,5,6,7,8,9])\d{9}$/,
                       message: '手机号格式填写有误',
                     },]"
          />
          <van-field
            v-model="dectionForm.beneficiaryIdNum"
            :disabled="isDisabled"
            class="appoint-form-items"
            clearable
            label="身份证号"
            placeholder="请输入受检人真实身份证号"
            :rules="[{ required: true, message: '请输入受检人真实身份证号' },
                     {
                       pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                       message: '身份证号格式填写有误',
                     },]"
          />
          <van-field
            label="检测地点"
            required
            disabled
            class="appoint-form-title"
          />
          <van-field
            class="appoint-form-items"
            label="省市区"
            disabled
            right-icon="arrow"
            placeholder="请选择省市区"
            @click="showAreaFn"
          >
            <template #input>
              <div
                v-if="!showAreaLabel"
                class="appoint-form-placeholder"
              >
                请选择省市区
              </div>
              <div
                v-else
                class="appoint-form-value"
              >
                {{ showAreaLabel }}
              </div>
            </template>
          </van-field>

          <van-field
            v-model="dectionForm.hospitalName"
            class="appoint-form-items"
            label="检测地点"
            disabled
            right-icon="arrow"
            placeholder="请选择检测机构"
            :rules="[{ required: true, message: '请选择检测机构' }]"
            @click="showPopup('showselectHospital')"
          >
            <template #input>
              <div
                v-if="!dectionForm.hospitalName"
                class="appoint-form-placeholder"
              >
                请选择检测机构
              </div>
              <div
                v-else
                class="appoint-form-value"
              >
                {{ dectionForm.hospitalName }}
              </div>
            </template>
          </van-field>
          <van-field
            name="checkboxGroup"
            label="预约时间"
            required
            right-icon="arrow"

            @click="showPopup('showSelectTime')"
          >
            <template #input>
              <div
                v-if="!dectionForm.appointmentTime"
                class="appoint-form-placeholder"
              >
                请选择预约时间
              </div>
              <div
                v-else
                class="appoint-form-value"
              >
                {{ appointmentTimeShadow }}
              </div>
            </template>
          </van-field>
        </van-form>
      </div>
      <van-button
        round
        block
        type="info"
        :disabled="!canSubmit"
        class="appoint-form-submit "
        :class="canSubmit ? 'appoint-form-submit-active':''"
        @click="appointment"
      >
        提交
      </van-button>
      <div class="appoint-tel">
        客服电话：<a
          style="font-weight:600"
          href="tel:400-006-5252"
        >400-006-5252</a>
        <div class="serve-time">
          周一至周五8:00-18:00 <span /> 双休日9:00-18:00
        </div>
      </div>
    </div>
    <SelectHospital
      :external-data="externalData"
      :project-equity-no="projectEquityNo"
      :show="showselectHospital"
      :hospital-id="hospitalId"
      @change="selectHospital"
      @close="closePopup"
      @clean="cleanHospitalId"
    />
    <SelectTime
      :hospital-id="hospitalId"
      :project-equity-no="projectEquityNo"
      :show="showSelectTime"
      @change="selectTimes"
      @close="closePopup"
    />
    <PickArea
      :location-area-code="locationAreaCode"
      :project-equity-no="projectEquityNo"
      :show="showArea"
      @confirm="confirm"
      @close="closePopup"
    />
    <div
      id="container"
    />
  </div>
</template>

<script>
import {getDetectionName, getOrderInfo, appointment, getHospitalList} from '@/api/appoint';
import SelectHospital from '@/components/selectHospital/index.vue';
import SelectTime from '@/components/selectTime/index.vue';
import PickArea from '@/components/pickArea/index.vue';
import { getJumpPageStatus, getButtonStatus} from '@/api/question';
import storejs from 'storejs';
import dayjs from 'dayjs';
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  components: {
    SelectHospital,
    SelectTime,
    PickArea
  },
  data() {
    return {
      picaWechat:window._picaWechat,
      headerInfo: {
        title: '检测服务',
        isBlack: true,
        backMethod: 'web',
        style: 'backgroundColor:#ffffff;zIndex:100;',
        background: '',
      },
      dectionData:{},
      dectionForm: {
        detectName: '',
        beneficiaryIdNum:'',
        beneficiaryName: '',
        appointmentTime: '',
        currentDate: '',
        timeBucket: '',
        beneficiaryPhone: '',
        hospitalName:'',
        goodsId: '',
      },
      showAreaLabel:'',
      showselectHospital:false,
      showArea:false,
      reportShow: false,
      placeList: [],
      popType: '',
      timsArray: [],
      timeBucket: {
        am: '上午',
        pm: '下午',
      },
      provinceList: [],
      showProvinces: false,
      searchPlace: '',
      selectPicker: {
        value: [],
        label: '',
      },
      geolocation:null,
      isShowAddress: false,
      showSelectTime:false,
      isSelf: false,
      spEquityCode: '',
      position: {
        latitude: '',
        longitude:''
      },
      locationAreaCode: [],
      hospitalId: '',
      projectEquityNo: '',
      yunOrderNo: '',
      externalData: {
        latitude: '',
        longitude:'',
        provinceId: '',
        countyId: '',
        cityId: '',
      },
      isDisabled: false,
      stock: false,
      buttonStatus: false,
      buttonText: '',
      appointmentTimeShadow: '',
    };
  },
  computed: {
    canSubmit() {
      return (
        this.dectionForm.appointmentTime &&
        this.dectionForm.goodsId &&
        this.dectionForm.hospitalName &&
        this.hospitalId &&
        this.dectionForm.beneficiaryIdNum &&
        this.dectionForm.beneficiaryName &&
        this.dectionForm.beneficiaryPhone &&
        this.yunOrderNo &&
        this.stock &&
        this.buttonStatus
      );
    },
  },
  mounted() {
    this.$loading.show();
    const { yunOrderNo, projectEquityNo } = this.$route.query;
    this.yunOrderNo = yunOrderNo;
    this.projectEquityNo = projectEquityNo;
    console.log('yunOrderNo', yunOrderNo);
    const data = {
        yunOrderNo,
        projectEquityNo:'',
        externalOrderNo:'',
      };
    this.$sendBuriedData({
      action: 'ACTION_WEB_AFTER',
      component_tag: '7802852#0#0#预约',
      web_data:{yunOrderNo: yunOrderNo},
    });
    this.getDetectionName(yunOrderNo);
    this.getOrderInfo(yunOrderNo);
    this.getJumpPageStatus(data);
    this.getButtonStatus(yunOrderNo);
    this.initMap();
  },
  methods: {
    // 判断 库存
    getJumpPageStatus(data) {
      getJumpPageStatus(data).then(res => {
        if (res.code == '000000') {
          this.stock = res.data.stock;
          this.isDisabled = !this.stock;
          // 提示活动结束
          if (!this.stock) {
            this.$toast('活动已经结束');
          }
        }
        console.log('getJumpPageStatus', res);
      });
    },
    //  高德地图导航只有在线上环境才能使用
    initMap() {
      const that = this;
      AMapLoader.load({
        key:'009dd02e4fe0a1b5f895cd7b86b9e216', // 申请好的Web端开发者Key，首次调用 load 时必填
        plugins:[''], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: 'RB'
          });
          geolocation.getCurrentPosition((status, result) => {
            console.log('geolocationgeolocation,', status, result);
            if (result.position) {
              const position = { ...result.position, addr: result.formattedAddress };
              storejs.set('geolocation', position);
            } else {
              storejs.remove('geolocation');
            }
            that.initHospitalList();

          });

        });
      });
    },
    initHospitalList() {
      const result = storejs.get('geolocation');
      console.log('initHospitalList', result);
      // 没有位置信息，不请求机构信息
      if (result) {
        console.log('geolocation', result);
        this.position.latitude = result.lat || '';
        this.position.longitude = result.lng || '';
        const data = {
          projectEquityNo: this.projectEquityNo,
          latitude: this.position.latitude,
          longitude:this.position.longitude,
        };
        this.getHospitalList(data);
      }

    },
    //  根据坐标获取最近的机构id
    getHospitalList(data) {
      getHospitalList(data).then(res => {
        const { provinceId, countyId, cityId, hospitalName, hospitalId } = res.data.data[0];
        console.log('getHospitalListposition', res.data.data[0], provinceId, countyId, cityId, hospitalName, hospitalId);
        this.locationAreaCode = [provinceId, cityId, countyId];
        this.dectionForm.hospitalName = hospitalName;
        this.hospitalId = hospitalId;
        this.externalData = {
          latitude: this.position.latitude,
          longitude:this.position.longitude,
          provinceId, countyId, cityId
        };
      });
    },
    // 目前是配置一个检测信息，可能会拓展，所以返回的是一个list
    getDetectionName(yunOrderNo) {
      getDetectionName(yunOrderNo).then(res => {
        if (res.code === '000000' && res.data) {
          const dectionData = res.data[0] || {};
          console.log('getDetectionName', dectionData);
          this.dectionData = dectionData;
          this.dectionForm.detectName = dectionData.detectionName;
          this.dectionForm.goodsId = dectionData.goodsId;
          this.$store.dispatch('home/setInsuranceInfo', dectionData);

        }
      });
    },
    // 获取订单信息
    getOrderInfo(yunOrderNo) {
      getOrderInfo(yunOrderNo).then(res => {
        console.log('getOrderInfo', res);
        this.dectionForm.beneficiaryName = res.data.beneficiaryName;
        this.dectionForm.beneficiaryPhone = res.data.beneficiaryPhone;
        this.dectionForm.beneficiaryIdNum = res.data.beneficiaryIdNum;
        this.isDisabled = (this.dectionForm.beneficiaryName != '' && this.dectionForm.beneficiaryPhone != '' && this.dectionForm.beneficiaryIdNum != '') && (this.dectionForm.beneficiaryName && this.dectionForm.beneficiaryPhone && this.dectionForm.beneficiaryIdNum );
        this.$store.dispatch('home/setOrderInfo', res.data);

      });
    },
    selectTimes(times) {
      console.log(times);
      const {value, currentItemChoosed} = times;
      this.dectionForm.appointmentTime = value;
      this.closePopup('showSelectTime');
      // appointmentTimeShadow
       const m = (Number(dayjs(currentItemChoosed.appointmentDate).month()) + 1) + '月' + (Number(dayjs(currentItemChoosed.appointmentDate).date())) + '日';
      this.appointmentTimeShadow = m + ' ' + currentItemChoosed[currentItemChoosed.timeBucket + 'TimeContent'];
    },
    getTimes() {
      this.timsArray = [];
      const current = new Date().getTime();
      const ss = 24 * 60 * 60 * 1000;
      for (let i = 5; i < 35; i++) {
        var addTime = i * ss + current;
        var myDate = new Date(addTime);
        var year = myDate.getFullYear();
        var month = myDate.getMonth() + 1;
        var date = myDate.getDate();
        var timeStr =
          year + '-' + this.plusZero(month) + '-' + this.plusZero(date);
        this.timsArray.push(timeStr);
      }
    },
    plusZero(num) {
      return num > 9 ? num + '' : '0' + num;
    },
    showPopup(name) {
      console.log(name);
      if (this.stock) {
        this[name] = true;
      }

    },
    closePopup(name) {
      this[name] = false;
    },
    appointment() {
      this.$sendBuriedData({
        action: 'ACTION_WEB_CLICK',
        component_tag: '7802852#0#0#预约提交',
        web_data:{yunOrderNo: this.yunOrderNo},
      });
      this.$refs.dectionForm.validate().then(result => {
        console.log('this.dectionForm', result);
        const data = {
          appointmentTime: this.dectionForm.appointmentTime,
          goodsId: this.dectionForm.goodsId,
          hospitalId: this.hospitalId,
          hospitalName: this.dectionForm.hospitalName,
          patientIdNo: this.dectionForm.beneficiaryIdNum,
          patientMobile: this.dectionForm.beneficiaryPhone,
          patientName: this.dectionForm.beneficiaryName,
          yunOrderNo:this.yunOrderNo,
        };
        appointment(data).then(res => {
          if (res.code === '000000') {
            this.$router.push({
              path: '/appoint-details',
              query: {
                yunOrderNo: this.yunOrderNo,
                projectEquityNo:this.projectEquityNo
              }
            });
          } else {
            res.message && this.$toast(res.message);
          }
        });

      }).catch(err => {
        console.log(err);
      });
    },
    // 获取按钮状态
    getButtonStatus(yunOrderNo) {
      getButtonStatus(yunOrderNo).then(res => {
        console.log(res);
        this.$loading.hide();
        this.buttonStatus = res.data.buttonStatus;
        this.buttonText = res.data.statusDesc;
        !this.buttonStatus && this.$dialog.alert({
          message: this.buttonText,
          confirmButtonColor:'#00bda5'
        });
      });
    },
    confirm(values) {
      console.log('confirm', values);
      if (values) {
        console.log('confirm1', values);
        this.showAreaLabel = values.map(ele => ele.name).join('');
        this.externalData.provinceId = values[0].id;
        this.externalData.countyId = values[2].id;
        this.externalData.cityId = values[1].id;
        console.log('confirm1', this.externalData);
        this.showArea = false;
      }

    },
    selectHospital({hospitalId, hospitalName}) {
      this.hospitalId = hospitalId;
      this.dectionForm.hospitalName = hospitalName;
      this.showselectHospital = false;

    },
    showAreaFn() {
      if (this.stock) {
        this.showArea = true;
      }
    },
    cleanHospitalId() {
      console.log('cleanHospitalId');
      this.hospitalId = '';
      this.dectionForm.hospitalName = '';
    }
  },
};
</script>

<style lang="scss" scoped>
.insurance-detection-appoint {
  width: 100%;
  height: 100vh;
  overflow: auto;
  box-sizing: border-box;
  color: #ffffff;
  background: #F3FCFF;

  .bg-img {
    width: 100%;
    height: 281px;
    position: absolute;
    top: 0;
    z-index: -1;
  }
  .wrap {
    padding: 0 12px;
    overflow: auto;
  }
  .title-1 {
    font-size: 20px;
    margin-top: 23px;
    font-style: oblique;
    font-weight: 600;
  }
  .title-2 {
    margin-top: 2px;
    font-size: 12px;
  }
  .appoint-form-title{
    font-size: 14px;
    font-family:  PingFang SC;
    font-weight: 400;
    color: #212121;
    padding-top:22px ;
    padding-bottom: 0;

    line-height: 20px
  }

  .choose-section {
    padding: 10px 12px;
    background: #ffffff;
    border-radius: 11px;
    margin-top: 15px;
    /deep/ .van-field__label{
      color: #212121;
    }
    /deep/ .van-field__control:disabled{
      color: #323233;
      -webkit-text-fill-color: #323233;
    }
    .item {
      color: #212121;
      font-size: 14px;
      display: flex;
      height: 60px;
      align-items: center;
      position: relative;
      .input-key {
        font-weight: 300;
        margin-left: 10px;
      }
      .input-value {
        margin-left: 18px;
        font-weight: 500;
        overflow: visible;
      }
      .right {
        position: absolute;
        right: 10px;
        top: 25px;
      }
    }
    .height60 {
      height: 30px;
    }
    .required {
      position: relative;
    }
    .required::after {
      position: absolute;
      content: '*';
      display: block;
      left: -10px;
      top: 0;
      text-align: center;
      color: rgba(255, 56, 56, 1);
    }
  }
  .appoint-form-items{
    // font-weight: 600;

    /deep/ .van-field__label{
      color: #999999;
    }
    /deep/ .van-field__control{
      font-weight: 600;
    }
    /deep/ .van-field__control::placeholder{
      font-weight: 450;
    }
    .appoint-form-placeholder{
      font-weight: 450;
    }

  }
  .appoint-form-value{
      font-weight: 600;
    }
  .appoint-form-placeholder{
    color: #999999;
  }
  .appoint-form-title::after{
    display: none;
  }
  // .sub-btn {
  //   background: #00bda5;
  //   font-size:16px;
  //   color: #ffffff;
  //   font-weight: 600;
  //   width: 90%;
  //   height: 40px;
  //   line-height: 40px;
  //   border-radius: 40px;
  //   margin: 0 auto;
  //   position: absolute;
  //   top: 922rpx;
  //   left: 5%;
  //   text-align: center;
  // }
  .content {
    color: #02120f;
    height: 350px;
    overflow: hidden;
    .title-wrap {
      font-size: 18px;
      font-weight: 500;
      text-align: center;
      padding-top: 18px;
      position: fixed;
      width: 100%;
      left: 0;
      background: #ffffff;
      z-index: 1;
      margin: 0 auto;
      .search {
        display: flex;
        align-items: center;
        justify-content: space-evenly;
      }
      .search-input {
        width: 303px;
        height: 35px;
        background: #f5f6f8;
        border-radius: 13px;
        text-align: left;
        padding-left: 20px;
      }
      .title {
        font-size: 18px;
        font-weight: 500;
      }
    }
  }
  .pop-wrap {
    width: calc(100% - 32px);
    padding: 0 16px;
    .tab-list {
      position: relative;
      border-bottom: 0.5px solid #e7e8e9;
      height: 64px;
      .hospitalActive-icon {
        position: absolute;
        width: 17px;
        height: 17px;
        top: 14px;
        right: 0;
      }
      .list-1 {
        font-weight: 500;
        color: #212121;
        font-size: 15px;
        margin-top: 14px;
      }
      .list-2 {
        font-size: 12px;
        font-weight: 400;
        color: #999999;
        margin-top: 2px;
      }
    }
    .hospitalActive {
    }
  }
  .date-wrap {
    height: 100%;
    padding-top: 58px;
    display: flex;
    .left {
      min-height: 100vh;
      overflow: scroll;
      width: 130px;
      padding-bottom: 50px;
      background: #f5f6f8;
      .date-item {
        height: 38px;
        background: #f5f6f8;
        line-height: 38px;
        font-size: 16px;
        font-weight: 500;
        color: #02120f;
        text-align: center;
      }
      .date-item-active {
        color: #00bda5;
        background: #ffffff;
      }
    }
    .right {
      position: absolute;
      top: 58px;
      left: 130px;
      width: calc(100% - 130px);
      .right-item {
        padding-left: 22px;
        width: 100%;
        height: 41px;
        font-size: 16px;
        font-weight: 400;
        color: #666666;
        line-height: 41px;
      }
      .right-item-active {
        color: #00bda5;
      }
    }
    .date-item {
      height: 38px;
    }
  }
  .disabled {
    background: #d9d9d9 !important;
  }
  // /deep/ .van-field__control::placeholder{
  //   color: #999999;
  // }
  .appoint-form-submit{
    margin-top: 30px;
    height: 40px;
    font-weight: 600;
    background: #D9D9D9;
    border-radius: 20px;
    border: 1px solid #D9D9D9;
  }
  .appoint-form-submit-active{
    background: #00BDA5;
    border: 1px solid #00BDA5;
  }
  .appoint-tel{
    margin-top: 25px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
    line-height: 22px;
    text-align: center;
    .serve-time{
      display: flex;
      align-items: center;
      justify-content: center;
      height: 18px;
      font-size: 13px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 18px;
      span{
        width: 1px;
        height: 12px;
        margin: 0 12px;
        background: #BBBBBB;
      }
    }
  }
}
::v-deep {
  .address-wrap {
    height: 590px;
    #province {
      height: 500px;
    }
    #city {
      height: 500px;
    }
    #county {
      height: 500px;
    }
    #town {
      height: 500px;
    }
    .tip-header h3 {
      font-weight: 700;
      color: #212121;
    }
    .tip-header .submit-btn {
      color: #00bda5 !important;
    }
    .address-select .show-address-header .item.active:after {
      background-color: #00bda5;
    }
    .address-select .address-content ul li.active {
      color: #00bda5;
    }
  }
}
</style>
<style>
.mpvue-picker-div-show {
  color: #000000;
}
#container{
  display: none;
  padding:0px;
  margin: 0px;
  width: 100%;
  height: 800px;
}
</style>
