<template>
  <div class="wallet-page">
    <div class="wallet-list flex-between">
      <div class="gradient flex-center-between li" v-for="(item, index) in 2" :key="index">
        <div class="wallet-list-li-left">
          <div class="">{{ index == 0 ? $t('common.mibi') : $t('common.baomibi') }} {{ $t('personalCenter.yue') }}</div>
          <div class="">{{ index == 0 ? appStore?.userInfo?.pointsBalance || 0 || 0 : appStore?.userInfo?.baoMiBalance
            || 0 }}</div>
        </div>
        <div class="wallet-list-li-right flex-align-center">
          <div @click="show = true" class="flex-align-center btn" v-if="index == 1">
            <img src="/src/assets/imgs/my/tixian@2x.png" alt="">
            <div class="">{{ $t('personalCenter.shenqingtixian') }}</div>
          </div>
          <div @click="changeTransformation(index)" class="flex-align-center btn">
            <img src="/src/assets/imgs/my/zhuanhuan@2x.png" alt="">
            <div class="">{{ index == 0 ? $t('personalCenter.zhuanhuanbaomibi') : $t('personalCenter.zhuanghuanmibi') }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-tabs v-model="form.changeType" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane :label="$t(tab.label)" v-for="tab in tabs" :key="tab.name" :name="tab.name">
        <div class="tabs flex-align-center" v-if="form.changeType != 3">
          <div @click="changeType(index)" :class="{ active: index + 1 == form.balanceType }" class="tab"
            v-for="(item, index) in 2">{{
              index == 0 ? $t('common.mibi') : $t('common.baomibi') }}{{ $t('personalCenter.details') }}
          </div>
        </div>
        <template v-if="form.changeType == 3">
          <div class="wallet-page-list">
            <div class="lis" v-for="(item, index) in list" :key="index">
              <div class="flex-center-between">
                <el-tag
                  :type="item.applyStatus == 0 ? 'primary' : item.applyStatus == 1 ? 'success' : item.applyStatus == 2 ? 'danger' : ''">{{
                    item.applyStatus == 0 ? $t('personalCenter.daishenhe') : item.applyStatus == 1 ?
                      $t('personalCenter.yitongguo') : $t('personalCenter.weitongguo') }}</el-tag>

                <div class="price">￥{{ item.applyAmount }}</div>
              </div>

              <div class="flex-center-between">
                <div class="">{{ $t('personalCenter.dingdanhao') }}:{{ item.applyNo }}</div>
                <div class="">{{ $t('personalCenter.shouxufei') }}:{{ item.feeAmount }}</div>
              </div>
              <div class="flex-center-between">
                <div class="">{{ $t('personalCenter.tixianfangshi') }}:{{ item.settleType == 'alipay' ?
                  $t('personalCenter.zhifubao') : item.settleType == 'wechat' ? '微信' : $t('personalCenter.yinhangka')
                  }}</div>
                <div class="">{{ $t('personalCenter.tixianzhanghao') }}:{{ item.receiveAccount }}</div>
              </div>
              <div class="flex-center-between">
                <div class="">{{ $t('personalCenter.shenqingshijian') }}:{{ item.createTime }}</div>

                <el-text v-if="item.applyStatus == 2" class="mx-1" type="danger">{{ $t('personalCenter.jujueliyou')
                  }}:{{ item.auditRemark }}</el-text>
              </div>

            </div>
          </div>
        </template>
        <template v-else>
          <div class="wallet-page-list" v-if="list?.length">
            <div v-for="(item, index) in list" :key="index" class="li">
              <div class="title">
                <div class="">{{ item.bizTypeName }}</div>
                <div class="">{{ item.createTime }}</div>
              </div>
              <div class="price" :class="{ green: form.changeType == 1 }">{{ form.changeType == 1 ? '+' : '' }}{{
                item.balanceChange }}</div>
            </div>
          </div>
        </template>

      </el-tab-pane>
    </el-tabs>
    <template v-if="list?.length">
      <Pagination :total="form.total" :page-size="form.pageSize" :current-page="form.pageNum"
        @page-change="handlePageChange" />
    </template>
    <el-empty v-else :description="$t('common.empty')" />

    <el-dialog v-model="dialogVisible"
      :title="`${transformationIndex == 0 ? $t('personalCenter.zhuanhuanbaomibi') : $t('personalCenter.zhuanghuanmibi')}`"
      width="523">
      <el-form :model="walletForm" label-width="auto" label-position="top" :rules="rules" ref="ruleFormRefs">
        <el-row>
          <el-col :span="24">
            <div class="input">
              <el-form-item :label="$t('common.use') + $t('common.baomibi')" v-if="transformationIndex" prop="orderAmt">
                <el-input-number v-model="walletForm.orderAmt" :min="1" :max="appStore?.userInfo?.baoMiBalance || 1"
                  controls-position="right" size="large" @change="handleChange" style="width: 100%;"
                  :placeholder="$t('common.placeholderInput')" align="left" :input-style="{ fontSize: '28px' }"
                  class="inputStyle" step-strictly />
              </el-form-item>

              <el-form-item :label="$t('common.use') + $t('common.mibi')" v-else prop="orderAmt">
                <el-input-number v-model="walletForm.orderAmt" :min="1"
                  :max="appStore?.userInfo?.pointsBalance || 1" :step="Number(configTxt.configValue)"
                  controls-position="right" size="large" @change="handleChange" style="width: 100%;"
                  :placeholder="$t('common.placeholderInput')" align="left" :input-style="{ fontSize: '28px' }"
                  class="inputStyle" step-strictly />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <div class="line">
          <img src="/src/assets/imgs/my/arrow-left-right-fill@2x.png" alt="">
        </div>
        <el-row>
          <el-col :span="24">
            <div class="input">
              <el-form-item v-if="transformationIndex"
                :label="$t('common.available') + $t('common.mibi') + `(${$t('personalCenter.shouxufeilv')}: ${walletForm.feeRate * 100}%)`">
                <el-input v-model="walletForm.targetAmount" :placeholder="$t('common.placeholderInput')" readonly
                  disabled :input-style="{ fontSize: '28px' }" class="inputStyle" />
              </el-form-item>
              <el-form-item v-else :label="$t('common.available') + $t('common.baomibi')">
                <el-input v-model="walletForm.targetAmount" :placeholder="$t('common.placeholderInput')" readonly
                  disabled :input-style="{ fontSize: '28px' }" class="inputStyle" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <div class="" style="font-size: 14px;margin-top: 16px;"> <text style="color: #E43434;">*</text> {{
          configTxt.configName }}{{ configTxt.configValue }}</div>
        <el-form-item prop="checked">
          <el-checkbox v-model="walletForm.checked">
            <template #default>
              <div class="">{{ $t('personalCenter.qydbty') }} <span @click.stop.prevent="changeShow('currency_conversion_protoco')" style="color: #2D71FF;font-weight: bold;">《{{  $t('personalCenter.zhxy') }}》</span> </div>
            </template>
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button @click="dialogVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button class="gradient" type="primary" @click="confirmTransformation(ruleFormRefs)">
            {{ $t('common.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="show" :title="$t('personalCenter.shenqingtixian')" width="500">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('personalCenter.txje')" prop="applyAmount">
              <el-input type="number" :min="1" :max="appStore?.userInfo?.baoMiBalance" v-model="ruleForm.applyAmount"
                :placeholder="$t('personalCenter.qsrtxje')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('personalCenter.txfs')" prop="settleType">

              <el-select v-model="ruleForm.settleType" :placeholder="$t('personalCenter.qxztxfs')" style="width: 100%">
                <el-option :label="$t('personalCenter.zhifubao')" value="alipay" />
                <el-option :label="$t('personalCenter.yinhangka')" value="bank_card" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('personalCenter.xm')" prop="withdrawPerson">
              <el-input v-model="ruleForm.withdrawPerson" :placeholder="$t('personalCenter.qsrxm')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('personalCenter.txzh')" prop="receiveAccount">
              <el-input v-model="ruleForm.receiveAccount" :placeholder="$t('personalCenter.qsrtxzh')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="checked1">
          <el-checkbox v-model="ruleForm.checked1">
            <template #default>
              <div class="">{{ $t('personalCenter.qydbty') }} <span @click.stop.prevent="changeShow('withdrawal_agreement')" style="color: #2D71FF;font-weight: bold;">《{{  $t('personalCenter.txxy') }}》</span> </div>
            </template>
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button @click="show = false">{{ $t('common.cancel') }}</el-button>
          <el-button class="gradient" type="primary" @click="submitForm(ruleFormRef)">{{
            $t('common.confirm') }}</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showWithdraw" :title="agreementTitle" width="50%">
      <div class="" style="height: 500px;overflow-y: scroll;" v-html="agreementContent"></div>
      <template #footer> 
        <div class="dialog-footer flex-center">
           <el-button class="gradient" type="primary" @click="confirmAgreement">{{
            $t('common.confirm') }}</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'

import type { TabsPaneContext } from 'element-plus'

import Pagination from '@/components/Pagination.vue'

import { getUserInfo } from '@/api/auth'

import { payConfigDearch, calRate } from '@/api/order'

import { recordList, applyWithdraw, withdrawList } from '@/api/my'

import { getAgreementType } from '@/api/common.js'

import { createOrder } from '@/api/order.js'

import { useAppStore } from '@/pinia/appStore'

import DGTMessage from '@/utils/message'

import { useI18n } from 'vue-i18n'
import { el } from 'element-plus/es/locale'

const { t } = useI18n()

const appStore = useAppStore();

const tabs = ref([
  { label: 'personalCenter.incomeDetails', name: 1 },
  { label: 'personalCenter.usageRecord', name: 2 },
  { label: 'personalCenter.withdrawHistory', name: 3 },
])
const list = ref([])

const form = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  balanceType: 1,//1-米币 2-暴米币
  changeType: 1,//1-增加 2-减少
  orderByColumn: 'create_time',
  isAsc: 'desc'
})

const walletForm = ref({
  payMethod: '',
  orderType: '',
  productId: '',
  orderNum: null,
  orderAmt: 1,
  feeRate: 0,
  targetAmount: 0,
  checked: false
})

const ruleFormRef = ref()

const configTxt = ref({})

const userInfo = ref({})//用户信息

const dialogVisible = ref(false);

const transformationIndex = ref(0);

const show = ref(false);

const ruleForm = ref({
  applyAmount: null,
  settleType: "alipay",
  withdrawPerson: "",
  receiveAccount: "",
  checked1: false
})

const ruleFormRefs = ref()

const showWithdraw = ref(false);
const agreementContent = ref('');
const agreementTitle = ref('');

const confirmAgreement = () => {
  if (['转换协议','Conversion Agreement'].includes(agreementTitle.value)) {
    console.log('111')
   walletForm.value.checked = true;
  } else {
    ruleForm.value.checked1 = true;
  }
  showWithdraw.value = false;
  
}
// 获取协议
const changeShow = async (type) => {

  agreementTitle.value = t(type == 'withdrawal_agreement' ? 'personalCenter.txxy' : 'personalCenter.zhxy');
  let res = await getAgreementType({ agreementType: type });
  if (res.code === 200) {
    showWithdraw.value = true;
    agreementContent.value = res.data.content || '';
  }
}

const validatePass = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error(t('common.placeholderInput')))
  } else if (Number(value) % Number(configTxt.value.configValue) !== 0 && transformationIndex.value == 0) {
    callback(new Error(`米币数量必须为${configTxt.value.configValue}的整倍数`))
  } else {
    callback()
  }
}

const validatePass1 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error(t('common.placeholderInput')))
    return
  } else if (Number(value) > appStore.userInfo.baoMiBalance) {
    callback(new Error(`余额不足`))
  } else {
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error(t('personalCenter.qydbtyzhxy')))
    return
  } else {
    callback()
  }
}
const validatePass3 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error(t('personalCenter.qydbtytxxy')))
    return
  } else {
    callback()
  }
}
const rules = ref({
  applyAmount: [
    { required: true, validator: validatePass1, trigger: 'blur' }
  ],
  settleType: [
    { required: true, message: t('common.qingxuanze'), trigger: 'blur' }
  ],
  withdrawPerson: [
    { required: true, message: t('common.placeholderInput'), trigger: 'blur' }
  ],
  receiveAccount: [
    { required: true, message: t('common.placeholderInput'), trigger: 'blur' }
  ],
  orderAmt: [
    { required: true, trigger: 'blur', validator: validatePass },
  ],
  checked: [{
    required: true,
   validator:validatePass2,
    trigger: 'blur',
  }],
  checked1: [{
    required: true,
   validator:validatePass3,
    trigger: 'blur',
  }]
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = await applyWithdraw(ruleForm.value);
      if (res.code === 200) {
        show.value = false;
        appStore.USERINFO();
        getList()
        ruleForm.value.applyAmount = null;
        DGTMessage.success(t('personalCenter.txsqytj'));
      }
    }
  })
}

// 确认转换
const confirmTransformation = async (formEl) => {
 
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = await createOrder({
        payMethod: walletForm.value.payMethod,
        orderType: walletForm.value.orderType,
        productId: '',
        orderNum: walletForm.value.targetAmount,
        orderAmt: walletForm.value.orderAmt
      })
      if (res.code === 200) {
        if (res.data.paySuccess) {
          dialogVisible.value = false;
          appStore.USERINFO();
          DGTMessage.success(`${transformationIndex.value ? t('personalCenter.zhuanhuanbaomibi') : t('personalCenter.zhuanghuanmibi')}${t('common.success')}`)
        }
      }
    }
  })


}

// 米币暴米币转换
const changeTransformation = async (index: any) => {
  

  transformationIndex.value = index;
  walletForm.value.payMethod = index ? 'BMI' : 'MI';
  walletForm.value.orderType = index ? 'exchange_mi' : 'exchange_bmi';
  let { data } = await payConfigDearch({ id: '03' });

  let result = data.filter((item: any) => item.configCode == 'bmb_to_mb_rate')
  if (result.length) {
    configTxt.value = result[0]
  }
  walletForm.value.orderAmt = index == 0 ? Number(configTxt.value.configValue) : 1
  if(index==0 && appStore?.userInfo?.pointsBalance <= 0){
    DGTMessage.warning(`${t('common.balanceNotEnough')}${t('common.baomibi')}`);
    return;
  }else if(index==1 && appStore?.userInfo?.baoMiBalance <= 0){
    DGTMessage.warning(`${t('common.balanceNotEnough')}${t('common.mibi')}`);
    return;
  }
  handleChange()
  dialogVisible.value = true;
}

const handleChange = async () => {
  if (walletForm.value.orderAmt) {
    if (transformationIndex.value == 0 && Number(walletForm.value.orderAmt) % Number(configTxt.value.configValue) !== 0) return
    let res = await calRate({
      orderType: walletForm.value.orderType,
      orderNum: walletForm.value.orderAmt
    });
    if (res.code === 200) {
      walletForm.value.feeRate = res.data.feeRate
      walletForm.value.targetAmount = res.data.targetAmount
    }
  }

}
// 米币暴米币切换
const changeType = (index) => {
  form.value.pageNum = 1;
  form.value.balanceType = index + 1;
  getList()
}

const handleClick = (tab: TabsPaneContext) => {
  form.value.pageNum = 1;
  form.value.changeType = tab.props.name;
  getList()
}
const getList = async () => {
  let api = form.value.changeType == 3 ? withdrawList(form.value) : recordList(form.value)
  let res = await api;
  list.value = res.rows;
  form.value.total = res.total;
}

const handlePageChange = (newPage: number, pageSize?: number) => {
  // list.value = []
  form.value.pageNum = newPage;
  if(pageSize)form.value.pageSize = pageSize;
  getList()
}
// 获取用户信息
const getInfo = async () => {
  let res = await getUserInfo();
  userInfo.value = res.user;
}

onMounted(() => {
  getInfo()
  getList()
})
</script>
<style scoped lang="scss">
.wallet-page {

  padding-bottom: 16px;

  .tabs {
    margin-bottom: 16px;

    .tab {
      cursor: pointer;
      color: #2D71FF;
      padding: 0 12px;
      line-height: 30px;
      font-size: 14px;
      background: #EAF0FF;
      border-radius: 4px;
      margin-right: 16px;
    }

    .active {
      color: #FFFFFF;
      background: linear-gradient(90deg, #0055FE 0%, #C832FA 100%);
    }
  }

  .wallet-list {
    gap: 16px;
    padding: 16px;

    .li {
      flex: 1;
      padding: 16px;
      border-radius: 16px;

      .wallet-list-li-left {

        div {
          color: #FFFFFF;
          font-size: 14px;
          line-height: 1;

          &:last-child {
            margin-top: 8px;
            font-size: 32px;
            font-weight: bold;
          }
        }
      }

      .wallet-list-li-right {
        .btn {
          cursor: pointer;
          margin-left: 8px;
          color: #2D71FF;
          font-size: 14px;
          padding: 0 20px;
          height: 40px;
          background: #FFFFFF;
          border-radius: 10px;

          img {
            width: 16px;
            height: 16px;
            margin-right: 4px;
          }

          &:hover {
            opacity: 0.7;
          }
        }
      }
    }
  }
}

.wallet-page-list {

  .li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    border-radius: 16px;
    background: #F5F7FA;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .title {
      div {
        font-size: 16px;
        line-height: 1;

        &:last-child {
          margin-top: 8px;
          color: #666666;
          font-size: 14px;
        }
      }
    }


  }

  .price {
    font-size: 16px;
    font-weight: bold;
    color: #F52929;
  }

  .green {
    color: #1FB362;
  }

  .lis {
    padding: 16px;
    border-radius: 16px;
    background: #F5F7FA;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.input {
  padding: 16px;
  background: #F5F7FA;
  border-radius: 16px;
}

.line {
  height: 16px;
  position: relative;

  img {
    top: 50%;
    width: 40px;
    height: 40px;
    left: 50%;
    z-index: 9;
    transform: translate(-50%, -50%);
    position: absolute;
  }
}

.inputStyle {

  :deep(.el-input__wrapper) {
    background-color: transparent;
    box-shadow: none !important;
    padding: 0;
  }

  :deep(.el-input__inner) {
    font-size: 28px;
  }

  :deep(.el-input-number__increase),
  :deep(.el-input-number__decrease) {
    display: none;
  }
}
</style>