<template>
  <view class='applyinfo'>
    <view class="form-wrapper" v-if="type == 'parent'">
      <form @submit="formSubmit" @reset="formReset">
        <view class="apply-item flex justify-between align-center">
          <view class="title required">家长姓名</view>
          <view class="flex align-center">
            <input class="uni-input" v-model="parentForm.parentName" name="parentName" placeholder="未填写" />
            <text class="input-icon cuIcon-right"></text>
          </view>
        </view>
        <view class="apply-item flex justify-between">
          <view class="title required">我是宝贝的</view>
          <view class="radio-wrapper">
            <radio-group v-model="parentForm.parentBabyRelation" name="parentBabyRelation">
              <radio class='radio' :checked="parentForm.parentBabyRelation == item.label" color="#FFF699" :value="item.label" v-for="(item, index) in relationList" :key="index">{{ item.label }}</radio>
            </radio-group>
          </view>
        </view>
        <view class="apply-item flex justify-between">
          <view class="title required">联系方式</view>
          <view class="flex align-center">
            <input class="uni-input" v-model="parentForm.parentPhone" name="parentPhone" :maxlength="11" type="number" placeholder="未填写" />
            <text class="input-icon cuIcon-right"></text>
          </view>
        </view>
        <view class="apply-item flex justify-between">
          <view class="title">家庭住址</view>
          <view class="flex align-center">
            <pick-regions name="regionCode" :defaultRegion="defaultRegionCode" @getRegion="handleGetRegion">
              <text :class="['regions', regionName ? '' : 'empty']" >{{ regionName || '未填写' }}</text>
            </pick-regions>
            <text class="input-icon cuIcon-right"></text>
          </view>
        </view>
        <view class="apply-item flex justify-between">
          <view class="title">详细地址</view>
          <view class="flex align-center">
            <input class="uni-input" name="address" v-model="parentForm.address" placeholder="未填写" />
            <text class="input-icon cuIcon-right"></text>
          </view>
        </view>
        <view class="uni-btn-v">
          <button class="cu-btn submit-btn" :disabled="disabled" form-type="submit">保存</button>
        </view>
      </form>
    </view>
    <view class="form-wrapper" v-else>
      <form @submit="formSubmit" @reset="formReset">
        <view class="apply-item flex justify-between align-center">
          <view class="title required">选手头像</view>
          <view class="flex align-center">
      			<!--#ifdef H5-->
            <view class="portrait-box" @tap="uploadImage">
              <image class="portrait" :src="form.headImg || userAva" mode="aspectFill" />
            </view>
      			<!-- #endif -->
            <text class="input-icon cuIcon-right"></text>
          </view>
        </view>
        <view class="apply-item flex justify-between">
          <view class="title required">选手姓名</view>
          <view class="flex align-center">
            <input class="uni-input" v-model="form.babyName" name="babyName" placeholder="未填写" />
            <text class="input-icon cuIcon-right"></text>
          </view>
        </view>
        <view class="apply-item flex justify-between arrow">
          <view class="title required">性别</view>
          <view class="flex align-center">
            <picker mode="selector" name="sex" @change="genderChange" :value="genderIndex" :range="genderList" range-key="label">
              <view class="picker">
                {{ genderList[genderIndex].label || '请选择' }}
              </view>
            </picker>
            <text class="input-icon cuIcon-right"></text>
            <!-- <input class="uni-input" name="input" type="number" placeholder="未填写" />
            <text class="input-icon cuIcon-right"></text> -->
          </view>
        </view>
        <view class="apply-item flex justify-between">
          <view class="title required">出生日期</view>
          <view class="flex align-center">
            <picker mode="date" name="babyBirthday" @change="dateChange" :value="form.babyBirthday">
              <view class="picker">
                {{ form.babyBirthday | dateFormat('YYYY-MM-DD') }}
              </view>
            </picker>
            <text class="input-icon cuIcon-right"></text>
          </view>
        </view>
        <view class="uni-btn-v">
          <button class="cu-btn submit-btn" :disabled="disabled" form-type="submit">保存</button>
        </view>
      </form>
    </view>
  </view>
</template>

<script>
import pickRegions from '@/components/pick-regions/pick-regions.vue';
import { getImgsUrl, uploadFile } from '@/api/common';
import { saveBaby, saveApply, saveApplyOnline } from '@/api/apply';
import areaList from '@/static/js/area.js';
import { mapMutations, mapState } from 'vuex'
const ERR_OK = 200;

export default {
  data() {
    return {
      loading: false,
      disabled: false,
      type: '',
      action: 'save',
      areaList,
      region: [],
      relationList: [
        {
          label: '爸爸',
          value: '1'
        },
        {
          label: '妈妈',
          value: '2'
        },
        {
          label: '爷爷',
          value: '3'
        },
        {
          label: '奶奶',
          value: '4'
        },
        {
          label: '外公',
          value: '5'
        },
        {
          label: '外婆',
          value: '6'
        },
        {
          label: '其它',
          value: '7'
        }
      ],
      genderIndex: 0,
      form: {
        babyName: '',
        headImg: '',
        sex: 1,
        babyBirthday: '2018-08-08'
      },
      parentForm: {
        parentName: '',
        parentBabyRelation: '爸爸',
        parentPhone: '',
        address: ''
      },
      genderList: [
        {
          label: '男',
          value: 1,
        },
        {
          label: '女',
          value: 2,
        }
      ],
      region:[],
      defaultRegion:['北京市','市辖区','东城区'],
      defaultRegionCode: '110101',
			reqBody: {},
      userAva: require('@/static/img/common/empty_avatar.png'),
    }
  },

  filters: {
    genderFilter(val) {
      switch (val){
        case 1:
          return '男'
        case 2:
          return '女'
        default:
          return '未知'
          break;
      }
    }
  },

  components: {
    pickRegions
  },

  computed: {
    regionName: {
      get: function() {
        return this.region.map(item=>item.name).join('/')
      },
      set: function(val) {
        if(val) {
          this.region = val.map(item => {
            return {
              name: item
            }
          })
        }
        return val;
      }
    },
    regionCode() {
      if (this.region.length > 0) {
        return this.region[this.region.length - 1].code;
      } else {
        return this.defaultRegionCode;
      }
    },
    ...mapState({
      baby: 'baby',
      signUp: 'signUp',
      onlineId: 'onlineId',
      offlineId: 'offlineId',
      applyType: 'applyType'
    })
  },


  onLoad(options) {
    if (options) {
      this.type = options.type;
      if(options.type === 'parent') {
        uni.setNavigationBarTitle({
          title: '家长信息'
        });
      }
    }
    const parent = uni.getStorageSync('parent') || '';
    if(parent) {
      this.parentForm = parent;
      this.defaultRegionCode = parent.regionCode;
      // this.defaultRegion = parent.regionCode;
      try {
        this.regionName = JSON.parse(parent.regionCity);
      } catch(e) {
        this.regionName = '';
      }
    }
    if(this.baby) {
      this.form = this.baby;
      this.genderIndex = this.genderList.findIndex(item => item.value == this.baby.sex) || 0;
    }
    if(this.signUp) {
      this.parentForm = this.signUp;
      this.defaultRegionCode = this.signUp.regionCode;
      try {
        this.regionName = JSON.parse(parent.regionCity);
      } catch(e) {
        this.regionName = '';
      }
    }
  },

  onShow() {
    this.getProvinceList();
  },

  methods: {
    // 上传头像
		uploadImage() {
			// 从相册选择图片
			const _this = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album'],
				success: function(res) {
					_this.handleUploadFile(res.tempFilePaths);
				}
			});
		},
		handleUploadFile(data) {
      uni.showLoading({
        title: '上传中'
      });
      // this.loading = true;
      const _this = this;
			const filePath = data.path || data[0];
      _this.$http
				.upload(uploadFile, {
					filePath,
					name: 'file'
				})
				.then(res => {
          // this.$mHelper.toast('上传成功');
          _this.form.headImg = res.data;
          uni.hideLoading();
				})
        .catch(() => {
          uni.hideLoading();
          this.$mHelper.toast('上传失败')
        });
    },
    formSubmit(e) {
      if (this.type === 'user') {
        this.saveOrUptBaby(e);
      } else if (this.type === 'parent') {
        this.saveOrUptParent(e);
      }
    },
    formReset() {},
    // 添加或者修改宝贝
    saveOrUptBaby(e) {
      const rules = [
        { name: 'babyName', checkType: 'notnull', checkRule: '', errorMsg: '选手姓名不能为空' },
        { name: 'babyName', checkType: 'string', checkRule: '2,8', errorMsg: '请输入2-8位选手姓名' },
        { name: 'sex', checkType: 'in', checkRule: '0,1,2', errorMsg: '性别不能为空' },
        { name: 'babyBirthday', checkType: 'notnull', checkRule: '', errorMsg: '出生日期不能为空' }
      ]
      const headImgRules = [
        { name: 'headImg', checkType: 'notnull', checkRule: '', errorMsg: '头像不能为空' },
      ]
      this.reqBody['headImg'] = this.form.headImg;
      let checkHeadImg = this.$mGraceChecker.check(
        this.reqBody,
        headImgRules
      );
      if(!checkHeadImg) {
        this.$mHelper.toast(this.$mGraceChecker.error);
        return false;
      }
      //进行表单检查
      let formData = e.detail.value;
      let checkRes = this.$mGraceChecker.check(formData, rules);
      if(checkRes) {
        this.disabled = true;
        if(this.form.id) { // 修改宝贝
          this.$http
            .put(saveBaby, {
              ...this.form,
              ...this.reqBody,
              ...formData,
              sex: this.genderList[this.genderIndex].value
            })
            .then(res => {
              this.disabled = false;
              this.$mHelper.toast('修改成功', 1500);
              this.$mStore.dispatch('getUserInfo',{
                competitionChildId: this.onlineId
              })
              // 刷新用户
              if (this.$mHelper.prePage() && this.$mHelper.prePage().baby) {
                this.$mHelper.prePage().baby = {
                  ...this.reqBody,
                  ...formData,
                  sex: this.genderList[this.genderIndex].value
                };
              }
              setTimeout(() => {
                this.$mRouter.back();
              }, 1500);
            })
            .catch(() => {
              this.disabled = false;
            })
        } else { // 添加宝贝
          this.$http
            .post(saveBaby, {
              ...this.reqBody,
              ...formData,
              sex: this.genderList[this.genderIndex].value
            })
            .then(res => {
              this.disabled = false;
              this.$mHelper.toast('保存成功', 1500);
              // this.$mHelper.prePage();
              if (this.$mHelper.prePage()) {
                console.log('prePage()', this.$mHelper.prePage())
                this.$mHelper.prePage().baby = {
                  ...this.reqBody,
                  ...formData,
                  sex: this.genderList[this.genderIndex].value
                };
              }
              setTimeout(() => {
                this.$mRouter.back();
              }, 1500);
            })
            .catch(() => {
              this.disabled = false;
            })
        }
      } else {
        this.$mHelper.toast(this.$mGraceChecker.error);
      }
    },
    // 添加或修改家长信息
    saveOrUptParent(e) {
      let rules = [
        { name: 'parentName', checkType: 'notnull', checkRule: '', errorMsg: '请填写家长姓名' },
        { name: 'parentBabyRelation', checkType: 'notnull', checkRule: '', errorMsg: '请选择关系' },
        { name: 'parentPhone', checkType: 'notnull', checkRule: '', errorMsg: '请填写联系方式'},
        { name: 'parentPhone', checkType: 'phoneno', checkRule: '', errorMsg: '联系方式不正确'},
        // { name: 'address', checkType: 'notnull', checkRule: '', errorMsg: '请填写详细地址'},
      ]
      // let regionRule = [
      //   { name: 'regionCode', checkType: 'notnull', checkRule: '', errorMsg: '请填写家庭住址'},
      // ];
      // this.reqBody['regionCode'] = this.region;
      let formData = e.detail.value;
      let checkRes = this.$mGraceChecker.check(formData, rules);
      if (!checkRes) {
        this.$mHelper.toast(this.$mGraceChecker.error);
        return false;
      }
      // 验证住址
      // let regionRes = this.$mGraceChecker.check(this.reqBody, regionRule)
      // if (!regionRes) {
      //   this.$mHelper.toast(this.$mGraceChecker.error);
      //   return false;
      // }
      if (checkRes) {
        if (this.type === 'parent') {
          if (this.parentForm && this.parentForm.id) {
            const parent = {
              ...this.parentForm,
              ...formData,
              regionCode: this.regionCode,
              regionCity: JSON.stringify(this.region.map(item => item.name))
            }
            const url = this.applyType == 0 ? saveApplyOnline : saveApply ; // 0线上 1线下
            this.$http
              .put(url, parent)
              .then(res => {
                // this.$mHelper.prePage().parent = parent;
                this.$mStore.commit('parent', parent);
                // this.$mStore.commit('signUp', parent);
                if (this.applyType == 1) {
                  this.$mStore.dispatch('getUserInfo', {
                    competitionChildId: this.offlineId
                  })
                } else if (this.applyType == 2) {
                  this.$mStore.dispatch('getUserInfoOnline', {
                    competitionChildId: this.onlineId
                  })
                }
                this.$mRouter.back();
              })
              .catch((err) => {
                console.log('err', err)
              })            
          } else {
            const parent = {
              ...formData,
              regionCode: this.regionCode,
              regionCity: JSON.stringify(this.region.map(item => item.name))
            };
            // 将数据存储在本地
            this.$mStore.commit('parent', parent);
            this.$mRouter.back();
          }
        }
      }

    },
    bindMultiPickerColumnChange(e) {
    },
    getProvinceList() {
      const { province_list, city_list, county_list} = areaList;
      this.multiArray = [province_list, city_list, county_list]
    },
    dateChange(e) {
      this.form.babyBirthday = e.detail.value;
    },
    genderChange(e) {
      const index = e.detail.value;
      this.genderIndex = index;
      // this.form.sex = this.genderList[index].value;
    },
    // 获取选择的地区
    handleGetRegion(region){
      console.log(region);
      this.region = region
    }
  }

}
</script>

<style lang="scss">
page {
  background: $color-white;
  // filter: blur(10px);
  height: 100%;
}
.applyinfo {
  padding: 0 22upx;
  .form-wrapper {
    margin-top: 20upx;
  }
  .apply-item {
    border-bottom: 1upx solid #F6F6F6;
    padding: 28upx 0;
    .title {
      min-width: 160upx;
      margin-right: 20upx;
      font-size: 28upx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 40upx;
      &.required {
        &::before {
          display: inline-block;
          margin-right: 1px;
          color: #FF0000;
          font-size: 14px;
          line-height: 1;
          content: "*";
        }
      }
    }
    .input-icon {
      color: #CACACA;
      line-height: 1;
    }
    ::v-deep .radio {
      margin-bottom: 38upx;
      &:nth-child(n+7) {
        margin-bottom: 0;
      }
      .uni-radio-input {
        border: 2px solid #4CD84A;
        width: 30upx;
        height: 30upx;
        margin-right: 8upx;
        &.uni-radio-input-checked {
          background: #FEEB56;
          border: 2px solid #4CD84A !important;
          &::after {
            border: none !important;
          }
        }
      }
      .uni-radio-wrapper {
        margin-right: 70upx;
      }
    }
  }
  ::v-deep .uni-input-input {
    text-align: right;
  }
  .input-placeholder {
    text-align:right;
    font-size: 28upx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
    line-height: 40upx;
  }
  .regions {
    &.empty {
      font-size: 28upx;
      color: #666666;
    }
  }
  .uni-btn-v {
    text-align: center;
    .submit-btn {
      margin-top: 80upx;
      width: 600upx;
      height: 80upx;
      line-height: 80upx;
      font-size: 30upx;
      font-family: PingFangSC-Medium, PingFang SC;
      color: #FFFFFF;
      background: #4CD84A;
      border-radius: 100upx;
    }
  }
  .portrait {
    position: relative;
    width: 120upx;
    height: 120upx;
    border-radius: 50%;
    border: 6upx solid #fff;
  }
}
</style>
