<template>
  <!-- 医生填写资料业务组件 -->
  <div class="fill-infomation-container">
    <van-form @submit="onSubmit"
              @failed="onFailed"
              ref="doctorFillForm">
      <!-- 医生姓名部分 -->
      <van-cell-group class="section1">
        <van-field v-model="doctorFillForm.doctorName"
                   name="doctorName"
                   label="医生姓名"
                   placeholder="姓名"
                   required
                   :rules="[{ required: true, pattern: patternName, message: '请输入正确的姓名' }]" />
        <van-field v-model="doctorFillForm.idCard"
                   name="idCard"
                   label="身份证号"
                   required
                   maxlength="18"
                   type="text"
                   placeholder="18位身份证"
                   :rules="[{ required: true, pattern: patternIDCard, message: '请输入正确的身份证号码' }]" />
      </van-cell-group>

      <!-- 医生职称部分 -->
      <van-field readonly
                 clickable
                 name="jobTitle"
                 :value="doctorFillForm.jobTitle"
                 label="医生职称"
                 required
                 placeholder="请选择"
                 right-icon="arrow"
                 @click="showPicker = true"
                 :rules="[{ required: true, message: '请选择医生职称' }]" />
      <van-popup v-model="showPicker"
                 position="bottom">
        <van-picker show-toolbar
                    :columns="doctorJobList"
                    @confirm="onConfirm"
                    @cancel="showPicker = false" />
      </van-popup>

      <!-- 医生科室部分 -->
      <van-field readonly
                 clickable
                 name="doctorDepartments"
                 :value="doctorFillForm.doctorDepartments"
                 label="医生科室"
                 required
                 placeholder="请选择"
                 right-icon="arrow"
                 @click="showPicker2 = true"
                 :rules="[{ required: true, message: '请选择医生科室' }]" />
      <van-popup v-model="showPicker2"
                 position="bottom">
        <van-picker show-toolbar
                    :columns="doctorDepartmentsList"
                    @confirm="onConfirm2"
                    @cancel="showPicker2 = false" />
      </van-popup>

      <!-- 执业医院部分 -->
      <van-field readonly
                 clickable
                 name="firstHospital"
                 :value="doctorFillForm.firstHospital"
                 label="执业医院"
                 required
                 placeholder="请选择"
                 right-icon="arrow"
                 @click="show = true"
                 :rules="[{ required: true, message: '请选择执业医院' }]" />
      <van-popup v-model="show"
                 position="bottom"
                 closeable
                 :style="{ height: '50%' }">
        <!-- 搜索框部分 -->
        <van-search v-model="searchValue"
                    show-action
                    placeholder="请输入医院名称"
                    @search="onSearch">
          <template #action>
            <div class="search-btn"
                 @click="onSearch">搜索</div>
          </template>
        </van-search>

        <!-- 内容列表部分 -->
        <van-list v-model="loading"
                  :finished="finished"
                  finished-text="没有更多了"
                  @load="onLoad">
          <van-cell v-for="(item,index) in hospitalList"
                    :key="item.id"
                    class="van-cell-item"
                    @click="handleHospitalItem(item.hospitalname,item.id)">
            <img src="../../static/imgs/doctorRegister/hospital-icon.png"
                 alt="">
            <span>{{item.hospitalname}}</span>
          </van-cell>
        </van-list>
      </van-popup>

      <!-- 首次执业日期部分 -->
      <van-field readonly
                 clickable
                 name="joinWorkdayTime"
                 :value="doctorFillForm.joinWorkdayTime"
                 label="首次执业"
                 placeholder="请选择日期"
                 right-icon="arrow"
                 @click="showPicker3 = true"
                 :rules="[{ required: false, message: '请选择日期' }]" />
      <van-popup v-model="showPicker3"
                 position="bottom">
        <van-datetime-picker v-model="currentDate"
                             type="year-month"
                             title="选择年月"
                             :min-date="minDate"
                             :max-date="maxDate"
                             :formatter="formatter"
                             @confirm="onConfirm3"
                             @cancel="showPicker3=false" />
      </van-popup>

      <!-- 选择全科医生部分 -->
      <van-field readonly
                 clickable
                 name="isEducationDoctor"
                 :value="isEducationDoctorValue"
                 label="全科医生"
                 placeholder="请选择"
                 right-icon="arrow"
                 @click="showPicker4 = true"
                 :rules="[{ required: false, message: '请选择是否全科医生' }]" />
      <van-popup v-model="showPicker4"
                 position="bottom">
        <van-picker show-toolbar
                    :columns="columns"
                    @confirm="onConfirm4"
                    @cancel="showPicker4 = false" />
      </van-popup>

      <van-button class="next-step-btn"
                  type="info"
                  size="large"
                  native-type="submit">下一步</van-button>
    </van-form>
  </div>
</template>

<script>
  import { reqGetJobList, reqGetDoctorDepartmentsList, reqGetHospitalList } from '../../api/doctorRegister/doctorRegister'
  export default {
    name: 'doctorFillInfomation',
    data() {
      return {
        // 校验身份证的正则
        patternIDCard: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}([0-9a-zA-Z]{1})$)/,
        // 校验姓名的正则
        patternName: /^([\u4e00-\u9fa5]{2,20}|[a-zA-Z.\s]{2,20})$/,
        // 是否全科医生
        columns: ['是', '否'],
        // 医生首次执业日期
        minDate: new Date(1949, 0, 1),
        maxDate: new Date(2020, 12, 1),
        currentDate: new Date(),
        // 医生职称列表
        doctorJobList: [],
        // 医生职称列表源数据
        doctorJobListSource: [],
        // 医生科室列表
        doctorDepartmentsList: [],
        // 搜索医生列表
        hospitalList: [],
        // 医生职称弹出框
        showPicker: false,
        // 医生科室列表
        showPicker2: false,
        // 首次置业日期弹窗
        showPicker3: false,
        // 是否全科医生弹窗
        showPicker4: false,
        isEducationDoctorValue: null,   // 该医生全职
        // 显示
        show: false,
        // 搜索关键词
        searchValue: "",
        loading: false,
        finished: false,
        // 搜索参数对象
        searchParams: {
          pageIndex: 1,
          pageSize: 10,
          filters: [
            {
              field: "hospitalname",
              operate: "contains",
              value: ""
            }
          ]
        },
        totalCount: 0,
        // 当前页的表单对象
        doctorFillForm: {
          doctorName: "",       // 医生名字
          idCard: "",         // 医生身份证号
          birthday: "",       // 出生日期
          gender: "",         // 性别   奇数是男性、偶数是女性
          jobTitle: "",       // 医生职称
          jobTitleId: "",     // 医生职称ID
          doctorDepartments: "",    // 医生科室
          departmentId: "",       // 医生科室ID
          firstHospital: "",         // 执业医院
          hospitalId: "",           // 执业医院ID
          joinWorkdayTime: "",      // 首次执业日期
          isEducationDoctor: null,     // 是否是全科医生
        }
      }
    },
    methods: {
      // 获取身份证号中的出生年日期和性别,返回对象
      getIdcardBorn_gender(idcard) {
        let idCardObj = {}
        // 获取年龄
        let born = idcard.substring(6, 14)
        let n1 = born.substring(0, 4)
        let n2 = born.substring(4, 6)
        let n3 = born.substring(6)
        idCardObj.born = n1 + "-" + n2 + "-" + n3
        idCardObj.gender = (+idcard[16]) % 2 == 0 ? 2 : 1
        return idCardObj
      },
      // 表单校验错误的处理函数
      onFailed(errorInfo) {
        console.log(errorInfo)
      },

      formatter(type, val) {
        if (type === 'year') {
          return `${val}年`;
        } else if (type === 'month') {
          return `${val}月`;
        }
        return val;
      },
      // 搜索医生列表触底函数
      onLoad() {
        this.getHospitalList()
      },

      // 获取医院列表数据
      async getHospitalList() {
        const { data: response } = await reqGetHospitalList(this.searchParams)
        this.loading = false
        this.totalCount = response.totalCount
        if (this.totalCount > this.hospitalList.length) {
          this.hospitalList = [...this.hospitalList, ...response.items]
          this.searchParams.pageIndex++
        } else {
          this.finished = true
        }
      },

      // 获取医院列表
      handleHospitalItem(name, id) {
        this.doctorFillForm.firstHospital = name
        this.doctorFillForm.hospitalId = id
        this.show = false
      },
      // 搜索事件
      onSearch() {
        this.searchParams.pageIndex = 1
        this.hospitalList.length = 0
        this.finished = false
        this.searchParams.filters[0].value = this.searchValue
        this.getHospitalList()
      },
      // 获取医生科室列表
      async getDoctorDepartmentsList() {
        const cacheData = JSON.parse(window.sessionStorage.getItem('doctorDepartmentsList'))
        if (!cacheData) {
          const { data: response } = await reqGetDoctorDepartmentsList()
          this.doctorDepartmentsList = response.map(item => {
            item.text = item.label
            if (item.children.length !== 0) {
              item.children.map(item2 => item2.text = item2.label)
            }
            return item
          })
          window.sessionStorage.setItem('doctorDepartmentsList', JSON.stringify(this.doctorDepartmentsList))
        } else {
          this.doctorDepartmentsList = cacheData
        }
      },
      // 获取医生职称数据列表
      async getDoctorJobList() {
        const { data: response } = await reqGetJobList()
        this.doctorJobListSource = response
        this.doctorJobList = response.map(item => item.label)
      },
      async onSubmit(e) {
        console.log("e: ", e)
        const value = e.isEducationDoctor
        // 用于表单验证
        const valideResult = await this.$refs.doctorFillForm.validate()
        this.doctorFillForm = { ...this.doctorFillForm, ...e }
        if(value === '是') {
          this.doctorFillForm.isEducationDoctor = 1
        }else if (value == '否') {
          this.doctorFillForm.isEducationDoctor = 0
        }else {
          this.doctorFillForm.isEducationDoctor = null
        }
        setTimeout(() => {
          // 删除Form对象中的undefined属性
          try {
            delete this.doctorFillForm.undefined
          } catch (error) {
            console.log(error)
          }
          console.log(this.doctorFillForm.idCard)
          let result = this.getIdcardBorn_gender(this.doctorFillForm.idCard)
          this.doctorFillForm.birthday = result.born
          this.doctorFillForm.gender = result.gender
          window.sessionStorage.setItem('doctorFillForm', JSON.stringify(this.doctorFillForm))
          this.$emit('doctorFillForm', this.doctorFillForm)
        }, 100)
      },
      // 医生职称
      onConfirm(value) {
        let res = this.doctorJobListSource.find(item => item.label === value)
        this.doctorFillForm.jobTitleId = res.value
        this.doctorFillForm.jobTitle = value
        this.showPicker = false
      },
      // 医生科室
      onConfirm2(value) {
        this.doctorFillForm.doctorDepartments = value.join('/')
        let res = this.doctorDepartmentsList.find(item => {
          if (item.label === value[0]) {
            item.children.find(item2 => {
              if (item2.label === value[1]) this.doctorFillForm.departmentId = item2.value
            })
          }
        })
        console.log("departmentId: ", this.doctorFillForm)
        this.showPicker2 = false
      },
      // 医生首次执业日期
      onConfirm3(value) {
        let d = new Date(value)
        let dateTime = d.getFullYear() + '-' + (d.getMonth() + 1)
        this.doctorFillForm.joinWorkdayTime = dateTime
        this.showPicker3 = false
      },
      // 是否全科医生确认事件
      onConfirm4(value) {
        this.isEducationDoctorValue = value
        this.showPicker4 = false
      },

    },
    created() {
      this.getDoctorJobList()
      this.getDoctorDepartmentsList()
      this.getHospitalList()
    },
    mounted() {
      // 获取缓存中的数据初始化doctorFillForm
      this.doctorFillForm = JSON.parse(window.sessionStorage.getItem('doctorFillForm')) || {}
      console.log("缓存数据: ", this.doctorFillForm)
      if(this.doctorFillForm.isEducationDoctor !== null) {
        if(this.doctorFillForm.isEducationDoctor===1) {
          this.isEducationDoctorValue = '是'
        }else if(this.doctorFillForm.isEducationDoctor===0) {
          this.isEducationDoctorValue = '否'
        }else {
          this.isEducationDoctorValue = null
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .section1 {
    margin-bottom: 0.2rem;
  }

  .van-search {
    margin-top: 0.8rem;
  }

  .search-btn {
    background-color: #478bfb;
    color: #fff;
    padding: 0 0.2rem;
    border-radius: 0.1rem;
  }

  /deep/.van-cell-item .van-cell__value {
    display: flex;
    align-items: center;
    img {
      margin-right: 0.4rem;
      width: 0.58rem;
    }
  }

  /deep/ .van-field__label {
    text-align: left;
  }

  .next-step-btn {
    /*   position: absolute;
      bottom: 5%;
      transform: translate(-50%); */
    margin: 0.5rem 0;
    width: 90%;
  }
</style>