<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="scene.length" 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">
              <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="请输入" type="number" v-model="form.phone" :maxlength="11"/>
            </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">
              <AiSelect v-model="form.type" dict="EP_registerPersonType" 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">
              <AiSelect v-model="form.highRiskIndustries" dict="EP_highRiskIndustries" class="select"></AiSelect>
            </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">
              <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"/>
            </div>
          </div>
        </div>
        <div class="form-item" v-show="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.highRiskAreaName">{{ 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"/>
            </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"/>
            </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>

      <!-- 同行情况 -->
      <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="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>

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

<script>
import { mapState, mapActions } from 'vuex'
import NamePhone from './components/namePhone.vue'
export default {
  appName: "添加卡口记录",
  data() {
    return {
      form: {
        infoType: '0',
        gatewayId: '',  // 卡口id
        gatewayName: '', // 卡口名称
        phone: '',  
        name: '',
        idNumber: '',
        type: '', // 人员类别
        highRiskIndustries: '',
        startTime: '',
        startAreaId: '',
        startAreaName: '',
        startAddress: '',
        travelType: '',
        trainNo: '',  // 车次航班
        description: '',
        arriveTime: '',
        arriveAreaId: '',
        arriveAreaName: '',
        arriveAddress: '',
        fromHighRiskArea: '',
        highRiskAreaId: '',
        highRiskAreaName: '',
        contactPatients: '',
        abnormalHealth: '',
        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)
    }
  },
  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(() => {
        // if(this.token) {
          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.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.arriveAreaName = 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
            }
          })
        }
      })
    },

    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: '0',
        }
      }).then(res => {
        if(res?.data) {
          this.form.name = res.data.records?.[0]?.name || ''
          this.form.phone = res.data.records?.[0]?.phone || ''
        }
      })
    },

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

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

      if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.form.idNumber)) {
        return this.$toast('请输入正确的身份证账号')
      }

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

      if (!this.form.name) {
        return this.$toast('请输入姓名')
      }

      if (!this.form.highRiskIndustries) {
        return this.$toast('请选择高危行业')
      }

      if (!this.form.type) {
        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(this.startAreaId.length - 3, 3) === '000') {
        return this.$toast('出发地必须选到村或社区')
      }

      // if (!this.form.startAddress) {
      //   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.arriveAreaName) {
        return this.$toast('请选择目的地')
      }

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

      // if (!this.form.arriveAddress) {
      //   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 = []
      } 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(),
        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:'./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;

        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: 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>
