<template>
  <LoginLayout>
    <template #form-box>
      <u-form
        labelPosition="left"
        :model="model1"
        :rules="rules"
        ref="loginForm"
        :labelWidth="0"
      >
        <u-form-item
          v-for="(item, index) in formAttrList"
          :key="index"
          :prop="`userInfo.${item.modelName}`"
        >
          <view v-if="item.type === 'text'">
            <u-input
              v-model="model1.userInfo[`${item.modelName}`]"
              :placeholder="item.placeholder"
              :shape="'circle'"
              clearable
              :customStyle="{
                'border-color':
                  currentFocus === item.modelName ? '#00dcee !important' : '',
              }"
              @focus="handleFocus(item.modelName)"
              @blur="handleFocus('')"
              @change="(e:any) => {handleInput(e, item.modelName)}"
              @clear="handleClear(item)"
            >
              <template #suffix>
                <text v-if="item.modelName === 'code'" class="code-btn">
                  <text
                    v-if="seconds === 0"
                    @click="handleCode"
                    class="code-primary"
                    >获取验证码</text
                  >
                  <text v-else
                    >剩余<text class="code-primary">{{ seconds }}秒</text></text
                  >
                </text>
              </template>
            </u-input>
          </view>
          <view v-if="item.type === 'password'">
            <u-input
              v-model="model1.userInfo[`${item.modelName}`]"
              :placeholder="item.placeholder"
              :shape="'circle'"
              clearable
              :password="!item.isShowPwd"
              :customStyle="{
                'border-color':
                  currentFocus === item.modelName ? '#00dcee !important' : '',
              }"
              @focus="handleFocus(item.modelName)"
              @blur="handleFocus('')"
              @change="(e:any) => {handleInput(e, item.modelName)}"
              @clear="handleClear(item)"
            >
              <template #suffix>
                <image
                  v-if="!item.isShowPwd"
                  :src="`https://backend-common.obs.cn-east-3.myhuaweicloud.com/static/pagesLogin/login/hide.png`"
                  class="custom-icon"
                  @click="item.isShowPwd = true"
                ></image>
                <image
                  v-else
                  :src="`https://backend-common.obs.cn-east-3.myhuaweicloud.com/static/pagesLogin/login/show.png`"
                  class="custom-icon"
                  @click="item.isShowPwd = false"
                ></image>
              </template>
            </u-input>
          </view>
        </u-form-item>
      </u-form>

      <view class="login-btn">
        <u-button
          @click="submit"
          type="primary"
          :customStyle="{
            'border-radius': '43rpx',
          }"
          >保存</u-button
        >
      </view>
    </template>
  </LoginLayout>
</template>

<script setup lang="ts">
import { ProfileApi } from "@/services/index";
import LoginLayout from "./components/loginLayout.vue";
import valid from "@/utils/validate";
const handleClear = (item:any) => {
  (model1.userInfo as any)[item.modelName] = '';
}
const loginForm = ref(null);
const model1 = <any>reactive({
  userInfo: {
    phone: "",
    code: "",
    newPassword: "",
    passwordConfirm: "",
  },
});
// 控制focus 边框样式
const currentFocus = ref("");

// 表单属性清单
const formAttrList = ref([
  {
    modelName: "phone",
    type: "text",
    placeholder: "请输入手机号",
  },
  {
    modelName: "code",
    type: "text",
    placeholder: "请输入验证码",
  },
  {
    modelName: "newPassword",
    type: "password",
    placeholder: "请输入新密码",
    isShowPwd: false, // 控制密码显示隐藏
  },
  {
    modelName: "passwordConfirm",
    type: "password",
    placeholder: "请输入确认密码",
    isShowPwd: false, // 控制密码显示隐藏
  },
]);

const handleInput = (e: any, key: string) => {
  if (key === "phone") {
    const temp = e?.replace(valid.valid_number, "");
    setTimeout(() => {
      (model1.userInfo as any)[key] = temp;
    }, 10);
  }

  if (key === "code") {
    const temp = e?.replace(valid.valid_number, "");
    setTimeout(() => {
      (model1.userInfo as any)[key] = temp;
    }, 10);
  }

  if (key === "newPassword" || key === "passwordConfirm") {
    const temp = e?.replace(valid.valid_no_cn, "");
    setTimeout(() => {
      (model1.userInfo as any)[key] = temp;
    }, 10);
  }
};

// 获取验证码交互
const seconds = ref(0);
const handleCode = () => {
  if (model1.userInfo === undefined || !model1.userInfo.phone) {
    uni.showToast({
      title: "请输入手机号",
      icon: "error",
    });
    return;
  }
  if (!valid.mobile.pattern.test(model1.userInfo.phone)) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "error",
    });
    return;
  }
  ProfileApi.sendCommonMsg({
    phone: model1.userInfo.phone,
    type: "forget",
  }).then((res) => {
    seconds.value = 120;
    let countDownTimer = setInterval(() => {
      if (seconds.value > 0) {
        --seconds.value;
      } else {
        clearInterval(countDownTimer);
      }
    }, 1000);
  });
};
const rules = ref({
  "userInfo.phone": {
    type: "string",
    required: true,
    message: "请输入手机号",
    trigger: ["blur", "change"],
  },
  "userInfo.code": {
    type: "string",
    required: true,
    message: "请输入验证码",
    trigger: ["blur", "change"],
  },
  "userInfo.newPassword": {
    type: "string",
    required: true,
    trigger: ["blur", "change"],
    message: "请输入新密码",
  },
  "userInfo.passwordConfirm": {
    type: "string",
    required: true,
    message: "请输入确认密码",
    trigger: ["blur", "change"],
  },
});

const handleFocus = (attr: string) => {
  currentFocus.value = attr;
};

const submit = () => {
  if (model1.userInfo.phone) {
    if (!valid.mobile.pattern.test(model1.userInfo.phone)) {
      uni.showToast({ icon: "none", title: "请输入正确的手机号" });
      return;
    }
  }
  if (model1.userInfo.newPassword || model1.userInfo.passwordConfirm) {
    if (
      !valid.valid_password.pattern.test(model1.userInfo.newPassword) ||
      !valid.valid_password.pattern.test(model1.userInfo.passwordConfirm)
    ) {
      uni.showToast({
        icon: "none",
        title: valid.valid_password.message,
      });
      return;
    }
  }

  if (model1.userInfo.newPassword !== model1.userInfo.passwordConfirm) {
    uni.showToast({ icon: "none", title: "新密码必须和确认密码相同" });
    return;
  }

  (loginForm.value as any).validate().then((res: any) => {
    if (res) {
      // 忘记密码登录
      ProfileApi.forgetPwd({ ...model1.userInfo, type: "forget" }).then(
        (res: any) => {
          if (res.code === 200) {
            uni.showToast({ title: "密码更新成功" });
            uni.navigateBack();
          }
        }
      );
    }
  });
};
</script>

<style lang="scss" scoped>
.custom-icon {
  width: 37.18rpx;
  height: 18.59rpx;
}
.login-btn {
  margin-top: 23.72rpx;
}
::v-deep .u-form-item__body__right__message {
  margin-left: 10px !important;
}
.code-btn {
  font-size: 27rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  cursor: pointer;
  .code-primary {
    color: $u-primary;
  }
}
</style>
