<template>
  <div class="add">
    <div class="tips">请确保以下信息全部由本人填写，本人对所填写内容的真实性和完整性负责</div>

    <div class="title">基本信息</div>
    <div class="form-item__group">
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>身份证号</h2>
          </div>
          <div class="form-item__right">
            <input placeholder="请输入" type="idcard" v-model="form.idNumber" :maxlength="18" @blur="idNumberChange" />
          </div>
        </div>
      </div>
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>姓名</h2>
          </div>
          <div class="form-item__right">
            <input placeholder="请输入" v-model="form.name" :maxlength="20"/>
          </div>
        </div>
      </div>
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>手机号码</h2>
          </div>
          <div class="form-item__right">
            <input placeholder="请输入" type="number" v-model="form.phone" :maxlength="11"/>
          </div>
        </div>
      </div>
    </div>

    <div class="title">行程信息</div>
    <div class="form-item__group">
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>出发时间</h2>
          </div>
          <div class="form-item__right">
            <div class="ai-area" @click="isShowStartTime = true">
              <div class="ai-area__wrapper">
                <span class="label" v-if="form.startTime">{{ form.startTime }}</span>
                <i v-else>请选择</i>
                <u-icon name="arrow-right" color="#ddd"/>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>出发地</h2>
          </div>
          <div class="form-item__right">
            <AiAreaPicker class="ai-area" v-model="startAreaId" :fullName.sync="startAreaName" all>
              <div class="ai-area__wrapper">
                <span class="label" v-if="startAreaName">{{ startAreaName }}</span>
                <i v-else>请选择</i>
                <u-icon name="arrow-right" color="#ddd"/>
              </div>
            </AiAreaPicker>
          </div>
        </div>
      </div>
      <div class="form-item form-item__textarea">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i style="margin-right: 8px;"></i>
            <h2>出发地详址</h2>
          </div>
          <div class="form-item__right">
            <textarea auto-height v-model="form.startAddress" :maxlength="500" placeholder="请尽量详细填写至街道、小区"
                      placeholder-style="font-size: 16px"></textarea>
          </div>
        </div>
      </div>
      <div class="form-item form-item__imgs">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>出行方式</h2>
          </div>
          <div class="form-item__right">
            <div class="travelType">
              <div class="travelItem" v-for="(v,index) in travelTypeDict" :key="index" :class="[travelType.includes(v.dictValue)? 'active':'']" @click="travelTypeSelect(v.dictValue)">{{ v.dictName }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i style="margin-right: 8px;"></i>
            <h2>车次/航班</h2>
          </div>
          <div class="form-item__right">
            <input placeholder="请输入" v-model="form.trainNo" :maxlength="20"/>
          </div>
        </div>
      </div>
      <div class="form-item form-item__textarea">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i style="margin-right: 8px;"></i>
            <h2>行程描述</h2>
          </div>
          <div class="form-item__right">
            <textarea auto-height style="height: 90px" v-model="form.description" :maxlength="500" placeholder="请输入行程描述"
                      placeholder-style="font-size: 16px"></textarea>
          </div>
        </div>
      </div>    
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>预计抵平时间</h2>
          </div>
          <div class="form-item__right">
            <div class="ai-area" @click="isShowEndTime = true">
              <div class="ai-area__wrapper">
                <span class="label" v-if="form.arriveTime">{{ form.arriveTime }}</span>
                <i v-else>请选择</i>
                <u-icon name="arrow-right" color="#ddd"/>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>抵平卡口</h2>
          </div>
          <div class="form-item__right">
            <AiSelect :list="getewayData" v-model="form.gatewayId" class="select"></AiSelect>
          </div>
        </div>
      </div>
      <div class="form-item">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>目的地</h2>
          </div>
          <div class="form-item__right">
            <AiAreaPicker class="ai-area" v-model="form.arriveAreaId" :fullName.sync="form.arriveAreaName" :areaId="$areaId">
              <div class="ai-area__wrapper">
                <span class="label" v-if="form.arriveAreaName">{{ form.arriveAreaName }}</span>
                <i v-else>请选择</i>
                <u-icon name="arrow-right" color="#ddd"/>
              </div>
            </AiAreaPicker>
          </div>
        </div>
      </div>
      <div class="form-item form-item__textarea">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i style="margin-right: 8px;"></i>
            <h2>目的地详址</h2>
          </div>
          <div class="form-item__right">
            <textarea auto-height v-model="form.arriveAddress" :maxlength="500" placeholder="请尽量详细填写至小区、楼栋号"
                      placeholder-style="font-size: 16px"></textarea>
          </div>
        </div>
      </div>
    </div>

    <div class="title">健康状况</div>
    <div class="form-item__group">
      <div class="form-item form-item__imgs">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>是否有风险旅居史？</h2>
          </div>
          <div class="form-item__right">
            <AiRadio style="width: 100%;" v-model="form.fromHighRiskArea" dict="yesOrNo"></AiRadio>
          </div>
        </div>
      </div>
      <div class="form-item" v-if="form.fromHighRiskArea == 1">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>风险地区</h2>
          </div>
          <div class="form-item__right">
            <AiAreaPicker class="ai-area" v-model="form.highRiskAreaId" :fullName.sync="form.highRiskAreaName" all>
              <div class="ai-area__wrapper">
                <span class="label" v-if="form.highRiskAreaId">{{ form.highRiskAreaName }}</span>
                <i v-else>请选择</i>
                <u-icon name="arrow-right" color="#ddd"/>
              </div>
            </AiAreaPicker>
          </div>
        </div>
      </div>
      <div class="form-item form-item__imgs">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>近七日内是否接触新冠确诊或疑似患者？</h2>
          </div>
          <div class="form-item__right">
            <AiRadio style="width: 100%;" v-model="form.contactPatients" dict="epidemicTouchInFourteen"></AiRadio>
          </div>
        </div>
      </div>
      <div class="form-item form-item__imgs">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>是否有健康异常情况？</h2>
          </div>
          <div class="form-item__right">
            <AiRadio style="width: 100%;" v-model="form.abnormalHealth" dict="yesOrNo"></AiRadio>
          </div>
        </div>
      </div>
      <div class="form-item" v-if="form.abnormalHealth==1">
        <div class="form-item__wrapper">
          <div class="form-item__title">
            <i>*</i>
            <h2>异常情况</h2>
          </div>
          <div class="form-item__right">
            <AiSelect dict="EP_abnormalType" v-model="form.abnormalType" class="select"></AiSelect>
          </div>
        </div>
      </div>
    </div>

    <u-picker mode="time" :params="params" v-model="isShowStartTime" @confirm="onStartChange"></u-picker>
    <u-picker mode="time" :params="params" v-model="isShowEndTime" @confirm="onEndChange"></u-picker>

    <div class="btn-wrapper">
      <div class="btn" hover-class="text-hover" @click="submit">提交</div>
    </div>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import dayjs from 'dayjs'

export default {
  appName: "添加返乡记录",
  data() {
    return {
      isShowType: false,
      isShowEndTime: false,
      isShowStartTime: false,
      isShowDate: false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true
      },
      dataParams: {
        year: true,
        month: true,
        day: true
      },
      form: {
        riskLevel: '',  // 风险等级
        infoType: '1',
        idNumber: '',
        name: '',
        phone: '',
        startTime: '',
        startAreaId: '',
        startAreaName: '',
        startAddress: '',
        travelType: '',  // 出行方式
        trainNo: '',
        description: '',
        arriveTime: '',
        arriveAreaId: '',  // 预计到达卡口id
        gatewayId: '',   // 卡口id
        gatewayName: '',
        arriveAreaId: '',
        arriveAreaName: '',
        arriveAddress: '',
        fromHighRiskArea: '0',
        highRiskAreaId: '',
        highRiskAreaName: '',
        contactPatients: '0',
        abnormalHealth: '0',
        abnormalType: '',
        companionList: [],
      },
      flag: false,
      $areaId: '',
      travelTypeDict: [],
      travelType: [],
      getewayData: [],
      startAreaId: '',
      startAreaName: '',
    }
  },

  computed: {
    ...mapState(['user'])
  },

  watch: {
    startAreaId: {
      handler(v) {
        if(v?.length) {
          this.getRiskLevel(v)
        }
      }
    },
  },

  onLoad(o) {
    if(o.id) {
      this.getDetail(o.id)
      uni.setNavigationBarTitle({
        title: '编辑返乡记录'
      })
    }
    this.$dict.load('EP_travelType','EP_registerPersonType','EP_abnormalType','EP_highRiskIndustries','yesOrNo','epidemicTouchInFourteen').then(()=> {
      this.$areaId = this.user.$areaId
      this.travelTypeDict = this.$dict.getDict('EP_travelType')
      this.getewayList()
    })
    let timeNow = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
    this.form.arriveTime = timeNow.substr(0,timeNow.length - 3)
  },

  methods: {
    onStartChange(e) {
      this.form.startTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}`
    },

    onEndChange(e) {
      this.form.arriveTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}`
    },

    getDetail(id) {
      this.$instance.post(`/app/appepidemicpreventionregisterinfo/queryDetailById?id=${id}`).then(res=> {
        if(res?.data) {
          this.form = res.data
          this.travelType = res.data.travelType?.split(',')
          this.form.startTime = res.data.startTime.substr(0, res.data.startTime.length - 3)
          this.form.arriveTime = res.data.arriveTime.substr(0, res.data.arriveTime.length - 3)
          this.startAreaId = res.data.startAreaId
          this.startAreaName = res.data.startAreaName
        }
      })
    },

    travelTypeSelect(value) {
      const index = this.travelType.indexOf(value)
      if (index === -1) {
        this.travelType.push(value)
      } else {
        this.travelType.splice(index, 1)
      }
    },

    // 获取风险等级
    getRiskLevel(areaId) {
      this.$instance.post(`/app/appepidemicpreventionriskarea/queryAreaRiskLevel?areaId=${areaId}`).then(res=> {
        if(res?.data) {
          this.form.riskLevel = res.data
        }
      })
    },

    idNumberChange(e) {
      if(e.detail.value.length) {
        this.getOwnerInfo(e.detail.value) 
      }
    },

    // 获取个人信息
    getOwnerInfo(idNumber) {
      this.$instance.post(`/app/appepidemicpreventionregisterinfo/list`, null, {
        params: {
          idNumber: idNumber,
          current: this.current,
          size: 10,
          infoType: '1',
        }
      }).then(res => {
        if(res?.data) {
          this.form.name = res.data.records?.[0]?.name || ''
          this.form.phone = res.data.records?.[0]?.phone || ''
          this.startAreaId = res.data.records?.[0]?.startAreaId
          this.startAreaName = res.data.records?.[0]?.startAreaName
          this.form.arriveAreaId = res.data.records?.[0]?.arriveAreaId
          this.form.arriveAreaName = res.data.records?.[0]?.arriveAreaName
          this.form.startAddress = res.data.records?.[0]?.startAddress || ''
          this.form.arriveAddress = res.data.records?.[0]?.arriveAddress || ''
          this.form.description = res.data.records?.[0]?.description || ''
        }
      })
    },

    // 获取卡口列表
    getewayList() {
      this.$instance.post(`/app/appepidemicpreventiongateway/list`, null, {
        current: this.current,
        size: 300,
      }).then(res => {
        if(res?.data) {
          this.getewayData = res.data.records.map(item=> {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      })
    },

    submit() {
      if(!this.form.idNumber) {
        return this.$toast('请输入身份证号')
      }

      if(this.form.idNumber.length) {
        let reg =  /^[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(!reg.test(this.form.idNumber)) {
          return this.$toast('请输入正确的身份证账号')
        }
      }
      
      if (!this.form.name) {
        return this.$toast('请输入姓名')
      }

      if (!this.form.phone) {
        return this.$toast('请输入手机号码')
      }

      if (!this.$reg.phone(this.form.phone) || this.form.phone.length != 11) {
        return this.$toast('请输入正确的手机号')
      }

      if (!this.form.startTime) {
        return this.$toast('请选择出发时间')
      }

      if (new Date(this.form.startTime.replace(/-/g, '/')).getTime() > new Date().getTime()) {
        return this.$toast('出发时间不得晚于当前时间')
      }

      if (!this.startAreaId) {
        return this.$toast('请选择出发地')
      }

      if (this.startAreaId.substr(4,this.startAreaId.length - 4) === '00000000') {
        return this.$toast('出发地必须选至县级及以下')
      }

      if (this.startAreaId == '511923000000') {
        return this.$toast('出发地选择错误，请重新选择！')
      }

      if (!this.travelType.length) {
        return this.$toast('请选择出行方式')
      }

      if (!this.form.arriveTime) {
        return this.$toast('请选择预计抵平时间')
      }

      if (new Date(this.form.startTime.replace(/-/g, '/')).getTime() >= new Date(this.form.arriveTime.replace(/-/g, '/')).getTime()) {
        return this.$toast('抵平时间不得早于出发时间')
      }

      if (!this.form.gatewayId) {
        return this.$toast('请选择抵平卡口')
      }

      if (!this.form.arriveAreaName) {
        return this.$toast('请选择目的地')
      }

      if (this.form.arriveAreaId.substr(this.form.arriveAreaId.length - 3, 3) === '000') {
        return this.$toast('目的地必须选到村或社区')
      }
      
      if (!this.form.fromHighRiskArea) {
        return this.$toast('请选择是否有风险旅居史')
      }

      if (this.form.fromHighRiskArea == 1) {
        if (!this.form.highRiskAreaId) {
          return this.$toast('请选择风险旅居地区')
        }
      }

      if (!this.form.contactPatients) {
        return this.$toast('请选择近七日内是否接触新冠确诊或疑似患者')
      }
      
      if (!this.form.abnormalHealth) {
        return this.$toast('请选择是否有健康异常情况')
      }

      if (this.form.abnormalHealth == 1) {
        if (!this.form.abnormalType) {
          return this.$toast('请选择异常情况')
        }
      }

      if (!this.form.companionCount || this.form.companionCount == 0) {
        this.form.companionCount = 0
        this.form.companionList = []
      }

      if (this.flag) return
      this.flag = true

      this.$loading()
      this.$instance.post(`/app/appepidemicpreventionregisterinfo/addOrUpdate`, {
        ...this.form,
        startAreaId: this.startAreaId,
        startAreaName: this.startAreaName,
        travelType: this.travelType.toString(),
        startTime: this.form.startTime + ':00',
        arriveTime: this.form.arriveTime + ':00',
      }).then(res => {
        this.$hideLoading()
        this.flag = false
        if (res.code == 0) {
          uni.$emit('update')
          this.$toast('提交成功')
          setTimeout(() => {
            uni.reLaunch({url:'./AppReturnHomeRegister'})
          }, 400)
        }
      })
    }
  }
}
</script>

<style lang="scss">
.add {
  padding-bottom: 140px;

  .tips {
    line-height: 1.3;
    padding: 32px 32px;
    color: #FF883C;
    font-size: 30px;
    text-align: justify;
    background: #FFF8F3;
  }

  .title {
    padding: 16px 32px 0 32px;
    box-sizing: border-box;
    background: #fff;
    font-size: 36px;
    font-weight: 600;
  }


  .form-item__group {
    margin-bottom: 24px;
    background: #fff;
  }

  .form-item {
    padding-left: 32px;

    .form-item__checkbox {
      width: 100%;

      div {
        width: 100%;
        height: 80px;
        line-height: 80px;
        margin-bottom: 24px;
        text-align: center;
        background: #FFFFFF;
        border-radius: 16px;
        color: #333333;
        font-size: 28px;
        border: 1px solid #CCCCCC;

        &.active {
          background: #4181FF;
          color: #fff;
          border-color: #4181FF;
        }
      }
    }

    .form-item__radio {
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      div {
        width: 212px;
        height: 80px;
        line-height: 80px;
        margin-right: 16px;
        margin-bottom: 8px;
        text-align: center;
        background: #FFFFFF;
        border-radius: 16px;
        color: #333333;
        font-size: 28px;
        border: 1px solid #CCCCCC;

        &:nth-of-type(3n) {
          margin-right: 0;
        }

        &.active {
          background: #4181FF;
          color: #fff;
          border-color: #4181FF;
        }
      }
    }

    .ai-area__wrapper {
      display: flex;
      align-items: center;
      // padding-left: 100px;

      span {
        color: #333;
        font-size: 30px;
      }

      i {
        color: #999;
        font-size: 30px;
      }

      image {
        width: 16px;
        height: 8px;
      }
    }

    .form-item__wrapper {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 128px;
      padding-right: 28px;
      border-bottom: 1px solid #DDDDDD;

      input {
        flex: 1;
        height: 100%;
        text-align: right;
        color: #333;
        padding-right: 10px;
      }

      .form-item__right {
        display: flex;
        align-items: center;
        font-size: 32px;

        .select {
          ._i {
            padding-left: 100px;
          }
        }

        span {
          max-width: 336px;
          margin-right: 8px;
          color: #333333;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        i {
          margin-right: 8px;
          color: #999999;
        }
        .travelType {
          width: 100%;
          .travelItem {
            width: 100%;
            line-height: 1.3;
            padding: 20px 32px;
            margin-bottom: 16px;
            text-align: center;
            background: #FFFFFF;
            box-sizing: border-box;
            border-radius: 16px;
            color: #333333;
            font-size: 28px;
            border: 1px solid #CCCCCC;
          }

          .active {
            background: #4181FF;
          }
        }
      }
    }

    &:last-child {
      .form-item__wrapper {
        border-bottom: none;
      }
    }

    .form-item__title {
      display: flex;
      align-items: center;

      i {
        font-size: 32px;
        color: #FF4466;
      }

      span {
        font-size: 28px;
        color: #999999;
      }

      h2 {
        padding: 0 4px;
        font-weight: 400;
        font-size: 32px;
        color: #333333;
        max-width: 100%;
        min-width: 260px;
      }
    }


    &.form-item__imgs, &.form-item__textarea {
      .form-item__wrapper {
        display: block;
        height: auto;
        padding-bottom: 32px;
      }

      textarea {
        width: 100%;
        height: 90px;
      }

      .form-item__title {
        padding: 32px 0;
      }

      .form-item__right {
        padding-left: 18px;
      }
    }
  }
}
</style>
