<template>
    <view class="user-form crm-form">
      <view class="card">
        <view class="bank-menu card-header">
          <view v-for="item in types" :key="item.key" class="bank-menu-item"
                :class="{ active: selectedType === item.key }" @click="selectedType = item.key">
            <!--                        <image class="bank-icon" :src="item.icon" mode="widthFix" />-->
            <text>{{ item.label }}</text>
          </view>
        </view>
        <uni-row class="demo-uni-row uni-row1" :gutter="20">
          <uni-col v-show="selectedType == 1" :xs="{span:24,offset:0}" :sm="{span:24,offset:0}" :md="{span:24,offset:0}" :lg="{span:12,offset:6}" :xl="{span:12,offset:6}" >
            <view class=" p-3">
              <view class="content-title">
                <view v-t="'PersonalManagement.Title.CustomerZonePasswordChange'"></view>
              </view>
              <hr>
              <uni-forms :model="passwordInfo" labelWidth="200" label-position="top">
                <uni-row class="demo-uni-row">
                  <uni-col :xs="24">
                    <uni-forms-item :label="t('PersonalManagement.Label.OldPassword')">
                      <uni-easyinput :clearable="false" v-model="passwordInfo.oldPassword"
                                     :placeholder="locale == 'es' ? 'Introduzca el nombre de la red' : t('placeholder.input')" />
                    </uni-forms-item>
                  </uni-col>
                  <uni-col :xs="24">
                    <uni-forms-item :label="t('PersonalManagement.Label.NewPassword')">
                      <uni-easyinput :clearable="false" v-model="passwordInfo.newPassword"
                                     :placeholder="locale == 'es' ? 'Introduzca nueva contraseña' : t('placeholder.input')" />
                    </uni-forms-item>
                  </uni-col>
                  <uni-col :xs="24">
                    <uni-forms-item :label="t('PersonalManagement.Label.NewPasswordConfirmation')">
                      <uni-easyinput :clearable="false" v-model="passwordInfo.checkPass"
                                     :placeholder="locale == 'es' ? 'Introduzca nueva contraseña' : t('placeholder.input')" />
                    </uni-forms-item>
                  </uni-col>
                  <uni-col :xs="24">
                    <view class="notice-list">
                      <view v-for="(item, index) in noticeItems" :key="index"
                            :class="['notice-item', item.valid ? 'isOK' : '']">
                        {{ item.label }}
                      </view>
                    </view>
                  </uni-col>
                  <uni-col :xs="24">
                    <button  type="button" class="btn btn-danger btn-shadow waves-effect mt-4" @click="passwordUpdate">
                    {{ locale == 'es' ?
                      'Actualizarcontraseña' : t('Btn.Application') }}
                    </button>
                  </uni-col>
                </uni-row>
              </uni-forms>
            </view>
          </uni-col>
          <uni-col v-show="selectedType == 2" :xs="{span:24,offset:0}" :sm="{span:{span:24,offset:0},offset:0}" :md="{span:24,offset:0}" :lg="{span:12,offset:6}" :xl="{span:12,offset:6}" >
            <view class=" p-3">
              <view class="content-title">
                <view v-t="'PersonalManagement.Title.EmailChange'"></view>
              </view>
              <hr>
              <uni-forms :model="emailInfo" labelWidth="200" label-position="top">
                <uni-row class="demo-uni-row">
                  <uni-col :xs="24">
                    <uni-forms-item :label="t('PersonalManagement.Label.OldEmail')">
                      <uni-easyinput :clearable="false" v-model="emailInfo.oldEmail"
                                     :placeholder="t('placeholder.input')" />
                    </uni-forms-item>
                  </uni-col>
                  <uni-col :xs="24">
                    <uni-forms-item :label="t('PersonalManagement.Label.NewEmail')">
                      <uni-easyinput :clearable="false" v-model="emailInfo.email"
                                     :placeholder="t('placeholder.input')" />
                    </uni-forms-item>
                  </uni-col>
                  <uni-col :xs="24">
                    <view class="email-code">
                      <uni-forms-item :label="t('PersonalManagement.Label.MailboxVerificationCode')"
                                      class="email-code-item">
                        <uni-easyinput :clearable="false" v-model="emailInfo.emailCode"
                                       :placeholder="locale == 'es' ? 'Código de 6 dígitos' : t('placeholder.input')" />
                      </uni-forms-item>
                      <view class="btn btn-code" @click="handleGetCode">{{ getCodeString }}</view>
                    </view>
                  </uni-col>
                  <uni-col :xs="24">
                    <button  type="button" class="btn btn-danger btn-shadow waves-effect mt-4" @click="emailUpdate">
                      {{ locale == 'es' ?
                      'Actualizarcontraseña' : t('Btn.Application') }}
                    </button>
                  </uni-col>
                </uni-row>
              </uni-forms>
            </view>
          </uni-col>
        </uni-row>
      </view>


    </view>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { showToast } from "@/utils/toast";
import { personalApi } from '@/service/personal';
import { useEmailCountdown } from '@/hooks/useEmailCountdown';
import config from '@/config';
const {
    time,
    text: getCodeString,
    canSend,
    start,
    restore,
    clear,
} = useEmailCountdown()
const { t, locale } = useI18n();
interface BankListType {
    key: string;
    label: string;
    icon: string;
}
const passwordInfo = ref({
    oldPassword: '',
    newPassword: '',
    checkPass: ''
});
const emailInfo = ref({
    email: '',
});
const selectedType = ref('1')
const types = computed(() => {
  return [
      { key: '1', label: t('PersonalManagement.Title.CustomerZonePasswordChange') },
      {
        key: '2',
        label: t('PersonalManagement.Title.EmailChange'),
      },
  ]
})
const rule1 = computed(() => {
    if (!passwordInfo.value.newPassword) {
        return false;
    }
    return /^.{8,16}$/.test(passwordInfo.value.newPassword);
});
const rule2 = computed(() => {
    return /^(?=.*?[a-z])(?=.*?[A-Z]).*$/.test(passwordInfo.value.newPassword);
});
const rule3 = computed(() => {
    return /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?!.*([~!@&%$^\\(\\)#_]).*\\1.*\\1)[A-Za-z0-9~!@&%$^\\(\\)#_]{8,16}$/.test(
        passwordInfo.value.newPassword
    );
});
const rule4 = computed(() => {
    console.log(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@&%$^*./\\(\\)\\+\\=#_-])[A-Za-z0-9~!@&%$^*./\\(\\)\\+\\=#_-]{8,16}$/.test(passwordInfo.value.newPassword))
    return /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@&%$^*./\\(\\)\\+\\=#_-])[A-Za-z0-9~!@&%$^*./\\(\\)\\+\\=#_-]{8,16}$/.test(
        passwordInfo.value.newPassword
    );
});
const noticeItems = computed(() => [
    { label: t('signup.form.rules.1st'), valid: rule1.value },
    { label: t('signup.form.rules.2nd'), valid: rule2.value },
    { label: t('signup.form.rules.4rd'), valid: rule4.value }
])
// 发送邮箱验证码
async function sendEmailCode() {
    try {
        const res = await personalApi.customUpdateEmailCode({
            email: emailInfo.value.email,
            oldEmail: emailInfo.value.oldEmail,
        });
        if (res.code === 200) {
            start()
            return true;
        } else {
            showToast(t("Msg.CodeFail"));
            return false;
        }
    } catch (error: any) {
        console.log(error, 12);

        showToast(t("Msg.CodeFail"));
        return false;
    }
}
async function handleGetCode() {
    if (!emailInfo.value.email) {
        showToast(t("vaildate.email.empty"));
        return;
    }
    if (!config.Pattern.Email.test(emailInfo.value.email)) {
        showToast(t("vaildate.email.format"));
        return;
    }

    if (!canSend.value) return
    await sendEmailCode();
}
// 提交修改邮箱
async function emailUpdate() {
    try {
        const res = await personalApi.customUpdateEmail({
            ...emailInfo.value
        });
        if (res.code === 200) {
            clear()
            emailInfo.value = {}
            showToast(t("Msg.Success"));
        } else {
            showToast(res.msg);
        }
    } catch (error: any) {
        showToast(error.msg);
    }
}
// 提交修改密码
async function passwordUpdate() {
    try {
        if (!rule1.value) {
            showToast(t("signup.form.rules.1st"));
            return;
        }
        if (!rule2.value) {
            showToast(t("signup.form.rules.2nd"));
            return;
        }
        if (!rule4.value) {
            showToast(t("signup.form.rules.4rd"));
            return;
        }
        if (passwordInfo.value.newPassword !== passwordInfo.value.checkPass) {
            showToast(t("vaildate.password.same"));
            return;
        }
        const res = await personalApi.customUpdatePassword({
            ...passwordInfo.value
        });
        if (res.code === 200) {
            // start()
            showToast(t("Msg.Success"));
        } else {
            showToast(res.msg);
        }
    } catch (error: any) {
        showToast(error.msg);
    }
}
onMounted(() => {
    restore()
})


</script>



<style scoped lang="scss">
  @import "@/uni.scss";
:deep(.uni-row1) {
    .uni-col {
    }

    .uni-forms-item {
        min-height: px2rpx(79);
        margin-bottom: px2rpx(10);
    }

    .uni-easyinput__content {
        //border: none !important;
        background-color: transparent;
        //background-color: var(--color-zinc-100) !important;
    }
}

.btn {
    width: 100%;
}

.notice-list {
    margin: 0;
    padding: 0 px2rpx(12) px2rpx(12) 0;

    .notice-item {
        font-size: px2rpx(14);
        color: var(--bs-emphasis-color);
        line-height: px2rpx(24);
    }

    .isOK {
        color: var(--bs-success);
    }
}

.email-code {
    display: flex;
    align-items: flex-end;

    :deep(.email-code-item) {
        flex: 1;
      .uni-easyinput__content{
        border-radius: px2rpx(6) 0 0 px2rpx(6);
      }
    }

    .btn-code {
      width: 30%;
        margin-bottom: px2rpx(10);
        //padding: px2rpx(10) px2rpx(16);
      padding: 0;
        background-color: #102047;
        color: #fff;
      height: 3rem;
      box-sizing: border-box;
      line-height: 3rem;
      text-align: center;
      border-radius: 0 px2rpx(6) px2rpx(6) 0;
      cursor: pointer;
      font-size: px2rpx(16);
      flex-shrink: 0;
    }

}
  .bank-menu {
    background: #fff;
    overflow: hidden;

    .bank-menu-item {
      display: flex;
      align-items: center;
      gap: px2rpx(12);
      padding: px2rpx(10) px2rpx(16);
      cursor: pointer;
      border: 1px solid #f3f4f6;
      font-size: px2rpx(16);
      font-weight: 500;
      color: #1f2937;
      transition: all 0.3s;
      height: px2rpx(50);
      border-radius: px2rpx(8);
      margin-bottom: px2rpx(8);

      .bank-icon {
        width: px2rpx(50);
      }

      &.active {
        background: #ea2027;
        color: var(--bs-emphasis-color);
        border-radius: px2rpx(0);
      }

      &:hover {
        background: #f9fafb;
      }

      &.active:hover {
        background: #d11920;
      }
    }
  }
  .bank-menu {
    // background: #fff;
    display: flex;
    flex-wrap: wrap;
    overflow: hidden;

    &.card-header {
      padding: px2rpx(10) px2rpx(20);
    }

    .bank-menu-item {
      flex: 1;
      min-width: px2rpx(260);
      display: flex;
      align-items: center;
      justify-content: center;
      //gap: px2rpx(12);
      padding: 0 px2rpx(16);
      cursor: pointer;
      font-size: px2rpx(16);
      font-weight: bold;
      color: var(--bs-emphasis-color);
      transition: all 0.3s;
      height: px2rpx(36);
      border-radius: px2rpx(8);

      .bank-icon {
        width: px2rpx(50);
      }

      &.active {
        background: #f5f5f5;
        color: #000;
        border-radius: px2rpx(8);

        &:hover {
          background: var(--bs-link-hover-color-rgb);
          color: #333;
        }
      }

      &:hover {
        background: #f5f5f5;
        color: #333;
      }

      &.active:hover {
        background: #f5f5f5;
      }
    }
  }
</style>