<template>
  <div class="register-container">
    <!-- 系统头部 -->
    <s-header :name="$t('register.header')" :noback="false" />

    <!-- 主要内容区域 -->
    <div class="register-content">
      <!-- 注册表单 -->
      <van-form @submit="registerSubmit" class="register-form">
        <!-- 账号信息 -->
        <div class="form-section">
          <!-- 用户名 -->
          <van-field
            v-model="username"
            name="username"
            :placeholder="$t('register.usernamePlaceholder')"
            :rules="[
              {
                pattern: /^[a-zA-Z][a-zA-Z0-9]*$/,
                message: $t('register.usernameRequired'),
              },
            ]"
            class="form-field"
          >
            <template #left-icon>
              <van-icon name="user" size="18" />
            </template>
          </van-field>

          <!-- 姓名 -->
          <van-field
            v-model="name"
            name="name"
            :placeholder="$t('register.namePlaceholder')"
            :rules="[{ required: true, message: $t('register.nameRequired') }]"
            class="form-field"
          >
            <template #left-icon>
              <van-icon name="star" size="18" />
            </template>
          </van-field>
        </div>

        <!-- 密码设置 -->
        <div class="form-section">
          <!-- 密码 -->
          <van-field
            v-model="password"
            name="password"
            type="password"
            :placeholder="$t('register.passwordPlaceholder')"
            :rules="[
              { required: true, message: $t('register.passwordRequired') },
              {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d).{10,}$/,
                message: $t('register.passwordPattern'),
              },
            ]"
            class="form-field"
          >
            <template #left-icon>
              <van-icon name="lock" size="18" />
            </template>
          </van-field>

          <!-- 确认密码 -->
          <van-field
            v-model="passwordCheck"
            name="passwordCheck"
            type="password"
            :placeholder="$t('register.passwordCheckPlaceholder')"
            :rules="[
              { required: true, message: $t('register.passwordCheckRequired') },
            ]"
            class="form-field"
          >
            <template #left-icon>
              <van-icon name="lock" size="18" />
            </template>
          </van-field>
        </div>

        <!-- 地区选择 -->
        <div class="form-section">
          <!-- 国家或地区 -->
          <div class="radio-group">
            <van-radio-group v-model="ifForeign" direction="horizontal">
              <van-radio name="0" icon-size="20" checked-color="@theme-color">
                <div class="radio-option">
                  <!-- <img
                    src="@/assets/china-flag.png"
                    class="flag-icon"
                    alt="中国"
                  /> -->
                  <span>{{ $t("register.chinese") }}</span>
                </div>
              </van-radio>

              <van-radio name="1" icon-size="20" checked-color="@theme-color">
                <div class="radio-option">
                  <!-- <img
                    src="@/assets/world-flag.png"
                    class="flag-icon"
                    alt="其他"
                  /> -->
                  <span>{{ $t("register.other") }}</span>
                </div>
              </van-radio>
            </van-radio-group>
          </div>

          <!-- 区域选择 -->
          <van-field
            v-if="ifForeign === '0'"
            v-model="areaValue"
            readonly
            name="picker"
            :placeholder="$t('register.areaPlaceholder')"
            :rules="[{ required: true, message: $t('register.areaRequired') }]"
            class="form-field"
            @click="showArea = true"
          >
            <template #left-icon>
              <van-icon name="location" size="18" />
            </template>
          </van-field>

          <van-popup v-model:show="showArea" position="bottom">
            <van-cascader
              :title="$t('register.areaRequired')"
              :options="areaOptions"
              @close="showArea = false"
              @finish="onConfirmArea"
            />
          </van-popup>

          <!-- 国家选择 -->
          <van-field
            v-if="ifForeign === '1'"
            v-model="cityValue"
            readonly
            name="picker"
            :placeholder="$t('register.clickCountryCity')"
            :rules="[
              { required: true, message: $t('register.chooseCountryCity') },
            ]"
            class="form-field"
            @click="showCountry = true"
          >
            <template #left-icon>
              <van-icon name="location" size="18" />
            </template>
          </van-field>

          <van-popup v-model:show="showCountry" round position="bottom">
            <van-cascader
              :title="$t('register.chooseCountryCity')"
              :options="countryOptions"
              @close="showCountry = false"
              @finish="onConfirmCountry"
            >
              <template #options-top="{ tabIndex }">
                <van-search
                  v-if="tabIndex === 0"
                  v-model="searchValue"
                  :placeholder="$t('kSelectPop.searchKey')"
                  @update:model-value="valueChange(tabIndex)"
                  class="search-city"
                />
              </template>
            </van-cascader>
          </van-popup>
        </div>

        <!-- 联系方式 -->
        <div class="form-section">
          <!-- 中国联系方式 -->
          <template v-if="ifForeign === '0'">
            <div class="radio-group">
              <van-radio-group v-model="logonMode" direction="horizontal">
                <van-radio
                  name="10"
                  icon-size="20"
                  checked-color="@theme-color"
                >
                  <div class="radio-option">
                    <van-icon name="phone" size="20" />
                    <span>{{ $t("register.phoneRegistration") }}</span>
                  </div>
                </van-radio>

                <van-radio
                  name="11"
                  icon-size="20"
                  checked-color="@theme-color"
                >
                  <div class="radio-option">
                    <van-icon name="envelop-o" size="20" />
                    <span>{{ $t("register.emailRegistration") }}</span>
                  </div>
                </van-radio>
              </van-radio-group>
            </div>

            <!-- 手机号 -->
            <van-field
              v-if="logonMode === '10'"
              v-model="phone"
              name="phone"
              type="tel"
              :placeholder="$t('register.phonePlaceholder')"
              :rules="[
                {
                  required: true,
                  pattern: /^1[3456789]\d{9}$/,
                  message: $t('register.phoneRequired'),
                },
              ]"
              class="form-field"
            >
              <template #left-icon>
                <van-icon name="phone-o" size="18" />
              </template>
            </van-field>

            <!-- 短信验证码 -->
            <van-field
              v-if="logonMode === '10'"
              v-model="code"
              name="code"
              :placeholder="$t('register.codePlaceholder')"
              :rules="[
                { required: true, message: $t('register.codeRequired') },
              ]"
              class="form-field"
            >
              <template #left-icon>
                <van-icon name="comment" size="18" />
              </template>

              <template #button>
                <van-button
                  size="small"
                  class="code-button"
                  @click="seedVerCode()"
                  :disabled="time !== 0 || phone.length !== 11"
                  :loading="reqApi"
                  loading-text="发送中..."
                >
                  {{ time === 0 ? $t("register.seedVerCode") : `${time} s` }}
                </van-button>
              </template>
            </van-field>

            <!-- 邮箱 -->
            <van-field
              v-if="logonMode === '11'"
              v-model="email"
              name="email"
              :placeholder="$t('register.emailPlaceholder')"
              :rules="[
                { required: true, message: $t('register.emailRequired') },
                {
                  pattern:
                    // /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/,
                    /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
                  message: $t('register.emailInvalid'),
                },
              ]"
              class="form-field"
            >
              <template #left-icon>
                <van-icon name="envelop-o" size="18" />
              </template>
            </van-field>

            <!-- 邮箱验证码 -->
            <van-field
              v-if="logonMode === '11'"
              v-model="code"
              name="code"
              :placeholder="$t('register.emailCodePlaceholder')"
              :rules="[
                { required: true, message: $t('register.emailCodeRequired') },
              ]"
              class="form-field"
            >
              <template #left-icon>
                <van-icon name="comment" size="18" />
              </template>

              <template #button>
                <van-button
                  size="small"
                  class="code-button"
                  @click="seedVerCode()"
                  :disabled="time !== 0 || email.length === 0"
                  :loading="reqApi"
                  loading-text="发送中..."
                >
                  {{ time === 0 ? $t("register.seedVerCode") : `${time} s` }}
                </van-button>
              </template>
            </van-field>
          </template>

          <!-- 国外联系方式 -->
          <template v-if="ifForeign === '1'">
            <!-- 邮箱 -->
            <van-field
              v-model="email"
              name="email"
              :placeholder="$t('register.emailPlaceholder')"
              :rules="[
                { required: true, message: $t('register.emailRequired') },
                {
                  pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
                  message: $t('register.emailInvalid'),
                },
              ]"
              class="form-field"
            >
              <template #left-icon>
                <van-icon name="envelop-o" size="18" />
              </template>
            </van-field>

            <!-- 邮箱验证码 -->
            <van-field
              v-model="code"
              name="code"
              :placeholder="$t('register.emailCodePlaceholder')"
              :rules="[
                { required: true, message: $t('register.emailCodeRequired') },
              ]"
              class="form-field"
            >
              <template #left-icon>
                <van-icon name="comment" size="18" />
              </template>

              <template #button>
                <van-button
                  size="small"
                  class="code-button"
                  @click="seedVerCode()"
                  :disabled="time !== 0 || email.length === 0"
                  :loading="reqApi"
                  loading-text="发送中..."
                >
                  {{ time === 0 ? $t("register.seedVerCode") : `${time} s` }}
                </van-button>
              </template>
            </van-field>
          </template>
        </div>

        <!-- 邀请码 -->
        <div class="form-section">
          <van-field
            v-model="inviteCode"
            name="inviteCode"
            :placeholder="$t('register.invitationCodePlaceholder')"
            :rules="[
              {
                required: true,
                message: $t('register.invitationCodePlaceholder'),
              },
            ]"
            class="form-field"
          >
            <template #left-icon>
              <van-icon name="coupon-o" size="18" />
            </template>
          </van-field>
        </div>

        <!-- 注册按钮 -->
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          class="register-button"
        >
          {{ $t("register.registerButton") }}
        </van-button>
      </van-form>
    </div>
  </div>
</template>
<script>
import md5 from "js-md5";
import { ref, onMounted, reactive, toRefs, watch } from "vue";
import { showFailToast, showToast } from "vant";
import { sentRegisterCode, tAdminSave } from "@/service/register";
import sHeader from "@/components/SimpleHeader";
import logiLogoImgUrl from "@/assets/login/logo.png";
import { useRouter } from "vue-router";
import { getLocal, setLocal, styleUrl } from "@/common/js/utils";
import { useI18n } from "vue-i18n";
import { countriesData } from "@/common/js/countries";
import { countriesDataEn } from "@/common/js/countries-en";
import { useCascaderAreaData } from "@vant/area-data";

export default {
  setup() {
    // 引入语言
    const languageName = ref(getLocal("curLang"));
    const { t } = useI18n();
    const active = ref(0);
    const username = ref("");
    const name = ref("");
    const password = ref("");
    const passwordCheck = ref("");
    const ifForeign = ref("0");
    const logonMode = ref("10");
    const phone = ref("");
    const email = ref("");
    const code = ref("");
    const inviteCode = ref("");
    const verifyRef = ref(null);
    const verCodeTime = reactive({
      time: 0,
    });
    let phoneOrEmailStr = ref("");

    const router = useRouter();
    const reqApi = ref(false);
    const hostName = ref("");

    const citiesValue = ref("");
    const showCountry = ref(false);
    const cityValue = ref("");
    const countryValue = ref("");
    const countryOptions = ref(
      languageName.value == "zh" ? countriesData : countriesDataEn
    );

    const { locale } = useI18n();
    watch(locale, (newValue) => {
      if (newValue == "zh") {
        countryOptions.value = countriesData;
      } else {
        countryOptions.value = countriesDataEn;
      }
    });
    const onConfirmCountry = ({ selectedOptions }) => {
      cityValue.value = selectedOptions.map((option) => option.text).join("/");
      countryValue.value = selectedOptions[0]?.value;
      citiesValue.value = selectedOptions[1]?.value;
      showCountry.value = false;
    };

    const areaOptions = ref();
    const areaValue = ref("");
    const showArea = ref(false);
    const onConfirmArea = ({ selectedOptions }) => {
      if (selectedOptions[0]?.text == selectedOptions[1]?.text) {
        areaValue.value = selectedOptions[0]?.text;
        citiesValue.value = selectedOptions[0]?.text;
      } else {
        areaValue.value =
          selectedOptions[0]?.text + "/" + selectedOptions[1]?.text;
        citiesValue.value = selectedOptions[0]?.text + selectedOptions[1]?.text;
      }
      showArea.value = false;
    };

    // 注册点击
    const registerSubmit = async () => {
      if (password.value !== passwordCheck.value) {
        showFailToast(t("register.twoTypedDiff"));
        return false;
      }
      if (username.value === "admin") {
        showFailToast(t("register.A0201"));
        return false;
      }
      const { data } = await tAdminSave({
        username: username.value,
        name: name.value,
        password: md5(password.value),
        ifForeign: ifForeign.value,
        phoneOrEmail: phone.value || email.value,
        code: code.value,
        companyType: "0",
        inviteCode: inviteCode.value,
        country: countryValue.value,
        cities: citiesValue.value,
      });

      if (data.code === "00000") {
        showToast(t("register.registerSucess"));
        router.push({ path: "/login" });
      } else if (data.code === "R0001") {
        showFailToast(t("register.R0001"));
      } else if (data.code === "R0002") {
        showFailToast(t("register.R0002"));
      } else if (data.code === "R0003") {
        showFailToast(t("register.R0003"));
      } else if (data.code === "R0004") {
        showFailToast(t("register.R0004"));
      } else if (data.code === "R0005") {
        showFailToast(t("register.R0005"));
      } else if (data.code === "R0006") {
        showFailToast(t("register.R0006"));
      } else if (data.code === "A0201") {
        showFailToast(t("register.A0201"));
      } else if (data.code === "A0203") {
        showFailToast(t("register.A0203"));
      } else {
        showFailToast(t("register.registerFail"));
      }
    };

    // 发送验证码
    const seedVerCode = async () => {
      reqApi.value = true;

      if (ifForeign.value === "1") {
        phoneOrEmailStr = email.value;
      } else if (ifForeign.value === "0" && logonMode.value === "10") {
        phoneOrEmailStr = phone.value;
      } else {
        phoneOrEmailStr = email.value;
      }

      getCurrentDomain();

      try {
        const { data } = await sentRegisterCode({
          ifForeign: ifForeign.value,
          phoneOrEmail: phoneOrEmailStr,
          hostName: hostName.value,
        });
        reqApi.value = false;
        if (data.code === "00000") {
          showToast(data.data);
          verCodeTime.time = 1 * 60; // 1分钟定时器，60s后可以更换验证方式
          verCodeTimeInterval();
        } else if (data.code === "R0009") {
          showToast(t("register.R0009"));
        } else if (data.code === "R0008") {
          showToast(t("register.R0008"));
        } else if (data.code === "A0202") {
          showToast(t("register.A0202"));
        } else if (data.code === "A0207") {
          showToast(t("register.A0207"));
        } else if (data.code === "R0004") {
          showToast(t("register.R0004"));
        } else {
          showToast(data.message);
        }
      } catch (error) {
        reqApi.value = false;
      }
    };

    // 验证码发送成功开始1分钟倒计时
    const verCodeTimeInterval = () => {
      const intervalId = setInterval(() => {
        verCodeTime.time--;
        setLocal("registerVerCodeTime", verCodeTime.time);
        if (verCodeTime.time === 0) {
          clearInterval(intervalId); // 清除定时器
        }
      }, 1000);
    };
    // 初始化页面获取验证码倒计时
    onMounted(async () => {
      // 加载样式
      styleUrl("register");
      verCodeTime.time = getLocal("registerVerCodeTime");
      if (verCodeTime.time && verCodeTime.time !== "") {
        verCodeTime.time = parseInt(verCodeTime.time);
        if (verCodeTime.time > 0) {
          verCodeTimeInterval();
        }
      } else {
        verCodeTime.time = 0;
      }
      const areaData = useCascaderAreaData();
      areaData.forEach((province) => {
        province.children.forEach((city) => {
          // 删除城市中的区级信息
          delete city.children;
        });
      });
      // 删除台湾、澳门和香港
      const provincesToRemove = ["710000", "810000", "820000"];
      areaOptions.value = areaData.filter(
        (province) => !provincesToRemove.includes(province.value)
      );
    });

    const getCurrentDomain = () => {
      const currentDomain = window.location.href;
      switch (true) {
        case currentDomain.includes("sevencloud.com.cn"):
          hostName.value = "Sevencloud";
          break;
        case currentDomain.includes("portalmcc.com.cn"):
          hostName.value = "Portalmcc";
          break;
        default:
          hostName.value = "Sunzee";
      }
    };

    const signOptions = [
      { text: "手机注册", value: "mo" },
      { text: "邮箱注册", value: "ema" },
    ];

    // 搜索关键词
    const searchValue = ref("");
    const countryData = ref(
      languageName.value == "zh" ? countriesData : countriesDataEn
    );
    // 搜索数据
    const valueChange = (index) => {
      let tempOptions = [];
      if (searchValue.value) {
        if (index === 0) {
          // 国家
          countryData.value.forEach((item) => {
            if (item.text.includes(searchValue.value)) {
              tempOptions.push(item);
            }
          });
          countryOptions.value = tempOptions;
        }
      } else {
        countryOptions.value = countryData.value;
      }
    };

    return {
      ...toRefs(verCodeTime),
      logiLogoImgUrl,
      username,
      name,
      password,
      passwordCheck,
      ifForeign,
      phone,
      email,
      code,
      inviteCode,
      verifyRef,
      verCodeTime,
      verCodeTimeInterval,
      seedVerCode,
      registerSubmit,
      signOptions,
      signinModel: "aaabb",
      active,
      logonMode,
      reqApi,

      cityValue,
      showCountry,
      countryOptions,
      onConfirmCountry,
      showArea,
      areaOptions,
      // areaList,
      onConfirmArea,
      areaValue,

      searchValue,
      valueChange,
    };
  },
  components: { sHeader },
};
</script>
<style lang="less" scoped>
@theme-color: #4d6add;

.register-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f8ff;
  overflow-y: auto;
}

.register-content {
  flex: 1;
  padding: 20px;
  background: #f5f6fa;
  height: calc(100% - 45px);
  overflow: auto;
  overflow-x: hidden;
}

.register-form {
  background-color: #fff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 20px rgba(77, 106, 221, 0.12);
}

.form-section {
  margin-bottom: 25px;
}

.form-field {
  display: flex;
  align-items: center;
  text-align: center;
  margin-bottom: 15px;
  border-radius: 12px;
  background-color: #f9faff;
  padding: 15px 16px;

  :deep(.van-field__control) {
    padding-left: 8px;
    font-size: 15px;
  }

  :deep(.van-field__error-message) {
    margin-left: 10px;
  }

  .van-icon {
    color: @theme-color;
  }
}

.radio-group {
  margin-bottom: 15px;

  .van-radio {
    margin-right: 20px;
    margin-bottom: 10px;

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

    :deep(.van-radio__label) {
      flex: 1;
      margin-left: 8px;
    }

    :deep(.van-radio__icon--checked .van-icon) {
      background-color: @theme-color;
      border-color: @theme-color;
    }
  }

  .radio-option {
    display: flex;
    align-items: center;
    font-size: 15px;

    .van-icon {
      margin-right: 6px;
      color: @theme-color;
    }

    .flag-icon {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      margin-right: 6px;
      object-fit: cover;
    }
  }
}

.code-button {
  background-color: @theme-color;
  color: white;
  border-radius: 20px;
  font-size: 14px;
  padding: 0 15px;
  height: 34px;

  &:disabled {
    background-color: #ccc;
    color: #fff;
  }
}

.search-city {
  background-color: #fff;
  padding: 10px 16px;
  border-bottom: 1px solid #eee;
}

.register-button {
  background: linear-gradient(to right, @theme-color, #6878eb);
  color: white;
  border: none;
  height: 50px;
  font-size: 17px;
  font-weight: 500;
  margin-top: 10px;
  margin-bottom: 15px;
  box-shadow: 0 4px 15px rgba(77, 106, 221, 0.35);

  &:active {
    opacity: 0.9;
  }
}

.login-link {
  text-align: center;
  font-size: 15px;
  color: #666;
  margin-top: 15px;

  .link-text {
    color: @theme-color;
    font-weight: 500;
    margin-left: 8px;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }
}

@media (max-width: 480px) {
  .register-content {
    padding: 15px;
  }

  .register-form {
    padding: 15px;
  }

  .register-button {
    height: 48px;
    font-size: 16px;
  }
}
</style>
