<template>
  <view class="mail">
    <dHeader :title="integral.orderMail"></dHeader>
    <view class="container">
      <view class="header">
        <view
          class="header-item"
          @click="menuChange(item.value)"
          v-for="item in menu"
          :key="item.value"
        >
          <text class="header-text" :class="{ 'header-active': item.value == current }">
            {{ locale === 'zh' ? item.labelZh : item.labelEn }}
          </text>
        </view>
      </view>
      <view class="address" v-if="current != 1" @click="bindPopup">
        <view class="address-image">
          <image class="img" src="../../static/img/site_address.png"></image>
        </view>
        <view class="address-content">
          <view class="content-text">
            {{ showAddress.address }}
          </view>
          <view class="content-info">
            <view class="info-name">{{ showAddress.name }}</view>
            <view class="info-phone" v-if="showAddress.areaCode"
              >+{{ showAddress.areaCode }}&ensp;{{ showAddress.phone }}</view
            >
          </view>
        </view>
        <view class="address-icon">
          <uni-icons type="right" color="#B7B7B7" size="20"></uni-icons>
        </view>
      </view>
      <view class="address" v-else>
        <view class="address-image">
          <image class="img" src="../../static/img/house.png"></image>
        </view>
        <view class="address-content address-content2">
          <view class="content-text">
            {{ locale === 'zh' ? orderInfo.nodeZh : orderInfo.nodeEn }}
          </view>
        </view>
      </view>
      <view class="main">
        <view class="main-gift">
          <view class="gift">
            <view class="gift-image">
              <image class="img" :src="locale === 'zh' ? orderInfo.imgZh : orderInfo.imgEn"></image>
              <view class="gift-tag">
                <view class="tags">
                  <image class="tag-image" src="../../static/img/score.png"></image>
                  <view class="tag-text">{{ orderInfo.pointsRequire }}</view>
                </view>
              </view>
              <view class="foot-tag">{{ integral.remainder(orderInfo.quantityRemain) }}</view>
            </view>
            <view class="gift-content">
              <view class="gift-content-text">{{
                locale === 'zh' ? orderInfo.titleZh : orderInfo.titleEn
              }}</view>
              <view class="gift-cell">
                <view class="cell-label">{{ integral.redeemType }}</view>
                <view class="cell-text">{{ handExchangeText(orderInfo.pickMethodList) }}</view>
              </view>
              <view class="gift-cell">
                <view class="cell-label">{{ integral.activityTime }}</view>
                <view class="cell-text"
                  >{{ orderInfo.startTime | $parseTime('{y}-{m}-{d}') }}{{ integral.to
                  }}{{ orderInfo.endTime | $parseTime('{y}-{m}-{d}') }}</view
                >
              </view>
            </view>
          </view>
          <view class="main-count">
            <count v-model="num" :max="orderInfo.quantityRemain"></count>
          </view>
        </view>
        <view class="main-footer">
          <view class="mobile">{{ mobile }}</view>
          <input class="inp" :placeholder="integral.codePlaceloader" v-model="code" />

		  <text class="code" v-if="codeTime >0">{{ integral.codeTimeText(codeTime) }}</text>
		  <picker class="code" :range="smsName" @change="handleCode" v-else>
		    <view class="uni-input">{{ integral.code }}</view>
		  </picker>
        </view>
      </view>
    </view>
    <view class="remark">
      <uni-easyinput
        class="input"
        type="textarea"
        :trim="true"
        autoHeight
        :inputBorder="false"
        :maxlength="100"
        v-model.trim="remark"
        :placeholder="integral.remark"
      >
      </uni-easyinput>
      <view class="placeholder">{{ integral.textLength }}</view>
    </view>
    <view class="container-text">
      {{ integral.totalScore(num) }}<view class="container-num">{{ total }}</view
      >{{ integral.totalScore1 }}
    </view>
    <view class="container-btn" @click="bindSubmitOrder">{{ integral.orderMail }}</view>
    <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff">
      <view class="popup-list">
        <view
          class="popup-list-item"
          v-for="(item, index) in addressList"
          :key="index"
          :class="{ 'popup-list-item-active': addressId == item.id }"
        >
          <!-- <label @click="bindCheck($event, item)"
            ><radio class="radio" color="#ff4d4f" :checked="check == item.id" :value="item.name"
          /></label> -->
          <view class="popup-list-item-text" @click="bindAddress(item.id)">
            <view class="item-text-address">{{ item.address }}</view>
            <div class="item-text-content">
              <view class="content-name">{{ item.name }}</view>
              <div class="content-code">+{{ item.areaCode }}</div>
              <view class="content-phone">{{ item.phone }}</view>
            </div>
          </view>
          <view class="popup-list-item-edit" @click="toEditAddress(item.id)">
            <image class="img" src="../../static/img/edit.png"></image>
          </view>
        </view>
      </view>
      <view class="popup-btn" @click="toAddressAdd">
        <image class="img" src="../../static/img/address_add.png"></image>
        <view class="text">{{ integral.addAddress }}</view>
      </view>
    </uni-popup>

    <!-- 确认提交弹窗信息 -->
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        type="success"
        :cancelText="$lang.lang.myInfo.cancel"
        :confirmText="$lang.lang.myInfo.confirm"
        :title="$lang.lang.notices.notice"
        @confirm="dialogConfirm"
        @close="dialogClose"
      >
        <view class="content">
          <view
            >{{ $lang.lang.integral.branch }}
            {{ locale === 'zh' ? orderInfo.nodeZh : orderInfo.nodeEn }}
          </view>
          <view
            >{{ $lang.lang.integral.gift }}
            {{ locale === 'zh' ? orderInfo.titleZh : orderInfo.titleEn }}
          </view>
          <view
            >{{ $lang.lang.integral.Num }}
            {{ num }}
          </view>
          <view
            >{{ $lang.lang.integral.total }}
            {{ total }}
          </view>
          <view
            >{{ $lang.lang.integral.exchangeType }}
            {{ handleExchangeSelected() }}
          </view>
          <view v-if="current != 1 && addressId"
            >{{ $lang.lang.integral.deliveryAddress }}
            {{ showAddress.address }}
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import dHeader from '../../components/dHeader/index.vue'
import count from './components/count.vue'
export default {
  components: {
    dHeader,
    count
  },
  data() {
    return {
      menu: [],
      // 邮寄类型
      current: 0,
      // 数量
      num: 1,
      // 备注
      remark: '',
      // 礼品详细信息
      orderInfo: {},
      // 礼品id
      id: null,
      // 地址信息
      addressList: [],
      // 地址默认选中
      check: 0,
      // 展示地址
      showAddress: {},
      first: true,
      // 地址id
      addressId: null,
      // 验证码
      code: '',
      // 验证码倒计时
      codeTime: 0,
      mobile: '',
	  smsName: ['SMS','WhatsApp'],
	  smsData: [1,2],
    }
  },
  onLoad(route) {
    this.id = route.id
    uni.$on('refreshPreviousPage', (params) => {
      this.bindPopup()
    })
    this.getOrder()
  },
  onShow() {
    this.getAddress()
    this.getUserInfo()
  },
  computed: {
    locale() {
      return this.$lang.locale
    },
    integral() {
      return this.$lang.lang.integral
    },
    // 计算总积分
    total() {
      if (this.orderInfo.pointsRequire) {
        return this.num * this.orderInfo.pointsRequire
      }
      return 0
    }
  },
  methods: {
    async getUserInfo() {
      try {
        const { code, data } = await this.$request.get('/app-api/member/user/get')
        if (code === 0 && data) {
          this.mobile = data.mobile
        }
      } catch (err) {}
    },
    // 送货类型切换
    menuChange(i) {
      this.current = i
    },
    // 获取订单信息 礼品详情
    async getOrder() {
      try {
        const { code, data, msg } = await this.$request.get('/app-api/ecw/reward/get', {
          id: this.id
        })
        if (code === 0 && data) {
          console.log(data)
          this.orderInfo = data
          this.menu = data.pickMethodList
          this.current = data.pickMethodList[0].value
        } else {
          uni.showToast({
            title: msg,
            icon: 'none'
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取验证码
    async handleCode(e) {
      if (this.codeTime > 0) return
      this.codeTime = 60
      this.timer = setInterval(() => {
        this.codeTime--
        if (this.codeTime <= 0) {
          clearInterval(this.timer)
        }
      }, 1000)
      try {
		  var data = {
		    memberId: this.$store.getters.id,
		    nodeValue: 'user-sms-redeem-reward',
		    isTransport: 0,
		    transportId: 0,
		    isOrders: 0,
		    messageType: this.smsData[e.detail.value]
		  }

        await this.$request.post('/app-api/reward/redeem/send-sms-code', data)
      } catch (error) {}
    },
    // 打开弹出层
    bindPopup() {
      this.$refs.popup.open()
    },
    // 获取地址列表
    async getAddress() {
      try {
        const id = this.$store.getters.id
        const { code, data } = await this.$request.get('/app-api/member/user-address/member/list', {
          id
        })
        if (code !== 0) return
        this.addressList = data
        if (this.first) {
          this.first = false
          const defaultAddress = this.addressList.find((item) => item.isDefault === 0)
          if (defaultAddress) {
            this.check = defaultAddress.id
            this.addressId = defaultAddress.id
            this.showAddress = defaultAddress
          } else if (this.addressList.length > 0) {
            this.showAddress = this.addressList[0]
            this.addressId = this.addressList[0].id
          }
        }
        // this.addressChange();
      } catch (error) {
        console.error(error)
      }
    },
    // 切换默认地址
    async bindCheck(e, item) {
      let that = this
      that.check = item.id
      try {
        await that.$request.post('/app-api/member/user-address/update', {
          ...item,
          isDefault: 0
        })
      } catch (err) {}
    },
    // 切换地址
    bindAddress(id) {
      this.addressId = id
      this.addressChange()
    },
    // 地址信息更改
    addressChange() {
      const i = this.addressList.findIndex((item) => item.id === this.addressId)
      if (i >= 0) this.showAddress = this.addressList[i]
      this.$refs.popup.close()
    },
    // 新增地址
    toAddressAdd() {
      uni.navigateTo({
        url: '/pages/address_add/address_add'
      })
      this.$refs.popup.close()
    },
    toEditAddress(id) {
      uni.navigateTo({
        url: '/pages/address_edit/address_edit?id=' + id
      })
      this.$refs.popup.close()
    },
    // 兑换类型返回
    handExchangeText(list) {
      if (!list) return ''
      let str = this.locale === 'zh' ? 'Zh' : 'En'
      return list.map((item) => item[`label${str}`]).join('/')
    },
    //获取选中的兑换类型
    handleExchangeSelected() {
      if (this.orderInfo?.pickMethodList?.length > 0) {
        if (this.locale === 'zh') {
          return this.orderInfo.pickMethodList.filter((element) => {
            return this.current == element.value
          })[0].labelZh
        } else {
          return this.orderInfo.pickMethodList.filter((element) => {
            return this.current == element.value
          })[0].labelEn
        }
      }
    },
    // 提交订单
    bindSubmitOrder() {
      if (!this.code) {
        uni.showToast({
          title: this.integral.codePlaceloader,
          icon: 'none'
        })
        return
      }
      this.$refs.alertDialog.open()
    },
    dialogConfirm() {
      uni.showLoading({
        title: this.$lang.lang.notices.loading
      })
      this.submitOrder()
    },
    dialogClose() {
      this.$refs.alertDialog.close()
    },
    // 提交订单
    async submitOrder() {
      try {
        const memberId = this.$store.getters.id
        const params = {
          memberId,
          code: this.code,
          entrance: 2,
          recipientName: this.showAddress.name,
          recipientAddress: this.showAddress.address,
          recipientPhoneNum: this.showAddress.phone,
          redeemType: this.current,
          rewardCount: this.num,
          rewardId: this.orderInfo.id,
          remark: this.remark
        }
        const { code, msg } = await this.$request.post('/app-api/reward/redeem/single', params)
        if (code === 0) {
          uni.reLaunch({
            url: '/pages/integral/integral'
          })
        } else {
          uni.showToast({
            title: msg,
            icon: 'none'
          })
        }
      } catch (error) {
        console.log(error)
      }
      uni.hideLoading()
    }
  }
}
</script>
<style lang="scss">
page {
  /* #ifdef H5 */
  padding-top: 140upx;
  /* #endif */
  /* #ifdef APP-PLUS */
  padding-top: calc(var(--status-bar-height) + 100upx);
  /* #endif */

  // box-sizing: border-box;
  // height: 100%;
  // background: linear-gradient(#317beb, #d3e5fe);
}
.mail {
  padding: 0 32upx;
}
.container {
  background-color: #fff;
  border-radius: 20upx;
  overflow: hidden;
  box-shadow: 0 2upx 8upx rgba(0, 0, 0, 0.12), 0 0 12upx rgba(0, 0, 0, 0.04);
}
.header {
  display: flex;
  height: 72upx;
  align-items: center;
  justify-content: space-around;
  background-color: #d3e6ff;
}
.header-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24upx;
}
.header-text {
  font-size: 24upx !important;
  color: #333;
}
.header-active {
  padding: 8upx 30upx;
  color: #fff;
  border-radius: 40upx;
  font-size: 28upx;
  font-weight: 600;
  background-color: #045fe7;
}
.address {
  display: flex;
  height: 160upx;
  align-items: center;
  justify-content: space-between;
}
.address-image {
  width: 100upx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10upx;
  .img {
    width: 64upx;
    height: 64upx;
    object-fit: cover;
  }
}
.address-content {
  padding: 20upx 0;
  flex: 1;
  height: inherit;
  display: flex;
  box-sizing: border-box;
  flex-direction: column;
  justify-content: space-between;
  .content-text {
    font-size: 24upx;
    color: #333;
  }
  .content-info {
    width: 100%;
    display: flex;
    color: var(--cb7b);
    font-size: 24upx;
    align-items: center;
    justify-content: space-between;
  }
}
.address-content2 {
  justify-content: center;
}
.address-icon {
  padding-right: 20upx;
  width: 80upx;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  justify-content: right;
}
.main-gift {
  padding: 20upx 30upx;
  border-top: 1px solid var(--cb7b);
  border-bottom: 1px solid var(--cb7b);
  .gift {
    width: 100%;
    display: flex;
  }
  .gift-image {
    position: relative;
    margin-right: 8upx;
    width: 174upx;
    height: 174upx;
    .img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}
.gift-content {
  flex: 1;
  display: flex;
  height: inherit;
  flex-direction: column;
  justify-content: space-between;
  .gift-content-text {
    width: 70%;
    font-size: 22upx;
    color: var(--cb7b);
  }
  .gift-cell {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .cell-label {
      font-size: 22upx;
      color: #333;
    }
    .cell-text {
      font-size: 22upx;
      color: var(--cb7b);
    }
  }
}
.main-count {
  display: flex;
  height: 100upx;
  align-items: center;
  justify-content: right;
}
.main-footer {
  box-sizing: border-box;
  font-size: 24upx;
  padding: 0 28upx;
  width: 100%;
  display: flex;
  height: 84upx;
  align-items: center;
  justify-content: space-between;
  .btn {
    font-weight: 600;
    color: #045fe7;
  }
  .inp {
    font-size: 24upx;
  }
}
.remark {
  position: relative;
  padding: 20upx 30upx;
  overflow: hidden;
  margin-top: 40upx;
  border-radius: 20upx;
  background-color: #fff;
  box-shadow: 0 2upx 8upx rgba(0, 0, 0, 0.12), 0 0 12upx rgba(0, 0, 0, 0.04);
  .input {
    font-size: 24upx;
  }
}
.placeholder {
  position: absolute;
  bottom: 20upx;
  right: 20upx;
  font-size: 20upx;
  color: #b3b3b3;
}
.container-text {
  margin-top: 80upx;
  padding: 0 30upx;
  width: 100%;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  justify-content: flex-end;
  font-size: 24upx;
  color: #333;
}
.container-num {
  font-size: 28upx;
  color: red;
}
.container-btn {
  margin: 20upx auto 0;
  width: 470upx;
  height: 80upx;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  justify-content: center;
  font-size: 28upx;
  color: #fff;
  background-color: #045fe7;
  border-radius: 40upx;
}
.popup-list {
  margin: 30upx 0 20upx 0;
  width: 100%;
  min-height: 100upx;
  max-height: 600upx;
  overflow-y: scroll;
  box-sizing: border-box;
  .popup-list-item {
    margin-bottom: 20upx;
    padding: 20upx 30upx;
    width: 100%;
    display: flex;
    align-items: center;
    font-size: 24upx;
    color: #333;
    box-sizing: border-box;
  }
  .radio {
    transform: scale(0.8);
    margin-right: 10upx;
  }
}
.popup-btn {
  margin: auto;
  margin-bottom: 40upx;
  width: 70%;
  height: 100upx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28upx;
  font-weight: 600;
  background-color: #f0f0f0;
  border-radius: 20upx;
  .img {
    width: 48upx;
    height: 48upx;
    object-fit: cover;
    margin-right: 10upx;
  }
}
.mobile {
  color: #4f4848;
}
.popup-list-item-text {
  min-height: 80upx;
  flex: 1;
  display: flex;
  font-size: 24upx;
  color: #333;
  flex-direction: column;
  justify-content: space-between;
  .item-text-address {
    font-size: 24upx;
    color: #333;
  }
  .item-text-content {
    display: flex;
    align-items: center;
    color: var(--cb7b);
    font-size: 24upx;
  }
  .content-code {
    margin: 0 10upx;
  }
}
.popup-list-item-edit {
  width: 80upx;
  display: flex;
  align-items: center;
  justify-content: center;
  .img {
    width: 40upx;
    height: 40upx;
    object-fit: cover;
  }
}
.popup-list-item-active {
  background-color: #f0f0f0;
}

.gift-tag {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8upx;
  min-width: 80upx;
  height: 32upx;
  box-sizing: border-box;
  background: linear-gradient(#ef7e1a, #f1b009);
  transform: skewX(15deg);
  border-top-right-radius: 10upx;
  border-bottom-left-radius: 10upx;
  .tag-image {
    width: 24upx;
    height: 24upx;
  }
  .tags {
    display: flex;
    align-items: center;
    justify-content: center;
    transform: skewX(-15deg);
  }
  .tag-text {
    margin-left: 4upx;
    font-weight: 500;
    color: #fff;
    font-size: 24upx;
  }
}

.foot-tag {
  position: absolute;
  padding: 0 8upx;
  bottom: 0;
  right: 0;
  z-index: 9;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 110upx;
  height: 32upx;
  color: #fff;
  font-size: 22upx;
  box-sizing: border-box;
  background: linear-gradient(#ef7e1a, #f1b009);
  border-top-right-radius: 10upx;
  border-bottom-left-radius: 10upx;
}
</style>
