<template>
  <div class="getewayAdd">
    <div class="addBox" v-show="pageShow">
      <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">
              <AiSelect v-model="form.gatewayId" :list="getewayData" disabled 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">
              <u-input placeholder="请输入" placeholder-style="color: #FF4466" type="number" v-model="form.phone" :maxlength="11" @blur="phoneChange"/>
            </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">
              <u-input placeholder="请输入" placeholder-style="color: #FF4466" v-model="form.name" :maxlength="20"/>
            </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">
              <AiAreaPicker class="ai-area" v-model="startAreaId" valueLevel="3"  :fullName.sync="startAreaName" all>
                <div class="ai-area__wrapper">
                  <span class="label" v-if="startAreaName">{{ startAreaName }}</span>
                  <i v-else style="color: #FF4466;">请选择</i>
                  <u-icon name="arrow-right" color="#ddd"/>
                </div>
              </AiAreaPicker>
            </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">
              <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 style="color: #FF4466;">请选择</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">
          <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="请输入" type="number" v-model="form.companionCount" :maxlength="20"/>
              <i>人</i>
            </div>
          </div>
        </div>
        <div style="padding: 16px 16px" v-if="form.companionCount > 0"><span style="color: #FF4466">*</span>同行人信息</div>
        <div class="form" v-if="form.companionCount > 0">
          <NamePhone v-for="(item, index) in people" :key="index" :name.sync="item.name"
          :phone.sync="item.phone" :index="index" @delCountHandle="delCountHandle"/>
        </div>
        <div class="addCount" @click="addCountHandle" v-if="form.companionCount > 0">添加同行人</div>
      </div>
      
      <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>

    <AiLogin ref="login" @success="getAuth()"/>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import NamePhone from './components/namePhone.vue'
import dayjs from 'dayjs'
export default {
  appName: "添加卡口记录",
  data() {
    return {
      form: {
        infoType: '0',
        gatewayId: '',  // 卡口id
        gatewayName: '', // 卡口名称
        phone: '',  
        name: '',
        startAreaId: '',
        startAreaName: '',
        travelType: '',
        trainNo: '',  // 车次航班
        description: '',
        arriveTime: '',
        arriveAreaId: '',
        arriveAreaName: '',
        arriveAddress: '',
        fromHighRiskArea: '0',
        highRiskAreaId: '',
        highRiskAreaName: '',
        contactPatients: '0',
        abnormalHealth: '0',
        abnormalType: '',
        companionCount: '',  // 同行人数量
        companionList: [],  // 同行人集合
        riskLevel: '',
      },
      isShowEndTime: false,
      isShowStartTime: false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true
      },
      $areaId: '',
      people: [{
        name: '',
        phone: '',
      }],
      current: 1,
      getewayData: [],
      flag: false,
      travelType: [], // 出行方式
      travelTypeDict: [],
      startAreaId: '',
      startAreaName: '',
      pageShow: false,
      scene: '',
      gatewayName: '',
    }
  },

  components: {
    NamePhone,
  },

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

  onLoad(o) {
    if(o.id) {
      this.form.id = o?.id
      this.getInfo(o.id)
    }
    if(decodeURIComponent(o.scene) != 'undefined') {
      this.scene = decodeURIComponent(o.scene)
    }
    let timeNow = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
    this.form.arriveTime = timeNow.substr(0,timeNow.length - 3)
  },
  onShow() {
    this.$dict.load(['EP_travelType']).then(()=> {
      this.travelTypeDict = this.$dict.getDict('EP_travelType')
      this.$areaId = this.user.$areaId
      this.getewayList()
      setTimeout(()=>{
        if(this.scene.length) {
          this.form.gatewayId = this.scene
          this.form.gatewayName = this.getewayData.filter(item=> item.value == this.scene)?.[0].label || ''
        }
      }, 400)
      if(!this.token) {
        this.$refs.login.show()
      } else {
        this.pageShow = true
      }
    })
  },

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

  methods: {
    ...mapActions(['getUserInfo']),
    // 授权登录
    getAuth() {
      this.$nextTick(() => {
        this.token && this.getUserInfo()
        this.form.gatewayId = this.scene
        this.getewayList()
        this.$forceUpdate()
        setTimeout(()=>{
          let item = this.getewayData.filter(item=> item.value == this.scene)
          this.form.gatewayName = item?.[0].label
        },400)
        this.pageShow = true
      })
    },

    addCountHandle() {
      this.people.push({
        name: "",
        phone: "",
      });
    },

    delCountHandle(index) {
      this.people.splice(index, 1);
    },

    // 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}`
    },

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

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

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

    // 获取卡口列表
    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
            }
          })
        }
      })
    },

    phoneChange(e) {
      if(e.length) {
        this.getOwnerInfo(e)
      }
    },

    // 获取个人信息
    getOwnerInfo(phoneNumber) {
      this.$instance.post(`/app/appepidemicpreventionregisterinfo/queryDetailByIdNumber`, null, {
        params: {
          phone: phoneNumber,
        }
      }).then(res => {
        if(res?.data) {
          this.form.name = res.data.name || ''
          this.startAreaId = res.data.startAreaId
          this.startAreaName = res.data.startAreaName
          this.form.arriveAreaId = res.data.arriveAreaId
          this.form.arriveAreaName = res.data.arriveAreaName
          this.form.arriveAddress = res.data.arriveAddress || ''
        }
      })
    },

    submit() {
      
      if (!this.form.gatewayId) {
        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.name) {
        return this.$toast('请输入姓名')
      }

      if (!this.startAreaId) {
        return this.$toast('请选择从哪来')
      }

      if (this.startAreaId.substr(4,this.startAreaId.length - 4) === '00000000') {
        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.arriveAreaName) {
        return this.$toast('请选择到哪去')
      }

      if (this.form.arriveAreaId.substr(this.form.arriveAreaId.length - 3, 3) === '000') {
        return this.$toast('目的地必须选到村或社区')
      }

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

        if(this.form.companionCount > 100) {
          return this.$u.toast('同行人数最多可填写100人。')
        }

        if(this.people.length != this.form.companionCount) {
          return this.$u.toast('请输入正确的同行人信息')
        } else {
          if(this.people.some(val=> (val.name=='') || (val.phone=='')) ) {
            return this.$u.toast('请输入完整的同行人信息')
          } else {
            this.form.companionList = this.people
          }
        }
      }

      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(),
        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:'./AppGetewayRegister'})
          }, 400)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.getewayAdd {
  .addBox {
    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;
      .addCount {
        padding: 16px 32px;
        box-sizing: border-box;
        color: #4181FF;

        ::v-deep .u-btn--primary {
          border-radius: 16px;
        }
      }
    }

    .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;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        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;

        ::v-deep .u-input,
        input {
          flex: 1;
          height: 100%;
          text-align: right !important;
          color: #333;
          padding-right: 10px;
        }



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

          

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

          span {
            max-width: 300px;
            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;
        }
      }
    }

    .form {
      padding: 0 32px;
      box-sizing: border-box;
    }

    
  }
}
</style>
