<template>
  <div>
    <j-nav-bar/>
    <!--  banner  -->
    <div :style="{paddingBottom: px2vw(20)}" style="overflow: hidden;">
      <van-swipe :autoplay="3000" lazy-render>
        <van-swipe-item v-for="banner in bannerList" :key="banner.bannerUrl">
          <van-image :src="banner.bannerUrl"></van-image>
        </van-swipe-item>
      </van-swipe>
    </div>
    <div :style="{padding: '0 ' + px2vw(30) + ' ' + px2vw(20)}">

      <div class="product">
        <div class="product-title">{{$t('home.productDetails')}}</div>

        <div class="product-content">
          <div class="product-content-label">
            <div>{{$t('home.minimumDailyInterestRate')}}</div>
            <div><span>{{ loans.minMonthRate }}%</span></div>
          </div>
          <div class="product-content-label">
            <div>{{$t('home.borrowingLimit')}}</div>
            <div><span>{{ defaultCoinUnit }}{{ loans.loansMinAccount }}-{{ loans.loansMaxAccount }}</span></div>
          </div>
          <div class="product-content-label">
            <div>{{$t('home.installmentPeriod')}}</div>
            <div><span>{{$t('home.optional')}}{{ loans.loansMonth.replaceAll(',', '/') }}</span></div>
          </div>
        </div>

      </div>


      <div class="apply">
        <div class="apply-title yellow_color">{{$t('home.applicationAmount')}}({{defaultCoinUnit}})</div>

        <div class="apply-money">{{ strip }}</div>

        <div class="apply-strip-box">
          <div class="reduce" @click="moneyReduce(1000)"></div>

          <div class="slider">
            <van-slider bar-height="16" active-color="linear-gradient(to bottom, #f3654d, #f9ad7d)" :max="loans.loansMaxAccount" :min="loans.loansMinAccount" :step="1000" v-model="strip">
              <template #button>
                <div class="custom-button"></div>
              </template>
            </van-slider>
          </div>

          <div class="add" @click="moneyAdd(1000)"></div>
        </div>

        <div class="apply-jkqx">
          <div class="apply-jkqx-title">{{$t('home.loanTerm')}}</div>
          <div class="apply-jkqx-item-box">
            <div v-for="lm in loans.loansMonthList" :key="lm" class="apply-jkqx-item" :class="{'checked': lm === lmChecked}" @click="lmChecked = lm">
              {{ lm }}{{$t('app.month')}}
            </div>
          </div>
        </div>

        <j-gap height="2" background="#fff"/>

        <div class="apply-mqhk">
          <div>{{ $t('home.repaymentPerInstallment') }}</div>
          <div>{{ defaultCoinUnit }}{{ calLoan.avgRepayment }}</div>
          <div>({{ $t('home.dailyInterestRate') }}{{ calLoan.loanRateMonth*100 }}% {{ $t('home.totalInterest') }}{{ defaultCoinUnit }}{{ calLoan.totalInterest }})</div>
        </div>

      </div>
    </div>

    <div class="notice">
      <van-icon :name="getAssetsImages('home/xlb.png')" size="30"/>
      <div>{{ loansUser.time }}</div>
      <div style="color: #ec6401">{{ loansUser.phone }}</div>
      <div>{{ $t('home.successfulBorrowing') }}</div>
      <div style="color: #BC7C1C; font-weight: 600;">{{ defaultCoinUnit }}{{ loansUser.amount }}</div>
    </div>


    <div class="xieyi">
      <van-checkbox v-model="checked" :icon-size="px2vw(28)" style="align-items: baseline" checked-color="linear-gradient(to right, #F9D88D, #D2A64C)">
        {{ $t('home.enterAgreement') }}
        <span class="yellow_color1" @click.stop="go('authAgreement')">《{{ $t('home.authAgreement') }}》</span>
        <span class="yellow_color1" @click.stop="go('serviceAgreement')">《{{ $t('home.serviceAgreement') }}》</span>
        <span class="yellow_color1" @click.stop="go('loansAgreement')">《{{ $t('home.loansAgreement') }}》</span>
      </van-checkbox>
    </div>


    <div style="padding: 0 20px 0">
      <van-button
        color="linear-gradient(to right, #D2A64C, #F9D88D)"
        round
        style="width: 100%; "
        @click.stop="immediateBorrowing"
      >
        {{ $t('home.immediateBorrowing') }}
      </van-button>
    </div>

    <j-gap :height="170" opacity/>
  </div>
</template>

<script lang="ts" setup>
import {debounce, getAssetsImages, px2vw} from "@/utils";
import {computed, onMounted, reactive, ref,onUnmounted} from "vue";
import {useRouter} from "vue-router";
import {useUserStore} from "@/store/modules/user";
import {getCalLoan, getHomeInfo, getLoansInfo, getLoansUser, getOssPolicyInfo, getUserInfo} from "@/api";
import {resetData} from "@/utils/dataUtil";
import {watch} from "vue-demi";
import {showToast} from "vant";
import JGap from "@/components/JGap/JGap.vue";
import { useI18n } from 'vue-i18n';

const user = useUserStore()
const router = useRouter()
const { t } = useI18n()
const bannerList = [
  {
    bannerUrl: getAssetsImages('home/banner_home.png')
  }
]
const defaultCoinUnit = localStorage.getItem('defaultCoinUnit')
const checked = ref(false);
const strip = ref(3000)
const lmChecked = ref('')


const moneyReduce = (step: number) => {
  if (strip.value - step < loans.loansMinAccount) {
    return
  }
  strip.value-=step
}

const moneyAdd = (step: number) => {
  if (strip.value + step > loans.loansMaxAccount) {
    return
  }
  strip.value+=step
}

const go = (key) => {
  // agreement
  router.push({
    path: '/agreement',
    query: {
      key: key
    }
  })
}

const immediateBorrowing = () => {
  if (checked.value) {
    if (userInfo.infoFlag && userInfo.bankFlag && userInfo.cardFlag) {
      router.push({
        path: '/loansInfo',
        query: {
          "totalLoanMoney": strip.value,
          "totalMonth": lmChecked.value
        }
      })
    } else {
      showToast(t('home.pleaseFillInYourPersonalInformationFirst'))
      router.push({
        path: '/userInfo'
      })
    }
    return
  }
  showToast(t('home.pleaseEnterAgreement'))
}

const loans = reactive({
  dueDate: 0,
  id: 0,
  loansInitAccount: 0,
  loansInitMonth: "",
  loansMaxAccount: 0,
  loansMinAccount: 0,
  minDayServiceRate: 0,
  loansMonth: "",
  loansMonthList: [],
  serviceRate: "",
  serviceRateList: [],
  defaultCoinUnit: "$"
})
const _getLoansInfo = () => {
  getLoansInfo().then(res => {
    resetData(loans, res)
    loans.loansMonthList.newPush(loans.loansMonth.split(','))
    loans.serviceRateList.newPush(loans.serviceRate.split(','))
    lmChecked.value = loans.loansInitMonth
    strip.value = loans.loansInitAccount
  })
}


const homeInfo = reactive({
  "id": "1",
  "homeTitle": "123123",
  "bannerOne": "http://localhost:8082/profile/upload/2023/11/29/5ea3a159-81e9-4630-a72d-3ff2ce68b306.jpg",
  "commonSeal": null
})
const _getHomeInfo = () => {
  getHomeInfo().then(res => {
    resetData(homeInfo, res)
    bannerList.newPush({
      bannerUrl: homeInfo.bannerOne
    })
  })
}

const calLoan = reactive({
  "avgRepayment": 0,
  "firstRepayment": 0,
  "loanRate": 0,
  "totalInterest": 0,
  "totalLoanMoney": 0,
  "totalMonth": 0,
  "totalRepayment": 0,
  "loanRateDay": 0,
  defaultCoinUnit: "$"
})

const params = computed(() => {
  return {
    "totalLoanMoney": strip.value,
    "totalMonth": lmChecked.value
  }
})

watch(params, () => {
  if (params.value.totalLoanMoney && params.value.totalMonth) {
    _getCalLoan()
  }
})

const _getCalLoan = debounce(() => {
  getCalLoan(params.value).then(res => {
    resetData(calLoan, res)
  })
}, 200)


const loansUser = reactive({
  amount : "48000",
  phone : "153****0552",
  time : "2023/11/27",
  defaultCoinUnit : "$"
})

const timer = ref(0)
const _getLoansUser = () => {
  getLoansUser().then(res => {
    resetData(loansUser, res)
  })
  timer.value = setInterval(() => {
    getLoansUser().then(res => {
      resetData(loansUser, res)
    })
  }, 30000);
}

const userInfo = reactive({
  cardFlag: false,
  infoFlag: false,
  bankFlag: false
})
const _getUserInfo = () => {
  getUserInfo().then(res => {
    resetData(userInfo, res)
  })
}

const _getSts = () => {
  getOssPolicyInfo().then(res => {
    console.log('res', res)
  })

}
onMounted(() => {
  _getLoansInfo()
  _getHomeInfo()
  _getLoansUser()
  _getUserInfo()
  _getSts()
})
onUnmounted(() => {
  clearInterval(timer.value);
})
</script>

<style lang="scss" scoped>
.product {
  &-title {
    font-weight: bold;
    font-size: 40px;
    padding: 0 0 20px 0;
  }

  &-content {
    background: url("../../../assets/images/home/detail_bg.png") no-repeat;
    background-size: 100% 100%;
    color: #a2a2a2;
    padding: 30px;

    &-label {
      display: flex;
      justify-content: space-between;
      padding: 7px 0;

      span {
        color: #F9BF3A
      }
    }
  }
}

.apply {
  background: url("../../../assets/images/home/apply_bg.png") no-repeat;
  background-size: 100% 100%;
  padding: 30px;
  margin: 30px 0 15px;
  &-title {
    text-align: center;
    font-weight: bold;
    font-size: 34px;
    &:before {
      content: "";
      display: inline-block;
      width: 120px;
      height: 1px;
      margin-right: 20px;
      margin-bottom: 12px;
      background-image: -webkit-gradient(linear, left top, right top, from(#fbde60), to(#e46f00));
      background-image: linear-gradient(to right, #fbde60, #e46f00);
    }
    &:after {
      content: "";
      display: inline-block;
      width: 120px;
      height: 1px;
      margin-left: 20px;
      margin-bottom: 12px;
      background-image: linear-gradient(to right, #e46f00, #fbde60);
    }
  }

  &-money {
    font-size: 80px;
    text-align: center;
    color: #5c2d00;
    font-weight: bold;
  }

  &-strip-box{
    margin-bottom: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .reduce {
      background: url("../../../assets/images/home/strip-reduce.png") no-repeat;
      background-size: 100% 100%;
      width: 40px;
      height: 40px;
      margin-right: 40px;
    }

    .add {
      background: url("../../../assets/images/home/strip-add.png") no-repeat;
      background-size: 100% 100%;
      width: 40px;
      height: 40px;
      margin-left: 40px;
    }

    .slider {
      flex: 1;
    }

    .custom-button {
      background: url("../../../assets/images/home/strip-block.png") no-repeat;
      background-size: 100% 100%;
      height: 58px;
      width: 43px;
    }
  }

  &-jkqx {
    margin-bottom: 40px;
    &-title {
      font-size: 28px;
      font-weight: 600;
      color: #141414;
      margin-bottom: 20px;
    }
    &-item-box {
      display: flex;
      flex-wrap: wrap;

      .apply-jkqx-item{
        border-radius: 40px;
        text-align: center;
        background: #fffbba;
        padding: 4px 16px;
        color: #BC7C1C;
        margin-right: 10px;
        margin-bottom: 10px;
      }
      .checked {
        background-image: linear-gradient(to bottom, #f3654d, #f9ad7d);
        color: #fff;
      }
    }

  }
  &-mqhk {
    margin-top: 40px;

    display: flex;
    justify-content: space-between;
    align-items: end;
    font-size: 28px;

    div:nth-child(1) {
      font-size: 25px;
      font-weight: 600;
      color: #141414;
    }
    div:nth-child(2) {
      color: #b25700;
    }

    div:last-child {
      color: #fff;
      font-size: 24px;
    }
  }
}

.notice {
  background-image: linear-gradient(to right, #fae1cf, #fcfaf8);
  padding: 8px 20px;
  margin: 0 30px;
  border-radius: 40px;
  font-size: 24px;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.xieyi {
  padding: 30px 35px;
  font-size: 24px;
}
</style>
