<template>
  <div
    class="page"
    v-if="isShow"
    id="perfect-info"
    :style="{ paddingTop: CustomBar + 'px' }"
  >
    <div class="head">
      <div class="box"></div>
      <div>
        您的生日是会员权益非常重要的参考信息，且填写后不支持修改，请您填写准确真实的生日信息。
      </div>
    </div>
    <div class="form-wrap">
      <div class="form__item" style="border-top: none">
        <div class="form__label">姓名</div>
        <div class="form__input">
          <input
            type="text"
            v-model="memberInfo.vipname"
            placeholder-class="placeholder_input"
            :disabled="vipnameIsDisabled"
            placeholder="请输入姓名"
          />
        </div>
      </div>
      <div class="form__item">
        <div class="form__label">性别</div>
        <div class="form__input">
          <!-- <radio-group @change="bindGenderChange" style="display: flex;">
						<label v-for="(item, index) in genderArray" :key="item.value" style="display: flex; margin-right: 100px;">
							<radio :value="item.value" :checked="item.value == genderValue" /><uni-view>{{item.label}}</uni-view>
						</label>
					</radio-group> -->
          <uni-data-checkbox
            v-model="genderValue"
            :localdata="genderArray"
            :map="{ text: 'label', value: 'value' }"
            selectedTextColor="#333333"
            selectedColor="#333333"
          >
          </uni-data-checkbox>
        </div>
      </div>
      <div class="form__item">
        <div class="form__label">出生年月</div>
        <div class="form__input">
          <picker
            mode="date"
            :value="memberInfo.birthday"
            :start="startDate"
            :end="endDate"
            :disabled="birthdayIsDisabled"
            @change="bindDateChange"
          >
            <div
              class="uni-input"
              :class="{ placeholder_input: !memberInfo.birthday }"
            >
              {{ memberInfo.birthday || '请选择出生年月' }}
            </div>
          </picker>
        </div>
      </div>
      <div class="form__item">
        <div class="form__label">所在地址</div>
        <div class="form__input">
          <!-- <input type="text" v-model="memberInfo.address" placeholder-class="placeholder_input"
						placeholder="请输入您的地址" /> -->
          <input
            type="text"
            v-model="allAddress"
            placeholder="请选择所在地址"
            class="form__item-ext"
            placeholder-style="color: #999999"
            @click="selectCity"
            disabled
          />
        </div>
      </div>
      <div v-if="isBeijing" class="form__item">
        <div class="form__label">公司名称</div>
        <div class="form__input">
          <input
            type="text"
            v-model="memberInfo.companyName"
            placeholder-class="placeholder_input"
            placeholder="公司名称"
          />
        </div>
      </div>
      <div v-if="showCertificatenum" class="form__item">
        <div class="form__label">身份证号码</div>
        <div class="form__input">
          <input
            type="text"
            v-model="memberInfo.certificatenum"
            placeholder-class="placeholder_input"
            placeholder="请输入身份证号码"
          />
        </div>
      </div>

      <div v-if="!isTianJin" class="form__item">
        <div class="form__label">邮箱</div>
        <div class="form__input">
          <input
            type="email"
            v-model="memberInfo.mailBox"
            placeholder-class="placeholder_input"
            placeholder="请输入电子邮箱"
          />
        </div>
      </div>
      <div v-if="isTianJin" class="form__item">
        <div class="form__label">详细地址</div>
        <div class="form__input">
          <input
            type="text"
            v-model="memberInfo.address"
            placeholder-class="placeholder_input"
            placeholder="请输入您的地址"
          />
        </div>
      </div>
      <div v-if="isTianJin" class="form__item">
        <div class="form__label">有无子女</div>
        <div class="form__input">
          <uni-data-checkbox
            v-model="babyStatus"
            :localdata="babyStatusArray"
            :map="{ text: 'label', value: 'value' }"
            selectedTextColor="#333333"
            selectedColor="#333333"
          >
          </uni-data-checkbox>
        </div>
      </div>
    </div>
    <div class="btn-wrap">
      <div
        class="btn btn--black"
        style="margin-bottom: 27px"
        @click="beComePromoter"
      >
        保存并提交
      </div>
      <div class="btn btn--white" @click="gotoIndex">跳过</div>
    </div>
    <simple-address
      ref="simpleAddress"
      title="请选择您常驻地区"
      titleColor="#4d4d4d"
      :pickerValueDefault="cityPickerValueDefault"
      @onConfirm="handleAddressConfirm"
      @onChange="handleAddressChange"
      themeColor="#007AFF"
      btnFontSize="32px"
      cancelColor="#999999"
      confirmColor="#4d4d4d"
    >
    </simple-address>
  </div>
</template>

<script>
import { kipGetUserDetail, kipCompleteUser } from '@/utils/api-kip.js';
import { crmUpdateMemberCompleted } from '@/utils/api-crm-member.js';
import MemberCacheTool from '@/utils/member-cache-tool.js';
import KipCacheTool from '@/utils/kip-cache-tool.js';
// const app = getApp()
const app = {};
// import authorize from '@/components/authorize/authorize.vue'
import {
  checkIdNumber,
  checkEmail,
  isTianJinMallid,
  isBeiJingMallid,
} from '@/utils/utils.js';
import simpleAddress from '@/components/simple-address/simple-address.vue';
import { isCruMarketByKey } from '@/utils/location-util.js';
import uniDataCheckbox from './components/uni-data-checkbox/uni-data-checkbox.vue';
export default {
  props: {
    // 是否显示
    isShow: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    // authorize,
    simpleAddress,
    uniDataCheckbox,
  },
  data() {
    const currentDate = this.getDate({
      format: true,
    });
    return {
      memberInfo: {
        birthday: '',
        vipname: '',
        certificatenum: '',
        mailBox: '',
      },
      vipnameIsDisabled: false,
      birthdayIsDisabled: false,
      date: currentDate,
      pickerText: '',
      shareVipcode: '',
      shareShopNo: '',
      vipcode: '',
      isSkip: '', //先跳过的值
      mobile: '',
      genderArray: [
        { label: '男士', value: '1' },
        { label: '女士', value: '2' },
      ],
      genderValue: '0',
      allAddress: '',
      cityPickerValueDefault: [0, 0, 0],
      isBeijing: false,
      logincallback: null,
      isShowHeader: false, // 是否显示导航
      CustomBar: '',
      rotesName: '',
      isTianJin: false,
      babyStatusArray: [
        { label: '有', value: 1 },
        { label: '无', value: 2 },
      ],
      babyStatus: 0,
    };
  },
  computed: {
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      return this.getDate('end');
    },
    showCertificatenum() {
      // KO小程序：北京不显示身份证号
      // 嘉里中心小程序：天津不显示身份证号
      return !this.isBeijing && !this.isTianJin;
    },
  },
  onLoad: function (option) {
    console.log(`===> 完善信息页面： onLoad`);
    if (option) {
      this.logincallback = option;
    }
  },
  created() {
    // 判读是否是天津，天津的完善信息不同与其他商场
    const mallid = uni.getStorageSync('mallid');
    this.isTianJin = isTianJinMallid(mallid);
    this.isBeijing = isBeiJingMallid(mallid);
    const member = uni.getStorageSync('member');
    let routes = getCurrentPages();
    this.rotesName = routes[routes.length - 1].route;
    console.log(this.rotesName);
    uni.getSystemInfo({
      success: (e) => {
        // #ifdef MP-WEIXIN
        let custom = wx.getMenuButtonBoundingClientRect();
        if (this.rotesName == 'pages/automatic/automaticIndex') {
          this.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
        } else {
          this.CustomBar = 0;
        }
        // #endif
      },
    });
  },
  async mounted() {
    console.log(`===> 完善信息页面： onShow`);
    await this.$onLaunched;
    this.isBeijing = isCruMarketByKey('北京');
    const member = uni.getStorageSync('member');
    this.getUserDetail();
  },
  methods: {
    /**
     * 获取页面到顶部的距离
     */
    getHeight() {
      let query = uni.createSelectorQuery().in(this);
      console.log(query, '获取值 gfhffffffffffffffffffffffffffff');
      query
        .select('#perfect-info')
        .boundingClientRect((data) => {
          console.log('元素距离顶部的距离' + data);
          if (data.top == 0) {
            this.isShowHeader = true;
          } else {
            this.isShowHeader = false;
          }
          // 这个
        })
        .exec();
    },
    //跳过
    gotoIndex: function () {
      this.$emit('closeInfo');
      // uni.reLaunch({
      // 	url: '/pages/automatic/automaticIndex'
      // })
    },
    selectCity: function () {
      this.$refs.simpleAddress.open();
    },
    handleAddressChange(e) {
      this.memberInfo.provinceAddress = e.labelArr[0];
      this.memberInfo.cityAddress = e.labelArr[1];
      this.memberInfo.districtAddress = e.labelArr[2];
      this.allAddress = e.label;
    },
    handleAddressConfirm: function (e) {
      if (!this.allAddress) {
        this.memberInfo.provinceAddress = e.labelArr[0];
        this.memberInfo.cityAddress = e.labelArr[1];
        this.memberInfo.districtAddress = e.labelArr[2];
        this.allAddress = e.label;
      }
    },
    bindGenderChange: function (e) {
      console.log(e);
      this.genderValue = e.target.value;
      this.memberInfo.sex = this.genderValue;
    },
    bindMarriageChange: function (e) {
      this.marriageIndex = e.target.value;
      this.memberInfo.marriagestatus = e.target.value;
    },
    bindDateChange: function (e) {
      this.memberInfo.birthday = e.target.value;
    },
    //保存
    beComePromoter: function () {
      console.log(this.memberInfo);
      if (this.checkMemberInfo()) {
        this.saveUserDetail();
      }
    },
    //设置开始和结束时间
    getDate: function (type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 120;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    getUserDetail: function () {
      const _this = this;
      kipGetUserDetail()
        .then((result) => {
          // const result = resp.data;
          if (result && result.code === '000000') {
            const userInfo = result.data;
            _this.handleKipUserToMemberInfo(userInfo);
          } else {
            uni.showToast({
              title: result.message,
              duration: 2000,
              icon: 'none',
            });
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    saveUserDetail: function () {
      const userInfo = this.handleMemberInfoToKipUser(this.memberInfo);
      if (userInfo) {
        uni.showLoading({
          title: '保存中',
          mask: true,
        });
        const _this = this;
        kipCompleteUser(userInfo)
          .then((result) => {
            uni.hideLoading();
            // const result = resp.data;
            if (result && result.code === '000000' && result.data) {
              uni.showToast({
                title: '保存成功!',
                duration: 2000,
                icon: 'none',
              });
              _this.checkIsCompleted(userInfo);
            } else {
              uni.showModal({
                content: result.message,
                showCancel: false,
              });
            }
          })
          .catch((err) => {
            uni.hideLoading();
            console.error(err);
          });
      }
    },
    handleKipUserToMemberInfo(userInfo) {
      if (userInfo && userInfo.extend) {
        const userDetail = userInfo.extend;
        this.memberInfo.kipUserId = userInfo.id;
        // 名称
        this.memberInfo.vipname = userInfo.realName;
        if (this.memberInfo.vipname) {
          this.vipnameIsDisabled = true;
        }
        // 性别
        this.genderValue = userInfo.gender + '';
        this.memberInfo.sex = userInfo.gender;

        // 生日
        this.memberInfo.birthday = userInfo.birthDate;
        if (this.memberInfo.birthday) {
          this.birthdayIsDisabled = true;
        }
        // 邮箱
        this.memberInfo.mailBox = userInfo.email;
        if (this.isBeijing) {
          this.memberInfo.companyName = userDetail.companyName;
        } else {
          // 身份证号
          this.memberInfo.certificatenum = userDetail.certificateNum;
        }

        // 详细地址
        this.memberInfo.address = userDetail.address;
        // 所在地
        const { provinceAddress, cityAddress, districtAddress } = userDetail;
        if (provinceAddress && cityAddress && districtAddress) {
          this.memberInfo.provinceAddress = provinceAddress;
          this.memberInfo.cityAddress = cityAddress;
          this.memberInfo.districtAddress = districtAddress;
          this.allAddress =
            provinceAddress + '-' + cityAddress + '-' + districtAddress;
        }
        this.babyStatus = userDetail.babyStatus;
      }
    },
    handleMemberInfoToKipUser(memberInfo) {
      if (!memberInfo) {
        return;
      }
      const obj = {
        birthDate: this.memberInfo.birthday,
        email: this.memberInfo.mailBox,
        gender: this.genderValue,
        realName: this.memberInfo.vipname,
        provinceAddress: this.memberInfo.provinceAddress,
        cityAddress: this.memberInfo.cityAddress,
        districtAddress: this.memberInfo.districtAddress,
      };
      if (this.isBeijing) {
        obj.companyName = this.memberInfo.companyName;
      } else if (this.isTianJin) {
        obj.babyStatus = this.babyStatus;
        obj.address = this.memberInfo.address;
      } else {
        obj.certificateNum = this.memberInfo.certificatenum;
      }
      return obj;
    },
    checkMemberInfo() {
      const { mailBox, certificatenum } = this.memberInfo || {};
      if (mailBox) {
        if (!checkEmail(mailBox)) {
          uni.showToast({
            title: '邮箱格式错误',
            duration: 2000,
            icon: 'none',
          });
          return false;
        }
      }
      if (certificatenum) {
        if (!checkIdNumber(certificatenum)) {
          uni.showToast({
            title: '身份证号格式错误',
            duration: 2000,
            icon: 'none',
          });
          return false;
        }
      }
      return true;
    },
    handleSelectCityConfirm(e) {
      const [provinceAddress, cityAddress, districtAddress] = e.labelArr;
      this.memberInfo.provinceAddress = e.labelArr[0];
      this.memberInfo.cityAddress = e.labelArr[1];
      this.memberInfo.districtAddress = e.labelArr[2];
      this.allAddress = e.label;
    },
    checkIsCompleted(memberInfo) {
      if (!memberInfo) {
        console.warn('===>memberInfo is null');
        return;
      }
      const _this = this;
      const {
        gender,
        realName,
        birthDate,
        email,
        certificateNum,
        provinceAddress,
        cityAddress,
        districtAddress,
        companyName,
        address,
        babyStatus,
      } = memberInfo || {};

      let isCompleted = true;

      if (
        !gender ||
        !realName ||
        !birthDate ||
        !provinceAddress ||
        !cityAddress ||
        !districtAddress
      ) {
        isCompleted = false;
      }

      if (this.isBeijing) {
        if (!companyName) {
          isCompleted = false;
        }
        if (!email) {
          isCompleted = false;
        }
      } else if (this.isTianJin) {
        if (!babyStatus) {
          isCompleted = false;
        }
        if (!address || address.trim().length == 0) {
          isCompleted = false;
        }
      } else {
        if (!certificateNum) {
          isCompleted = false;
        }
        if (!email) {
          isCompleted = false;
        }
      }

      if (!isCompleted) {
        console.log('===>没有完善信息，直接跳转');
        _this.gotoIndex();
        return;
      }

      console.log('===>会员信息已完善，请求crm接口');
      const kipMember = uni.getStorageSync('kipMember');
      const params = {
        groupId: app.globalData.groupId,
        mallid: app.globalData.mallid,
        kipUserId: kipMember.id,
      };
      uni.showLoading({
        title: '保存中',
        mask: true,
      });
      crmUpdateMemberCompleted(_this.$baseURL, params)
        .then((result) => {
          uni.hideLoading();
          // const result = res.data;
          if (result && result.code == '0') {
            console.log('===>改变crm会员信息完善成功');
            _this.gotoIndex();
          } else {
            uni.showLoading({
              title: '保存失败',
            });
            console.log('===>改变crm会员信息完善失败');
            console.error(result.msg);
            // _this.gotoIndex()
          }
        })
        .catch((err) => {
          console.log('===>改变crm会员信息完善错误');
          console.error(err);
          // _this.gotoIndex()
          uni.showLoading({
            title: '保存失败',
          });
        });
    },
  },
};
</script>

<style lang="less">
.page {
  width: 100%;
  font-size: 30px;
  height: 100vh;
  background: #f4f7ff;
  position: fixed;
  z-index: 999;
  .pageHeader {
    width: 100%;
    height: 88px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.head {
  margin: 20px 40px 0 40px;
  border-left: 1px solid #f4f7ff;
  border-top: 1px solid #aab1d4;
  border-right: 1px solid #f4f7ff;
  border-bottom: 1px solid #f4f7ff;
  border-radius: 12px;
  box-shadow: 0px 0px 9px 0px #aab1d4;
  padding: 40px;
  font-size: 26px;
  position: relative;
  overflow: hidden;
}
.box {
  position: absolute;
  left: 0;
  top: 0;
  height: 12px;
  width: 100%;
  background-color: #737db5;
  border-radius: 8px 8px 0 0;
  opacity: 0.7;
}

.form-wrap {
  margin-top: 10px;
  border-bottom: 1px solid #d8dae0;

  .form__item {
    position: relative;
    display: flex;
    height: 121px;
    padding-right: 30px;
    align-items: center;
    border-top: 1px solid #d8dae0;
    margin-left: 40px;

    .form__label {
      color: #333;
      width: 205px;
      font-size: 34px;
      font-family: PingFangHK-Regular, PingFangHK;
      font-weight: 400;
    }

    .form__input {
      flex: 1;
      color: #999;
      input {
        font-size: 34px;
        color: #999;
        font-family: PingFangSC-Regular, PingFang SC;
      }
      ::v-deep .checklist-text,
      .placeholder_input {
        font-size: 34px !important;
        color: #999;
        font-family: PingFangSC-Regular, PingFang SC;
      }
    }
  }
}

.btn-wrap {
  margin: 80px 34px;
}

.btn {
  width: 100%;
  height: 100px;
  line-height: 100px;
  font-size: 40px;
  border-radius: 50px;
  text-align: center;
  font-family: PingFangHK-Regular, PingFangHK;
}
.btn--black {
  background-color: #333333;
  color: #ffffff;
}
.btn--white {
  border: 1px solid #979797;
}

/deep/ .checklist-text {
  color: #999999;
}
</style>
