<template>
  <div class='insured-info-container pb50'>
    <!-- 基本信息 -->
    <van-cell-group class='mt10'>
      <p style='border-bottom: 1px solid #ebedf0' class='fs15 fwb pl10 pv12'>推荐人信息</p>
      <van-field v-model='recommender.name' label='推荐人姓名' name='推荐人姓名' readonly />
      <van-field :value='getAgentGrade(recommender.agentGrade)' label='推荐人职级' name='推荐人职级' readonly />
      <!-- <van-field v-model="recommender.applyNo" label="推荐人工号" name="推荐人工号" readonly /> -->
      <van-field v-model='recommender.unitName' label='销售机构' name='销售机构' readonly />
      <p style='border-bottom: 1px solid #ebedf0' class='fs15 fwb pl10 pv12'>个人信息</p>
      <van-field v-model='userInfo.name' label='姓名' name='姓名' placeholder='请输入' v-validate="'required|name'"
                 clearable />
      <van-field
        :value="userInfo.applGrade | idToText('applGrade')"
        v-validate="'required'"
        readonly
        label='职级'
        name='职级'
        right-icon='arrow'
        placeholder='请选择职级'
        @click="toSelect('13')"
      />

      <van-field
        :value="userInfo.idType | idToText('idType')"
        v-validate="'required'"
        readonly
        label='证件类型'
        name='证件类型'
        right-icon='arrow'
        placeholder='请选择证件类型'
        @click="toSelect('1')"
      />
      <van-field
        v-model='userInfo.idNo'
        placeholder='请输入证件号码'
        label='证件号码'
        name='证件号码'
        v-validate="'required'"
        maxlength='18'
        clearable
        @blur='getRelatedData(userInfo.idNo)'
      />
      <select-radio :radios='sexRadio' label='性别'  name='性别' v-validate="'required'" :required='false'
                    :value.sync='userInfo.sex'></select-radio>
      <van-field v-model='userInfo.mobile' label='手机号' name='手机号' placeholder='请输入手机号' v-validate="'required|mobile'"
                 maxlength='11' clearable />
      <van-field v-model='userInfo.authCode' center clearable label name='短信验证码' placeholder='请输入短信验证码'
                 v-validate="'required'" maxlength='6'>
        <van-button slot='button' size='small' type='danger' @click='getCode' :disabled='codeDisabled'
                    v-no-more-click='1000'>
          {{ codeDisabled ? `${countDown}s后重新获取` : '获取验证码' }}
        </van-button>
      </van-field>
    </van-cell-group>
    <van-button type='danger' class='bottom-btn' @click='nextStep' v-no-more-click='1000'>提交信息</van-button>

    <!-- 字段选择 -->
    <van-popup v-model='popupShow' position='bottom'>
      <van-picker show-toolbar :columns='columns' @confirm='onConfirm' @cancel='popupShow = false' />
    </van-popup>
  </div>
</template>
<script>
import { Field, CellGroup, Checkbox, Popup, Picker, Area, RadioGroup, Radio, Dialog } from 'vant';
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 DataDictionary from '@/assets/js/utils/data-dictionary';
import areaList from '@/assets/js/utils/area';
import { getTokenForAgent, agentInfowxSubmit, getTokenForUserModel } from '@/api/ebiz/agentEenter/agentEenter';
import utilsAge from '@/assets/js/utils/age';
import getAreaName from '@/assets/js/utils/get-area-name';
import IdentityCardScan from '@/components/ebiz/sale/IdentityCardScan';
import idNoCheck from '@/assets/js/utils/idNoCheck';
import beforeDate from '@/assets/js/utils/getBeforeDate.js';
import { idToData } from '@/assets/js/utils/verification';
import { weixinShare } from '@/assets/js/utils/wxShare.js';
import axios from 'axios';
import index from '@/config/index';
import { getAuthCode,CommitmentSelfCheck } from '@/api/ebiz/sale/sale';


export default {
  name: 'insuredInfo',
  components: {
    [SelectRadio.name]: SelectRadio,
    [FieldDatePicter.name]: FieldDatePicter,
    [OccupationPicker.name]: OccupationPicker,
    [CustomerPicker.name]: CustomerPicker,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Checkbox.name]: Checkbox,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Area.name]: Area,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [IdentityCardScan.name]: IdentityCardScan
  },
  data() {
    return {
      sexRadio: [
        {
          label: '男',
          value: '0'
        },
        {
          label: '女',
          value: '1'
        }
      ],
      maxDate: beforeDate.getBeforeYear(18),
      popupShow: false,
      censusShow: false, //户籍联动
      pickerType: undefined,
      columns: [],
      valueKey: 'text',
      census: '', //户籍
      recommender: {
        name: '--',
        agentGrade: '--',
        unitName: '--',
        applyNo: '--'
      },
      agentGrade: '',
      userInfo: {
        name: '', //投保人姓名
        sex: '', //投保人性别
        idType: '1', //证件类型
        idNo: '', //证件号码
        mobile: '',//手机号
        applGrade: '' // 职级
      },
      areaList: areaList,
      token: '',
      wxShareDesc: '',
      codeDisabled: false, //获取验证码按钮是否禁用
      countDown: 60, //获取短信验证码倒计时
      sessionId: '' //后台返回的 id
    };
  },
  mounted() {
    if (this.$route.query.content) {
      window.localStorage.setItem('wxShareDesc', this.$route.query.content);
    }
    weixinShare({
      title: '国富人寿欢迎你！',
      imgUrl: this.$assetsUrl + 'images/logo.png',
      desc: localStorage.wxShareDesc,
      link: location.origin + '/#/agentEenter/ShareInfo?token=' + localStorage.token
    });
  },
  created() {
    if (this.$route.query.token) {
      // this.token = this.$route.query.token
      window.localStorage.setItem('token', this.$route.query.token);
    } else {
      this.$toast.fail('链接已失效，请联系代理人重新分享！');
    }
    this.getData();
  },
  methods: {
    getData: function() {
      let self = this;
      self.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '加载中……'
      });
      getTokenForUserModel({
        token: this.$CacheUtils.getLocItem('token')
      }).then(function(response) {
        self.$toast.clear();
        console.log('response', response);
        if (response.result == '0') {
          self.recommender = response;
        } else {
          this.$toast.fail(response.resultMessage);
        }
      })
        .catch(function(error) {
          // this.$toast.fail(error)
        });
      // var self = this
      // //获取推荐人信息
      // let data = {
      // }
      // // console.log('getData', data)
      // getTokenForAgent(data)
      //   .then(res => {
      //     // console.log(res)
      //     if (res.result == 0) {
      //       self.recommender = res
      //     } else {
      //       this.$toast.fail(res.resultMessage)
      //     }
      //   })
      //   .then(function(err) {
      //     console.log(err)
      //   })
    },
    getAgentGrade(agentGrade) {
      let result = '';
      DataDictionary.agentGrade.map((item, index) => {
        for (var key in item) {
          if (key == agentGrade) {
            result = item[agentGrade];
          }
        }
      });
      return result;
    },
    // 下一步
    nextStep() {
      var self = this;
      self.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '加载中……'
      });
      this.$validator.validate().then(valid => {
        if (true === valid) {
          self.$toast.clear();
          if (this.userInfo.idType == '1') {
            //身份证
            // 证件号码规则校验
            if (!idNoCheck.isIdno(this.userInfo.idNo)) {
              return this.$toast('请录入正确的身份证');
            }
            if (this.userInfo.idNo.length == '18') {
              //18位身份证第17位是性别位, 奇男偶女
              let sexSign = this.userInfo.idNo.substr(16, 1);
              if ((parseInt(sexSign) % 2 == 0 && this.userInfo.sex != 1) || (parseInt(sexSign) % 2 != 0 && this.userInfo.sex != 0)) {
                return this.$toast('性别录入与身份证不符');
              }
            }
              self.save();
          } else {
            self.save();
          }
        } else {
          this.$toast(this.$validator.errors.all()[0]);
        }
      });
    },
  async  save() {
      let checkStr ='';
      let recmd=this.userInfo;
      recmd.source='XG';
      recmd.agentCode='A860101000001';
      recmd.birthday='';
      let checkData = {
        token: this.$CacheUtils.getLocItem('token'),
        recmdDTO:recmd
      };
    const resp =    await CommitmentSelfCheck(checkData);
    if (resp.result == '0' && resp.content.data.ruleList && resp.content.data.ruleList.length ) {
      checkStr='<span style="color: red;width:auto; display: block;text-align: left">温馨提示:</span>'+resp.content.data.ruleList[0].retMsg
    }
    // else {
    //  console.log(resp.resultMessage);
    // }
      let str ='是否确认提交？手机号与证件信息会作为您入司的重要信息，一旦提交无法再次修改！<br/> '
              +checkStr;
     // let str ='是否确认提交？手机号与证件信息会作为您入司的重要信息，一旦提交无法再次修改！<br/> ' +
           //   '<span style="color: red;width:auto; display: block;text-align: left">温馨提示:</span>尊敬的代理人，您好！您在我司属于二次入司人员,原名下保单85668955426144655640已失效，为更好的维护您的利益，建议您先将保单复效后再继续提交入司申请，否则上号后两年内不可投保新契约自保件，保单复效办理，详询4006946688';
      Dialog.confirm({
        title: '提示',
        message: str,
        messageAlign:'left'
      }).then(() => {
        let data = {
          // userModel: { //线上去掉
          //   mobile: '18978145583'
          // },
          entryType: 'SHARE_ADD',
          ebizEnterCustomerDto: this.userInfo,
          smsCodeDTO: { smsId: this.sessionId, code: this.userInfo.authCode }
          // ebizReferrerDto: this.recommender
        };
        console.log(data);
        let that = this;
        that.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message: '加载中……'
        });
        agentInfowxSubmit(data)
          .then(res => {
            // console.log(res)
            if (res.result == '0') {
              this.$store.commit('updateAgentEnterApplyMsg', this.userInfo);
              that.$toast.clear();
              this.$jump({
                flag: 'h5',
                extra: {
                  url: location.origin + `/#/agentEenter/ShareInfoSuccess`,
                  forbidSwipeBack: '1',
                  backToFirst: '1'
                },
                routerInfo: {
                  path: `/agentEenter/ShareInfoSuccess`
                }
              });
            } else {
              this.$toast(res.resultMessage);
            }
          })
          .then(function(err) {
            console.log(err);
          });
      });
    },
    //弹框选择
    toSelect(pickerType, valueKey) {
      ;[this.popupShow, this.pickerType] = [true, pickerType];
      if (valueKey) this.valueKey = valueKey;
      if (pickerType == '1') {
        this.columns = DataDictionary.idType;
      } else if (pickerType == '13') {
        this.columns = DataDictionary.applGrade;
      }
    },
    // //确认选择字段
    onConfirm(value) {
      this.popupShow = false;
      if (this.pickerType == '1') {
        this.userInfo.idType = value.id;
      } else if (this.pickerType == '13') {
        this.userInfo.applGrade = value.id;
      }
    },
    getRelatedData(val) {
      if (this.userInfo.idType != '1') {
        return;
      }
      if (idToData(val).text) {
        ;[this.userInfo.idNo, this.userInfo.sex] = ['', '']
        return this.$toast(idToData(val).text)
      }
      this.userInfo.sex = idToData(val).sex;
    },

    //获取验证码
    getCode() {
      if (this.userInfo.mobile == '') {
        return this.$toast('请填写手机号');
      }
      this.codeDisabled = true;
      //倒计时
      this.timeId = setInterval(() => {
        this.countDown--;
        if (this.countDown <= 0) {
          window.clearInterval(this.timeId);
          this.codeDisabled = false;
          this.countDown = 60;
        }
      }, 1000);
      let data = {
        operateType: 'appntInfoEntry',
        type: 'H5',
        operateCode: this.userInfo.mobile,
        system: 'agentApp',
        operateCodeType: '0'
      };
      //获取验证码
      getAuthCode(data).then(res => {
        console.log(res);
        if (res.result == 0) {
          this.sessionId = res.sessionId;
        } else {
          this.$toast(res.resultMessage);
        }
      });
    }
  }
};
</script>
<style lang='scss' scoped>
.insured-info-container {
  .referrerW {
    /deep/ .van-cell__title {
      width: 110px;
    }
  }
}
</style>
