<template>
  <div class="proposal-insured-person pt10">
    <van-cell-group>
      <div class="border-bottom">
        <van-field :value="insured.relationToAppnt | idToText('relationToAppnt')" required clearable readonly label="是投保人的:  " name="投保人是被保险人的" v-validate="'required'" />
      </div>
      <customer-picker
        class="border-bottom"
        @nameChange="nameChange"
        @on-choose="chooseCustomer"
        name="被保险人"
        :readonly="disabled"
        label="姓名"
        @on-click="selectClick('1')"
        :parentShowPicker.sync="customerShowPicker"
        v-model="insured.name"
        :disabled="disabled"
      ></customer-picker>

      <select-radio :disabled="disabled" class="border-bottom" :radios="sexRadio" label="性别" :value.sync="insured.sex"></select-radio>

      <FieldDatePicter
        :disabled="disabled"
        label="出生日期"
        name="出生日期"
        :flag="true"
        :value.sync="insured.birthday"
        type="date"
        :maxDate="currentTime"
        @confirm="dateConfirm"
      ></FieldDatePicter>
      <div class="border-bottom">
        <van-field type="digit" :readonly="disabled" v-model="insured.insuredAge" required v-validate="'required|onlyInteger'" :value="ageShow" @blur="ageBlur" clearable label="年龄" name="年龄" placeholder="被保险人年龄" />
        <!-- <van-field :readonly="disabled" :value="ageShow" @input="changeAgeInput($event)" clearable label="年龄" placeholder="被保险人年龄" /> -->
      </div>
      <occupation-picker
        :disabled="disabled"
        class="border-bottom"
        :value.sync="insured.occupationCode"
        :chooseName.sync="insured.occupationName"
        :lifeGrade.sync="insured.lifeGrade"
        :healthGrade.sync="insured.healthGrade"
        :parentShowPicker.sync="occupationShowPicker"
        @on-choose="chooseOccupation"
        @on-click="selectClick('2')"
        required
        clearable
        label="职业"
        name="职业"
        v-validate="'required'"
        placeholder="被保险人职业"
      />
      <select-radio class="border-bottom" :radios="medicalRadio" label="有无社保" :value.sync="insured.medical"></select-radio>
      <van-field
        v-model="insured.mobile"
        :readonly="disabled"
        clearable
        label="手机号码"
        name="手机号码"
        placeholder="被保险人手机号码"
        v-validate="'mobile'"
      />
      <van-button type="danger" @click="nextStep" class="bottom-btn fs16">下一步</van-button>
    </van-cell-group>
  </div>
</template>
<script>
import SelectRadio from '@/components/ebiz/SelectRadio'
import FieldDatePicter from '@/components/ebiz/FieldDatePicter'
import OccupationPicker from '@/components/ebiz/occipation/OccupationPicker'
import CustomerPicker from '@/components/ebiz/customer/CustomerPicker'
import { updateInsured,getDetail } from '@/api/ebiz/proposal/proposal.js'
import { CellGroup, Field, Dialog, Toast } from 'vant'
import getAge from '@/assets/js/utils/age.js'
import beforeDate from '@/assets/js/utils/getBeforeDate.js'
import { checkSex, checkRelation } from './rule'
import utils from '@/assets/js/utils/date-utils'
import CacheUtils from '@/assets/js/utils/cacheUtils'

export default {
  data() {
    return {
      sexRadio: [
        {
          label: '男',
          value: '0'
        },
        {
          label: '女',
          value: '1'
        }
      ],
      medicalRadio: [
        {
          label: '有',
          value: '0'
        },
        {
          label: '无',
          value: '1'
        }
      ],
      currentTime: beforeDate.getBeforeDays(28),
      insured: {
        name: '',
        insuredAge: '',
        sex: '0',
        birthday: '',
        occupationCode: '',
        occupationName: '',
        mobile: '',
        relationLabel: '',
        relationToAppnt: '',
        medical: '0',
        lifeGrade: '',
        healthGrade: ''
      },
      localInfo: '',
      customerShowPicker: false,
      occupationShowPicker: false,
      currentPopupIndex: '',
      disabled: false,
      ageShow: '' //被保险人显示年龄
    }
  },

  created() {
    document.body.style.backgroundColor = '#F5F5F5'

    this.init()
  },
  mounted() {},
  watch: {
    'insured.insuredAge': {
      handler(newVal) {
        this.ageShow = newVal == '-1' ? '' : newVal
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    async init() {
      this.$jump({
        flag: 'navigation',
        extra: {
          title: '被保险人信息'
        },
      })
      //重置左上角按钮，变成返回
      window.EWebBridge.webCallAppInJs("webview_left_button",{
        reset:"1" //1：重制 其他值不变
      })
      setTimeout(() => {
        EWebBridge.webCallAppInJs('webview_right_button', {
          btns: [
            {
              img: this.$assetsUrl + 'images/del-close.png',
              route: { flag: '', extra: {} }
            }
          ]
        })
      }, 500)
      window.appCallBack = this.appCallBack
      this.localInfo = JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo'))
      let { relationToAppnt, relationName } = this.localInfo
      this.insured.relationToAppnt = relationToAppnt
      this.insured.relationLabel = relationName
      if (this.insured.relationToAppnt == '1') {
        //如果是投被同人 就将投保人信息存入被保险人信息
        this.disabled = true
        this.insured = Object.assign(this.insured, JSON.parse(this.$CacheUtils.getLocItem('proposalAppnt')))
        this.insured.insuredAge = this.insured.birthday?getAge.getAge(this.insured.birthday, new Date()):this.insured.age
        this.insured.medical = localStorage.orderNoSocialSecurity === '1' ? '1' : '0'
        // 建议书投保人/被保人姓名不必填, 填写姓名时展示姓名(落库),不填写姓名时展示性别+年龄,如:男30岁(不落库)
        if(!this.insured.name){
          let sex = this.insured.sex == '0'?'男':'女'
          this.insured.name = sex + this.insured.insuredAge+'岁'
        }
      }
      this.ageShow = this.insured.insuredAge == '-1' ? '0' : this.insured.insuredAge
      //获取详情
      if (this.$route.query.proposalOrderNo && this.$route.query.insuredId) {
        let proposalInfoDTO = {
          orderNo: this.$route.query.proposalOrderNo
        }
        let res = await getDetail(proposalInfoDTO)
        let insuredDTOs = res.content[0].insuredDTOs
        // 建议书投保人/被保人姓名不必填, 填写姓名时展示姓名(落库),不填写姓名时展示性别+年龄,如:男30岁(不落库)
        insuredDTOs.forEach(item => {
          if (item.insuredId == this.$route.query.insuredId) {
            this.insured = item
          }
        })
        if(!this.insured.name){
          let sex = this.insured.sex == '0'?'男':'女'
          this.insured.name = sex+this.insured.insuredAge+'岁'
        }
        let chooseProductCodes = []
        this.insured.riskDTOLst.forEach(item => {
          chooseProductCodes.push(item.mainRiskCode)
        })
        CacheUtils.setLocItem('chooseProductCodes',JSON.stringify(chooseProductCodes))
      }
    },
    // //设置被保险人年龄显示 如果this.insured.age为 -1时显示为空，不为1时显示为正常输入值
    // changeAgeInput(val) {
    //   // this.ageShow = val == '-1' ? '0' : val
    //   this.insured.insuredAge = val
    //           this.$toast('您的年龄不符合投保人的年龄范围')        

    //   console.log(11111111)
    // },
    //年龄变化时，清空出生日期
    //并校验年龄规则按照出生日期的校验规则来定
    ageBlur(){
      if(this.insured.insuredAge){
        this.insured.birthday = ''
        // let minAge = getAge.getAge(utils.formatDate(new Date(this.maxDate),'yyyy-MM-dd'), new Date())
        // let maxAge = getAge.getAge('1900-01-01', new Date())
        // if(this.insured.insuredAge < minAge || this.insured.insuredAge > maxAge){
        //   this.$toast('您的年龄不符合被保人的年龄范围')        
        // } 
      }
    },
    selectClick(index) {
      this.currentPopupIndex = index
      let title = ''
      if (index == 1) {
        ;[this.customerShowPicker, title] = [true, '客户列表']
      } else if (index == 2) {
        ;[this.occupationShowPicker, title] = [true, '职业类别']
      }

      setTimeout(() => {
        this.$jump({
          flag: 'navigation',
          extra: {
            title,
            hiddenLeft: '1'
          }
        })
        this.closeBtn()
      }, 400)
    },
    closeBtn() {
      // 筛选按钮的显示
      this.$jump({
        flag: 'webview_right_button',
        extra: {
          btns: [
            {
              img: this.$assetsUrl + 'images/del-close.png',
              route: { flag: '', extra: {} }
            }
          ]
        }
      })
    },
    appCallBack(data) {
      if (this.currentPopupIndex == 1) {
        this.customerShowPicker = false
        this.currentPopupIndex = ''
        this.$jump({
          flag: 'navigation',
          extra: {
            title: '被保险人信息',
          }
        })
      } else if (this.currentPopupIndex == 2) {
        this.occupationShowPicker = false
        this.currentPopupIndex = ''
        this.$jump({
          flag: 'navigation',
          extra: {
            title: '被保险人信息',
          }
        })
      } else if (this.currentPopupIndex == '') {
        if (data.trigger == 'right_button_click') {
          return this.$dialog
            .confirm({
              className: 'dialog-delete',
              title: '提示',
              message: '退出流程可能会丢失部分数据，是否确认退出？',
              cancelButtonColor: '#E9332E',
              confirmButtonColor: '#FFFFFF'
            })
            .then(() => {
              this.$jump({
                flag: 'h5',
                extra: {
                  title: '建议书列表',
                  forbidSwipeBack: 1, //当前页面禁止右滑返回
                  url: location.origin + `/#/proposal/list`
                },
                routerInfo: {
                  path: `/proposal/list`,
                  type: '1'
                }
              })
          })
            .catch(() => {
              return
          })
        }
      }
    },
    chooseOccupation() {
      this.$jump({
        flag: 'navigation',
        extra: {
          title: '被保险人信息',
          // hiddenRight: '1'
        }
      })
      this.occupationShowPicker = false
    },
    nameChange(data) {
      this.insured.name = data
    },
    dateConfirm(data) {
      let insuredAge = getAge.getAge(data, new Date())
      this.insured.insuredAge = insuredAge
    },
    //点击下一步
    nextStep() {
      // 建议书投保人/被保人姓名不必填, 填写姓名时展示姓名(落库),不填写姓名时展示性别+年龄,如:男30岁(不落库)
      // let sex = this.insured.sex == '0'?'男':'女'
      // let name = sex + this.insured.insuredAge+'岁'
      // if(this.insured.name == name){
      //   this.insured.name = ''
      // }
      //保存有没有社保，在保费计算用到
      //localStorage.setItem('proposalMedical', this.insured.medical == '0' ? '1' : '0')
      localStorage.proposalMedical = this.insured.medical == '0' ? '1' : '0'
      this.insured.insuredAge = String(this.insured.insuredAge)
      let cacheSex = JSON.parse(this.$CacheUtils.getLocItem('proposalAppnt')).sex
      let localSex = this.insured.sex
      let relation = this.localInfo.relationToAppnt
      let resultSex = checkSex(cacheSex, localSex, relation)
      let ageRule = /^[a-zA-Z0-9\.\s\u4e00-\u9fa5]{2,120}$/
      if (this.insured.name && !ageRule.test(this.insured.name)) {
        return Toast.fail('姓名长度为2-120个字符之内，只能输入汉字、数字或者英文')
      }
      if (!resultSex) {
        return Toast.fail('被保险人性别有误')
      }
      this.$validator.validate().then(valid => {
        if (true === valid) {
          this.fromPath()
        } else {
          this.$toast(this.$validator.errors.all()[0])
        }
      })
    },
    //判断跳转来源
    fromPath() {
      let proposalOrderNo = this.$route.query.proposalOrderNo || this.$CacheUtils.getLocItem('proposalNo') || ''
      let codes = localStorage.chooseProductCodes
      let fromSelect = false
      if (codes && codes != '[]') {
        fromSelect = true
      }
      if (fromSelect) {
        //被保人年龄校验
        let relation = this.localInfo.relationToAppnt
        let resultRelation = checkRelation(relation, this.insured.insuredAge) 
        if (!resultRelation) {
          return Toast.fail('0-7岁未成年人须由其父母投保')
        }
        let minAge = getAge.getAge(utils.formatDate(new Date(this.maxDate),'yyyy-MM-dd'), new Date())
        let maxAge = getAge.getAge('1900-01-01', new Date())
        if(this.insured.insuredAge < minAge || this.insured.insuredAge > maxAge){
          return Toast.fail('您的年龄不符合被保人的年龄范围')        
        } 
        //表示从产品列表返回
        //先进行比对 当前信息是否有更改 如果更改
        let locaInsured = JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo'))
        let { name, sex, birthday, occupationCode, medical,insuredAge,mobile} = this.insured
        if (
          locaInsured.name == name &&
          locaInsured.sex == sex &&
          locaInsured.birthday == birthday &&
          locaInsured.occupationCode == occupationCode &&
          locaInsured.medical == medical &&
          locaInsured.insuredAge == insuredAge &&
          locaInsured.mobile == mobile
        ) {
          this.mainPath()
        } else {
          Dialog.confirm({
            className: 'dialog-delete',
            title: '提示',
            message: '当前信息已经发生改变，有可能影响险种费率，是否确认修改并清除险种信息?',
            cancelButtonColor: '#4FC6B3',
            confirmButtonColor: '#FFFFFF'
          })
            .then(() => {
              //在此处进行产品的删除
              let insuredId = locaInsured.insuredId
              this.insured = Object.assign(this.insured, { insuredId })
              let params = {
                orderDTO: {
                  orderInfoDTO: {
                    orderNo: proposalOrderNo
                  },
                  insuredDTOs: [this.insured]
                }
              }
              updateInsured(params).then(res => {
                if (res.result == '0') {
                  this.mainPath()
                }
              })
            })
            .catch(() => {})
        }
      } else {
        //正常流程
        this.mainPath()
      }
    },
    //主流程
    mainPath() {
      // 建议书投保人/被保人姓名不必填, 填写姓名时展示姓名(落库),不填写姓名时展示性别+年龄,如:男30岁(不落库)
      let sex = this.insured.sex == '0'?'男':'女'
      let name = sex + this.insured.insuredAge+'岁'
      if(this.insured.name == name){
        this.insured.name = ''
      }
      let proposalOrderNo = this.$route.query.proposalOrderNo || this.$CacheUtils.getLocItem('proposalNo') || ''
      localStorage.isFrom = 'proposal'
      let insuredInfo = {}
      let cacheInfo = JSON.parse(this.$CacheUtils.getLocItem('saleInsuredPersonInfo'))
      insuredInfo = Object.assign(cacheInfo, this.insured)
      this.$CacheUtils.setLocItem('saleInsuredPersonInfo', JSON.stringify(insuredInfo))
      let url = `/common/selectedProduct?proposalOrderNo=${proposalOrderNo}`
      this.$router.push({ path: url })
      // this.$jump({
      //   flag: 'h5',
      //   extra: {
      //     url: location.origin + `/#${url}`
      //   },
      //   routerInfo: {
      //     path: url
      //   }
      // })
    },
    //选择客户列表中的客户
    chooseCustomer(data) {
      this.customerShowPicker = false
      this.$jump({
        flag: 'navigation',
        extra: {
          title: '被保险人信息',
          // hiddenRight: '1'
        }
      })
      console.log('data == ', data)
      let { customerName, customerSex, birthday, customerPhone, occupationName, occupationCode, lifeGrade, healthGrade, socialSecurity } = data
      let insuredAge = ''
      try {
        insuredAge = getAge.getAge(data['birthday'], new Date())
      } catch (e) {
        console.error(e)
      }
      let insured = {
        mobile: customerPhone,
        birthday: birthday,
        sex: customerSex ? customerSex.toString() : '0',
        name: customerName,
        occupationName: occupationName,
        insuredAge: insuredAge,
        occupationCode: occupationCode,
        lifeGrade: lifeGrade,
        healthGrade: healthGrade,
        medical: socialSecurity ? socialSecurity : '0'
      }
      console.log('insured.insuredAge', insured.insuredAge)
      Object.assign(this.insured, insured)
      console.log('insured == ', insured)
    }
  },

  components: {
    [SelectRadio.name]: SelectRadio,
    [FieldDatePicter.name]: FieldDatePicter,
    [OccupationPicker.name]: OccupationPicker,
    [CustomerPicker.name]: CustomerPicker,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Dialog.name]: Dialog
  }
}
</script>
<style lang="scss">
.proposal-insured-person {
  .van-cell:not(:last-child)::after {
    display: none;
  }
  .border-bottom::after {
    position: absolute;
    z-index: 99;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 0;
    left: 4.26667vw;
    border-bottom: 1px solid #dadada;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }
  .customer {
    .van-cell:not(:last-child)::after {
      position: absolute;
      z-index: 99;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      content: ' ';
      pointer-events: none;
      right: 0;
      left: 4.26667vw;
      border-bottom: 1px solid #dadada;
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
    }
  }
}
</style>
