<template>
  <view class="baseinfo">
    <view class="box">
      <u-form
        labelPosition="left"
        :model="model1"
        :rules="rules"
        ref="form"
        :labelWidth="0"
        :errorType="'border-bottom'"
      >
        <u-form-item
          v-for="(item, index) in formAttrList"
          :key="index"
          :prop="`userInfo.${item.key}`"
        >
          <u-input
            v-model="(model1.userInfo as any)[item.key]"
            :placeholder="`请${item.type === 'select' ? '选择' : '输入'}${
              item.name
            }`"
            clearable
            :customStyle="{}"
            :border="index === 2 ? 'none' : 'bottom'"
            :value="(model1.userInfo as any)[item.key]"
            :password="!item.isShowPwd"
            @change="(e:any) => {handleInput(e, item.key)}"
            @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>
        </u-form-item>
      </u-form>
    </view>

    <view class="save-btn">
      <u-button
        @click="submit"
        type="primary"
        :customStyle="{
          'border-radius': '43rpx',
        }"
        >保存</u-button
      >
    </view>
  </view>
</template>
<script setup lang="ts">
import { ProfileApi } from "@/services";
import valid from "@/utils/validate";

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

const handleClear = (item:any) => {
  (model1.userInfo as any)[item.key] = '';
}

// 表单属性清单
const formAttrList = ref([
  {
    name: "当前密码",
    key: "password",
    type: "password",
    required: true,
    isShowPwd: false,
  },
  {
    name: "新密码",
    key: "newPassword",
    type: "password",
    required: true,
    isShowPwd: false,
  },
  {
    name: "确认密码",
    key: "passwordConfirm",
    type: "password",
    required: true,
    isShowPwd: false,
  },
]);
const model1 = <any>reactive({
  userInfo: {
    password: "",
  },
});
const rules = ref({
  "userInfo.password": {
    type: "string",
    required: true,
    message: "请输入当前密码",
    trigger: ["blur", "change"],
  },
  "userInfo.newPassword": {
    type: "string",
    required: true,
    message: "请输入新密码",
    trigger: ["blur", "change"],
  },
  "userInfo.passwordConfirm": {
    type: "string",
    required: true,
    message: "请输入确认密码",
    trigger: ["blur", "change"],
  },
});
const form = ref();
const check = () => {
  return new Promise((resolve) => {
    form.value
      .validate()
      .then((res: boolean) => {
        resolve(res);
      })
      .catch((errors: any) => {
        resolve(false);
        uni.showToast({
          icon: "none",
          title: errors[0].message || "校验失败",
        });
      });
  });
};

const startSave = () => {
  console.log(model1.userInfo);
  ProfileApi.updateUserPwd({ ...model1.userInfo }).then((res) => {
    if (res.code === 200) {
      uni.showToast({ icon: "none", title: "密码修改成功" });
      model1.userInfo = {};
      setTimeout(() => {
        ProfileApi.logOut().then((res: any) => {
          if (res.code === 200) {
            uni.reLaunch({
              url: "/pagesLogin/login/index", // 要跳转到的页面路径
            });
          }
        });
      }, 10);
    }
  });
};

const submit = () => {
  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.password === model1.userInfo.newPassword) {
    uni.showToast({ icon: "none", title: "新密码不能和旧密码相同" });
    return;
  }
  if (model1.userInfo.newPassword !== model1.userInfo.passwordConfirm) {
    uni.showToast({ icon: "none", title: "新密码必须和确认密码相同" });
    return;
  }
  check().then((res) => {
    if (res) {
      startSave();
    }
  });
};
</script>
<style lang="scss">
.custom-icon {
  width: 37.18rpx;
  height: 18.59rpx;
}
.baseinfo {
  background: #f8f8f8;
  height: 100vh;
  padding: 26.28rpx 25.64rpx;
  .box {
    padding: 18.59rpx;
    background: #ffffff;
    box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(5, 68, 37, 0.12);
    border-radius: 13rpx;
    font-size: 27rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #000000;
    ::v-deep .u-border-bottom {
      border-color: rgb(233 233 233 / 0.76) !important;
    }
    ::v-deep .u-form-item__body__right__message {
      height: 0px;
      display: none;
    }
    ::v-deep .u-form-item {
      height: 45px;
    }
  }
  .save-btn {
    margin-top: 150px;
    button {
      width: 80%;
    }
  }
}
</style>
