<template>
  <div class="main" :style="{height: lotteryInfo.type === 3 ? '100vh' : ''}">
    <template v-if="lotteryInfo.needCheckPremise && !premise">
      <div class="top">
        <div style="width: 28px;height: 14px;"></div>
        <div class="top-title">请先填写信息</div>
        <div class="top-btn" @click="submit">提交</div>
      </div>
      <div v-if="lotteryInfo.newPremise.length" class="form" :class="{error: isError}">
        <div v-for="item in lotteryInfo.newPremise" :key="item.type">
          <template v-if="item.type === 'name' && item.isChecked">
            <van-field v-model="form.name" label-width="60" label="姓名" placeholder="请输入姓名" @focus="isError = false"/>
          </template>
          <template v-if="item.type === 'phone' && item.isChecked">
            <van-field v-model="form.phone" label-width="60" label="手机号" placeholder="请输入联系电话" @focus="isError = false"/>
            <van-field v-model="form.code" label-width="60" label="验证码" placeholder="请输入验证码" @focus="isError = false">
              <template #button>
                <span class="code" @click="sendCode">
                  <span v-if="!isSend">获取验证码</span>
                  <span v-else>{{ time }}s后重发</span>
                </span>
              </template>
            </van-field>
          </template>
          <template v-if="item.type === 'address' && item.isChecked">
            <template v-if="!addressList.length">
              <van-field v-model="form.address" label-width="60" label="收件地址" readonly placeholder="请选择省市区" @focus="isError = false" @click="select" >
                <template #button>
                  <van-icon name="location" />
                </template>
              </van-field>
              <van-field
                v-model="form.detail"
                label="门牌号"
                label-width="60"
                placeholder="详细地址（精确到门牌号）"
                maxlength="50"
                show-word-limit
                @focus="isError = false"
              />
            </template>
            <template v-else>
              <div v-if="lotteryInfo.newPremise[0].isChecked + lotteryInfo.newPremise[1].isChecked === 0" class="address" @click="isShowAddressPopup = true">
                <img class="address-icon" src="@/assets/images/lottery/address.png" alt="">
                <div class="address-text">{{ form.address + form.detail }}</div>
                <img class="address-right" src="@/assets/images/lottery/address-right.png" alt="">
              </div>
              <div v-else class="address" @click="isShowAddressPopup = true">
                <div class="address-title">收件地址</div>
                <img class="address-icon__alter" src="@/assets/images/lottery/address.png" alt="">
                <div class="address-text">{{ form.address + form.detail }}</div>
                <img class="address-right" src="@/assets/images/lottery/address-right.png" alt="">
              </div>
            </template>
          </template>
          <template v-if="item.type.includes('custom') && item.isChecked">
            <van-field v-model="form[item.type]" :class="item.title.length > 4 ? 'long-title' : ''" label-width="60" :label="item.title" maxlength="50" show-word-limit :placeholder="`请输入${item.title}`" @focus="isError = false"/>
          </template>
        </div>
      </div>
      <div v-else class="form" :class="{error: isError}">
        <van-field v-if="lotteryInfo.premise && lotteryInfo.premise.includes('name')" v-model="form.name" label-width="60" label="联系人" placeholder="请输入联系人" @focus="isError = false"/>
        <template v-if="lotteryInfo.premise && lotteryInfo.premise.includes('phone')">
          <van-field v-model="form.phone" label-width="60" label="手机号" placeholder="请输入联系电话" @focus="isError = false"/>
          <van-field v-model="form.code" label-width="60" label="验证码" placeholder="请输入验证码" @focus="isError = false">
            <template #button>
              <span class="code" @click="sendCode">
                <span v-if="!isSend">获取验证码</span>
                <span v-else>{{ time }}s后重发</span>
              </span>
            </template>
          </van-field>
        </template>
        <template v-if="lotteryInfo.premise && lotteryInfo.premise.includes('address')">
          <van-field v-model="form.address" label-width="60" label="收货地址" readonly placeholder="请选择省市区" @focus="isError = false" @click="select" >
            <template #button>
              <van-icon name="location" />
            </template>
          </van-field>
          <van-field
            v-model="form.detail"
            type="textarea"
            label="门牌号"
            label-width="60"
            placeholder="详细地址（精确到门牌号）"
            rows="2"
            autosize
            maxlength="50"
            show-word-limit
            @focus="isError = false"
          />
        </template>
      </div>
    </template>
    <template v-else>
      <div class="comment-tip">
        在留言区留言即可参与抽奖
      </div>
    </template>
    <van-popup
      v-model="isShowAdd"
      position="bottom"
      round
    >
      <van-area title="区域选择" :area-list="areaList" @confirm="chooseAdd" @cancel="isShowAdd = false"/>
    </van-popup>
    <address-popup
      v-model="isShowAddressPopup"
      :addressList="addressList"
      :addressItem="addressItem"
      :create-api="addAddress"
      :update-api="setAddress"
      :delete-api="removeAddress"
      @confirm="resetAddress"
      @reload="_getAddressList"
    ></address-popup>
  </div>
</template>

<script>
import {
  savePremise,
  setSendSmsCode,
  setValidSmsCode
} from '@/api/modules/lottery'
import { areaList } from '@vant/area-data';
import { mapGetters, mapActions } from 'vuex'
import postMessage from '@/utils/postMessage'
import { getAddressList, removeAddress, setAddress, addAddress } from '@/api/modules/address'
import AddressPopup from '@/components/Common/AddressPopup/AddressPopup.vue'
import UserAgents from '@/utils/UserAgents'
import CONFIG from '@/config'
import Bus from '@/utils/Bus'

export default {
  name: 'ConfigPopup',
  components: {
    AddressPopup,
  },
  data() {
    return {
      form: {
        name: '',
        phone: '',
        code: '',
        address: '',
        detail: '',
        custom1: '',
        custom2: '',
        custom3: '',
      },
      removeAddress,
      setAddress,
      addAddress,
      areaList,
      isShowAdd: false,
      isError: false,
      isSend: false,
      addressList: [1],
      time: 60,
      isShowAddressPopup: false,
      addressItem: null,
    }
  },
  computed: {
    ...mapGetters({
      uin: 'users/uin',
      lotteryInfo: 'lottery/lotteryInfo',
      isLogin: 'users/isLogin',
      premise: 'lottery/premise',
    }),
  },
  // watch: {
  //   'lotteryInfo.newPremise': {
  //     handler(val) {
  //       const isOpen = val && val.some(item => item.isChecked && item.type === 'address')
  //       if (isOpen && this.isLogin && this.addressList.length === 0) {
  //         this._getAddressList(this.resetAddress)
  //       }
  //     }
  //   },
  //   isLogin(val) {
  //     const premise = this.lotteryInfo.newPremise || []
  //     const isOpen = premise && premise.some(item => item.isChecked && item.type === 'address')
  //     if (isOpen && val && this.addressList.length === 0) {
  //       this._getAddressList(this.resetAddress)
  //     }
  //   }
  // },
  mounted() {
    this.dataInit()
    Bus.$on('addressList', (data) => {
      this.addressList = data
      this.resetAddress()
    })
  },
  methods: {
    ...mapActions({
      getLotteryDetail: 'lottery/getLotteryDetail',
      updateInfo: 'lottery/updateInfo',
      checkPremise: 'lottery/check_premise'
    }),
    dataInit() {
      const { id, sessionId: playId, uin } = this.$route.query
      // 拉取场次内基础信息
      this.getLotteryDetail({ id, playId, uin })
        .then(() => {
          this.isLoading = false
          // 微信分享
          if (UserAgents.isWx) {
            const { lotteryInfo } = this
            const wxShare = require('@/utils/wxShare').default
            wxShare.init(
              {
                link: window.location.href,
                title: lotteryInfo?.shareTitle || lotteryInfo?.title || '抽奖',
                desc: lotteryInfo?.intro || window.location.href,
                imgUrl: CONFIG.defShareImg
              },
              { uin }
            )
          }
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    _getAddressList(cb) {
      getAddressList({ uin: this.uin }).then(res => {
        const { code, data, errorMessage, errorCode } = res
        if (code === 200 && errorCode === 0) {
          this.addressList = data
          if (cb) {
            cb()
          }
        }else {
          this.$toast(errorMessage)
        }
      })
    },
    resetAddress(item) {
      this.addressItem = item || this.addressList.find(item => item.isDefault === 1) || this.addressList[0]
      if (this.addressItem?.province) {
        this.form.address = `${this.addressItem.province} ${this.addressItem.city} ${this.addressItem.area} `
        this.form.detail = this.addressItem.detail
      } else {
        this.form.address = ''
        this.form.detail = ''
      }
    },
    select() {
      this.isShowAdd = true
    },
    chooseAdd(val) {
      const str = val[0].name + ' ' + val[1].name + ' ' + val[2].name
      this.form.address = str
      this.isShowAdd = false
    },
    sendCode() {
      if (this.isSend) return
      if (!this.form.phone) {
        this.$toast('请先填写手机号')
        return
      }
      if (!this.form.phone.match(/^s*$|(?:(?:\+|00)86)?1\d{10}$/)) {
        this.$toast('手机号格式不正确')
        return
      }
      const { uin } = this.$route.query
      const phone = this.form.phone
      setSendSmsCode({ uin, phone, module: 'draw' }).then((res) => {
        const { code, errorCode, errorMessage } = res
        if (code === 200 && errorCode === 0) {
          // if (data) {
          //   this.$toast(data)
          // }
          this.$toast('成功')
          let time = 60
          this.isSend = true
          const timer = setInterval(() => {
            time--
            this.time = time
            if (time <= 0) {
              clearInterval(timer)
              this.isSend = false
            }
          }, 1000)
        } else {
          this.$toast(errorMessage)
        }
      })
    },
    submit() {
      if (this.lotteryInfo.newPremise.length) {
        this.submitNewPremise()
      } else {
        this.submitOldPremise()
      }
    },
    submitOldPremise() {
      const { uin } = this.$route.query
      const { name, phone, code, address, detail } = this.form
      if (this.lotteryInfo.premise.includes('name')) {
        if (!name) {
          this.isError = true
          return 0
        }
      }
      if (this.lotteryInfo.premise.includes('address')) {
        if (!address || !detail) {
          this.isError = true
          return 0
        }
      }
      if (this.lotteryInfo.premise.includes('phone')) {
        if (!phone || !code) {
          this.isError = true
          return 0
        }
        setValidSmsCode({ uin, phone, code }).then((res) => {
          const { code, errorCode, errorMessage } = res
          if (code === 200 && errorCode === 0) {
            this.$toast('验证成功')
            this.saveOldPremise()
          } else {
            this.$toast(errorMessage)
          }
        })
      }else {
        this.saveOldPremise()
      }
    },
    saveOldPremise() {
      const { id, uin } = this.$route.query
      const params = {
        id,
        uin,
      }
      if (this.lotteryInfo.premise.includes('name')) {
        params.name = this.form.name
      }
      if (this.lotteryInfo.premise.includes('phone')) {
        params.phone = this.form.phone
      }
      if (this.lotteryInfo.premise.includes('address')) {
        params.address = this.form.address + this.form.detail
      }
      savePremise(params).then(res => {
        const { code, errorCode, errorMessage } = res
        if (code === 200 && errorCode === 0) {
          this.$toast('信息保存成功')
          postMessage.premiseFilled()
          this.visible = false
          this.checkPremise({ id, uin })
          this.dataInit()
        } else {
          this.$toast(errorMessage)
        }
      })
    },
    submitNewPremise() {
      const { uin } = this.$route.query
      const { phone, code, address, detail } = this.form
      // 校验表单
      for (let i = 0; i < this.lotteryInfo.newPremise.length; i++) {
        const item = this.lotteryInfo.newPremise[i]
        if (item.isChecked) {
          if (!this.form[item.type]) {
            this.isError = true
            return 0
          }
          if (item.type === 'address') {
            if (!address || !detail) {
              this.isError = true
              return 0
            }
          }
          if (item.type === 'phone') {
            if (!phone || !code) {
              this.isError = true
              return 0
            }
          }
        }
      }
      // 有手机跟验证码数据时，验证手机验证码
      if (phone && code) {
        setValidSmsCode({ uin, phone, code }).then((res) => {
          const { code, errorCode, errorMessage } = res
          if (code === 200 && errorCode === 0) {
            this.$toast('验证成功')
            this.saveNewPremise()
          } else {
            this.$toast(errorMessage)
          }
        })
      } else {
        this.saveNewPremise()
      }
    },
    saveNewPremise() {
      const { id, uin } = this.$route.query
      const params = {
        id,
        uin,
      }
      this.lotteryInfo.newPremise.forEach(item => {
        params[item.type] = this.form[item.type]
        if (item.type === 'address') {
          params.address = this.form.address + this.form.detail
        }
      })
      savePremise(params).then(res => {
        const { code, errorCode, errorMessage } = res
        if (code === 200 && errorCode === 0) {
          this.$toast('信息保存成功')
          postMessage.premiseFilled()
          this.visible = false
          this.checkPremise({ id, uin })
          this.dataInit()
        } else {
          this.$toast(errorMessage)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.main {
  min-height: 42vh;
  padding-bottom: 30px;
  background-color: #FFFFFF;
}
.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 12px 12px;
  font-size: 14px;
  &-title {
    font-size: 16px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #333333;
  }
  &-btn {
    font-size: 15px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: #357BF0;
  }
}
.form {
  /deep/ .van-icon {
    font-size: 20px;
  }
  .long-title {
    // width: 100px;
    /deep/ .van-field__label{
      height: 24px;
      font-size: 15px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #666666;
      width: auto !important;
    }
  }
  .address {
    display: flex;
    align-items: center;
    // justify-content: space-between;
    padding: 9.5px 13px;
    &-icon {
      width: 24px;
      height: 24px;
      margin-right: 12px;
      &__alter {
        width: 20px;
        height: 20px;
        margin-right: 5px;
      }
    }
    &-text {
      flex: 1;
      // width: 225px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 15px;
      color: #333333;
      line-height: 24px;
      text-align: justify;
      padding-right: 20px;
    }
    &-right {
      width: 5px;
      height: 9px;
    }
    &-title {
      height: 24px;
      line-height: 24px;
      font-size: 15px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #666666;
      margin-right: 8px;
    }
  }
  .code {
    font-size: 15px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: #357BF0;
  }
  /deep/ .van-field__control {
    padding-right: 40px;
  }
  /deep/ .van-field__word-limit {
    position: absolute;
    top: 0;
    right: 0;
  }
  /deep/ .van-cell {
    padding: 9.5px 13px;
    font-size: 15px;
  }
  /deep/ .van-field__label{
    height: 24px;
    line-height: 24px;
    font-size: 15px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: #666666;
    margin-right: 8px;
    span {
      white-space: nowrap;
    }
  }
  /deep/ .van-field__word-limit{
    color: #999;
  }
  /deep/ .van-cell::after {
    border-bottom: none;
  }
}
.error {
  /deep/ .van-field__control::placeholder {
    color: red;
  }
}
/deep/ .van-picker__cancel {
  font-size: 15px;
}
/deep/ .van-picker__confirm {
  font-size: 15px;
  color: #357BF0;
}
.comment-tip {
  text-align: center;
  font-size: 30px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #666666;
  padding: 12px 13px;
  line-height: 80vh;
}
</style>
