<template>
  <view class="Mall4j page-apply-distCon">
    <view
      id="main"
      :class="['main',{ 'no-over-page':heightEle>windowHeight }]"
    >
      <!-- 信息输入框 -->
      <view
        v-if="needRealName && paySettlementType!==1"
        class="section"
      >
        <input
          :placeholder="$t('distribution.actualName')"
          maxlength="30"
          type="text"
          @input="onRealNameInput"
        >
      </view>
      <view
        v-if="needIdCardNo && paySettlementType!==1"
        class="section"
      >
        <input
          :placeholder="$t('distribution.identification')"
          type="text"
          maxlength="18"
          @input="onIdCardNoInput"
        >
      </view>
      <view v-if="neddIdCardPic && paySettlementType!==1">
        <view
          class="upload"
          @tap="onGetImage('uploadIdCardFront')"
        >
          <image
            v-if="identityCardPicFrontCom"
            :src="identityCardPicFrontCom"
            @error="identityCardPicFrontCom=''"
          />
          <text v-else>
            {{ $t('distribution.uploadIDFront') }}
          </text>
        </view>
        <view
          class="upload"
          @tap="onGetImage('uploadIdCardBack')"
        >
          <image
            v-if="identityCardPicBackCom"
            :src="identityCardPicBackCom"
            @error="identityCardPicBackCom=''"
          />
          <text v-else>
            {{ $t('distribution.uploadIDBack') }}
          </text>
        </view>
        <view
          class="upload"
          @tap="onGetImage('uploadIdCardHold')"
        >
          <image
            v-if="identityCardPicHoldCom"
            :src="identityCardPicHoldCom"
            @error="identityCardPicHoldCom=''"
          />
          <text v-else>
            {{ $t('distribution.uploadIDHand') }}
          </text>
        </view>
      </view>

      <!-- 系统判定的条件展示 -->
      <view
        v-if="distributionCondition.autoCheck === 1"
        class="system-decision"
      >
        <view class="system-decision-title">
          如果满足以下所有条件，申请将在提交后自动获得批准
        </view>
        <view class="requirements">
          <view
            v-if="distributionCondition.expenseNumber"
            class="requirement-item"
          >
            消费次数大于等于{{ distributionCondition.expenseNumber }}，确认收货后计入
          </view>
          <view
            v-if="distributionCondition.expenseAmount"
            class="requirement-item"
          >
            消费金额大于等于{{ distributionCondition.expenseAmount }}，确认收货后计入
          </view>
          <view
            v-if="prodList.length"
            class="requirement-item"
          >
            <view class="prod-title">
              购买下列任意一件商品，确认收货后计入
            </view>
            <view class="prod-con">
              <block
                v-for="(item, key) in prodList"
                :key="key"
              >
                <!-- <prod :item="item" /> -->
                <view
                  class="prod-items"
                  @tap="onToProdPage(item.spuId)"
                >
                  <view class="hot-imagecont">
                    <img-show
                      :src="item.mainImgUrl"
                      img-mode="aspectFit"
                      :class-list="['hotsaleimg']"
                    />
                  </view>
                  <view class="hot-text">
                    <view>
                      <view class="hotprod-text">
                        {{ item.spuName }}
                      </view>
                    </view>
                    <view class="prod-text-info">
                      <view class="price">
                        <text class="symbol">
                          ￥
                        </text>
                        <text class="big-num">
                          {{ wxs.parsePrice(item.priceFee)[0] }}
                        </text>
                        <text class="small-num">
                          .{{ wxs.parsePrice(item.priceFee)[1] }}
                        </text>
                      </view>
                    </view>
                  </view>
                </view>
              </block>
            </view>
          </view>
        </view>
      </view>
      <!-- 系统判定的条件展示 end -->
    </view>
    <!-- 提交申请栏 -->
    <view
      v-if="isLoaded"
      :class="['submit-btn',{ 'no-over-page':heightEle>windowHeight }]"
    >
      <view
        class="btn"
        @tap="onSubmitDisterApply"
      >
        <text>{{ $t('distribution.submitApplication') }}</text>
      </view>
    </view>
    <!--end 提交申请栏 -->
  </view>
</template>

<script setup>
import util from '@/utils/util'
const wxs = number()

const paySettlementType = uni.getStorageSync('cloudPaySettlementType')
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL

let identityCardNumber = ''
let identityCardPicBack = ''
let identityCardPicFront = ''
let identityCardPicHold = ''
let realName = ''
let distributionUserId = ''
onLoad(() => {
  // 获取平台分销信息
  onGetDistInfo()
})
onShow(() => {
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: '申请成为分销员'
  })
})

const windowHeight = ref(0) // 屏幕高度
onLoad((options) => {
  if (options.distributionUserId) {
    // #ifdef MP-WEIXIN
    distributionUserId = decodeURIComponent(options.distributionUserId)
    // #endif

    // #ifdef H5 || APP-PLUS
    distributionUserId = options.distributionUserId
    // #endif
  }
  uni.getSystemInfo({
    success: res => {
      windowHeight.value = res.windowHeight // 获取屏幕高度
    }
  })
})

/**
 * 获取平台分销信息
 */
const onGetDistInfo = () => {
  http.request({
    url: '/tmerclub_marketing/distribution_set/info',
    method: 'GET',
    dontShowLogin: true
  }).then(res => {
    if (res.distributionSwitch === 1) {
      // 获取申请分销员需要填写的数据
      onGetApplyInfo()
    } else {
      uni.showModal({
        title: '提示',
        content: '暂未开启分销员招募，请咨询平台',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            if (distributionUserId) {
              uni.switchTab({
                url: '/pages/index/index'
              })
            } else {
              uni.navigateBack()
            }
          }
        }
      })
    }
  })
}
/**
 * 获取申请分销员需要填写的数据
 */
const needIdCardNo = ref(false)
const neddIdCardPic = ref(false)
const needRealName = ref(false)
const distributionCondition = ref({})
const prodList = ref([])
const heightEle = ref(0) // 元素高度
const isLoaded = ref(false) // 是否加载完成
const onGetApplyInfo = () => {
  http.request({
    url: '/tmerclub_marketing/distribution_set/info',
    method: 'GET',
    dontShowLogin: true
  }).then(res => {
    // 判断是否需要填写信息或根据条件自动审核
    if (res.autoCheck !== 1 && !res.identityCardNumber && !res.identityCardPic && !res.realName && !(res.spuList && res.spuList.length)) {
      onSubmitDisterApply()
      return
    }
    isLoaded.value = true
    needIdCardNo.value = res.identityCardNumber
    neddIdCardPic.value = res.identityCardPic
    needRealName.value = res.realName
    distributionCondition.value = res
    prodList.value = res.spuList || []
    // 获取元素高度
    nextTick(() => {
      uni.createSelectorQuery().select('#main').boundingClientRect(data => {
        heightEle.value = data.height
      }).exec()
    })
  })
}
// 跳转商品详情
const onToProdPage = (spuId) => {
  if (!spuId) {
    return
  }

  uni.navigateTo({
    url: '/pages/detail/detail?spuId=' + spuId
  })
}
const onRealNameInput = (e) => {
  realName = e.detail.value
}
const onIdCardNoInput = (e) => {
  identityCardNumber = e.detail.value
}

let tempFiles = null
let currentPicType = ''
const onGetImage = (type) => {
  currentPicType = type
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    success: res => {
      tempFiles = res.tempFiles
      onUploadImg()
    }
  })
}

// 上传图片
let ossList = []
const onUploadImg = () => {
  const fileNames = tempFiles?.map(item => {
    let fileName = ''
    // #ifdef H5
    fileName = item.name
    // #endif
    // #ifdef APP-PLUS|| MP-WEIXIN
    fileName = item.path
    // #endif
    return fileName
  }).join(',')
  http.request({
    url: '/tmerclub_biz/ua/oss/get_batch_pre_sign_url',
    method: 'GET',
    data: { fileNames }
  }).then(res => {
    ossList = res
    onConfirmUpload()
  })
}

/**
 * 确认上传
 */
const onConfirmUpload = () => {
  const attachFile = Object.assign({
    fileType: tempFiles[0].type ? tempFiles[0].type.split('/') : null,
    fileName: tempFiles[0].name,
    fileSize: tempFiles[0].size,
    type: 1
  })
  attachFile.filePath = '/' + ossList[0].dir + ossList[0].fileName
  util.awsUpload(ossList, tempFiles).then(() => {
    uni.hideLoading()
    const filePath = ossList[0].dir + ossList[0].fileName
    onUploadSuccess(filePath)
  })
}
const identityCardPicBackCom = ref('')
const identityCardPicFrontCom = ref('')
const identityCardPicHoldCom = ref('')
const onUploadSuccess = (filePath) => {
  if (currentPicType === 'uploadIdCardFront') {
    identityCardPicFrontCom.value = resourcesUrl + '/' + filePath
    identityCardPicFront = '/' + filePath
  } else if (currentPicType === 'uploadIdCardBack') {
    identityCardPicBackCom.value = resourcesUrl + '/' + filePath
    identityCardPicBack = '/' + filePath
  } else {
    identityCardPicHoldCom.value = resourcesUrl + '/' + filePath
    identityCardPicHold = '/' + filePath
  }
}

/**
 * 提交申请
 */
const onSubmitDisterApply = () => {
  if (paySettlementType !== 1 && needRealName.value && realName.length < 2) {
    uni.showToast({
      title: $t('distribution.enterRealName'),
      icon: 'none'
    })
  } else if (paySettlementType !== 1 && needIdCardNo.value && !util.checkIDCard(identityCardNumber)) {
    uni.showToast({
      title: $t('distribution.identificationTips'),
      icon: 'none'
    })
  } else if (paySettlementType !== 1 && neddIdCardPic.value && identityCardPicFront === '') {
    uni.showToast({
      title: $t('distribution.uploadIDFront'),
      icon: 'none'
    })
  } else if (paySettlementType !== 1 && neddIdCardPic.value && identityCardPicBack === '') {
    uni.showToast({
      title: $t('distribution.uploadIDBack'),
      icon: 'none'
    })
  } else if (paySettlementType !== 1 && neddIdCardPic.value && identityCardPicHold === '') {
    uni.showToast({
      title: $t('distribution.uploadIDHand'),
      icon: 'none'
    })
  } else {
    http.request({
      url: '/tmerclub_marketing/distribution_register/add_distribution_user',
      method: 'post',
      data: {
        identityCardNumber,
        identityCardPicBack,
        identityCardPicFront,
        identityCardPicHold,
        realName,
        sharer: distributionUserId
      }
    }).then(() => {
      uni.showModal({
        content: distributionCondition.value.autoCheck === 2 ? $t('distribution.passAudit') : $t('distribution.applicationSubmitted'),
        showCancel: false,
        cancelText: $t('distribution.cancel'),
        confirmText: $t('distribution.confirm'),
        complete: () => {
          if (distributionCondition.value.autoCheck === 2) {
            uni.redirectTo({
              url: '/package-activities/pages/distribution-center/distribution-center'
            })
            return
          }
          uni.switchTab({
            url: '/pages/my/my'
          })
        }
      })
    })
      .catch(() => {
        uni.switchTab({
          url: '/pages/my/my'
        })
      })
  }
}

</script>
<style lang="scss" scoped>
@use "./apply-distCon.scss";
</style>
