<template>
  <Theme>
    <view class="wrap">
      <Navbar title="账户安全" fixed border>
        <template #right>
          <navMenu :options="{ icon: 'icon-home', text: '主页' }" />
        </template>
      </Navbar>
      <view class="content">
        <view class="cont_item">
          <view class="item_top">
            <view class="top_title">
              <trans _t="修改登录密码" />
            </view>
            <view class="top_btn" @click="editPassword('pass')">
              <trans _t="编辑" />
            </view>
          </view>
          <view class="item_tip">
            <trans _t="修改密码tips" />
          </view>
        </view>
        <view class="cont_item">
          <view class="item_top">
            <view class="top_title">
              <trans _t="新交易密码" v-if="userInfo.setpaypass" />
              <trans _t="设置交易密码" v-else />
            </view>
            <view class="top_btn" @click="editPayPassword">
              <trans _t="编辑" />
            </view>
          </view>
          <view class="item_tip">
            <trans _t="交易密码tips" />
          </view>
        </view>
      </view>
    </view>

    <Popup
      :title="edit == 'pass' ? '修改登录密码' : '交易密码'"
      ref="popupRef"
      isClose
    >
      <template #content>
        <view class="form">
          <up-form
            labelPosition="top"
            labelWidth="auto"
            :model="passwordForm"
            :rules="passwordRules"
            ref="formRef"
            v-if="edit == 'pass'"
          >
            <up-form-item prop="oldpass" :label="t('登录密码')" required>
              <up-input
                type="text"
                :placeholder="t('登录密码')"
                v-model="passwordForm.oldpass"
              ></up-input>
            </up-form-item>
            <up-form-item prop="newpass" :label="t('新密码')" required>
              <up-input
                type="text"
                :placeholder="t('新密码')"
                v-model="passwordForm.newpass"
              ></up-input>
            </up-form-item>
            <up-form-item
              prop="confirmpass"
              :label="t('再次输入密码')"
              required
            >
              <up-input
                type="text"
                :placeholder="t('再次输入密码')"
                v-model="passwordForm.confirmpass"
              ></up-input>
            </up-form-item>
          </up-form>
          <!-- <up-form
            labelPosition="top"
            labelWidth="auto"
            :model="paypassForm"
            :rules="paypassRules"
            ref="formRef"
            v-else
          >
            <up-form-item
              prop="oldpass"
              :label="t('原交易密码')"
              required
              v-if="userInfo.setpaypass"
            >
              <up-input
                type="number"
                maxlength="4"
                :placeholder="t('原交易密码')"
                v-model="paypassForm.oldpass"
              ></up-input>
            </up-form-item>
            <up-form-item prop="newpass" :label="t('新交易密码')" required>
              <up-input
                type="number"
                maxlength="4"
                :placeholder="t('新交易密码')"
                v-model="paypassForm.newpass"
              ></up-input>
            </up-form-item>
            <up-form-item
              prop="confirmpass"
              :label="t('再次输入密码')"
              required
            >
              <up-input
                type="number"
                maxlength="4"
                :placeholder="t('再次输入密码')"
                v-model="paypassForm.confirmpass"
              ></up-input>
            </up-form-item>
          </up-form> -->
        </view>
      </template>
      <template #footer>
        <view class="footer_btn">
          <view class="btn" @click="submit">
            <trans _t="提交" />
          </view>
        </view>
      </template>
    </Popup>

    <!-- PIN码弹框 -->
    <PinCodeModal
      :visible="showPinModal"
      :title="pinModalTitle"
      @complete="handlePinComplete"
      @close="handlePinClose"
    />
  </Theme>
</template>
<script setup>
import Navbar from "@/components/navbar";
import navMenu from "@/components/nav_menu";
import Popup from "@/components/popup";
import PinCodeModal from "@/components/PinCodeModal";
import { computed, ref, nextTick, reactive, onMounted } from "vue";
import { t } from "@/locale";
import {
  USER_EDIT_USERPASS,
  USER_EDIT_PAYPASS,
  USER_CHECK_PAYPASS,
} from "@/api";
import { Toast } from "@/utils";
import { useUserStore } from "@/store";

const useUser = useUserStore();
const popupRef = ref(null);
const formRef = ref(null);
const edit = ref("");

// PIN码弹框相关
const showPinModal = ref(false);
const pinModalTitle = ref("");
const pinStep = ref(""); // 'old' | 'new' | 'confirm'
const oldPinCode = ref("");
const newPinCode = ref("");

const userInfo = computed(() => useUser.getuserInfo);

const passwordForm = reactive({
  oldpass: "",
  newpass: "",
  confirmpass: "",
});
const passwordRules = reactive({
  oldpass: {
    required: true,
    message: t("密码是必需的"),
    trigger: ["change"],
  },
  newpass: {
    required: true,
    message: t("密码是必需的"),
    trigger: ["change"],
  },
  confirmpass: [
    {
      required: true,
      message: t("密码是必需的"),
      trigger: ["change"],
    },
    {
      validator: (rule, value, callback) => {
        if (value != passwordForm.newpass) {
          callback(new Error(t("两次密码不一致")));
        } else {
          callback();
        }
      },
    },
  ],
});
const paypassForm = reactive({
  oldpass: "",
  newpass: "",
  confirmpass: "",
});
// const paypassRules = reactive({
//   oldpass: {
//     required: true,
//     len: 4,
//     message: t("密码是必需的且为4位"),
//     trigger: ["change"],
//   },
//   newpass: {
//     required: true,
//     len: 4,
//     message: t("密码是必需的且为4位"),
//     trigger: ["change"],
//   },
//   confirmpass: [
//     {
//       required: true,
//       len: 4,
//       message: t("密码是必需的且为4位"),
//       trigger: ["change"],
//     },
//     {
//       validator: (rule, value, callback) => {
//         if (value != paypassForm.newpass) {
//           callback(new Error(t("两次密码不一致")));
//         } else {
//           callback();
//         }
//       },
//     },
//   ],
// });

const submit = () => {
  formRef.value
    .validate()
    .then((valid) => {
      editPass();
    })
    .catch(() => {});
};
const editPass = async () => {
  try {
    if (edit.value == "pass") {
      const res = await USER_EDIT_USERPASS({
        oldpass: passwordForm.oldpass,
        newpass: passwordForm.newpass,
      });
      Toast(res.msg, 1000).then(() => {
        setTimeout(() => {
          useUser.loginOut();
        }, 1000);
      });
      return;
    }
    const res = await USER_EDIT_PAYPASS({
      oldpass: paypassForm.oldpass,
      newpass: paypassForm.newpass,
    });
    Toast(res.msg, 1000).then(() => {
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    });
  } catch (error) {
    Toast(error.msg);
  }
};

const editPassword = (value) => {
  edit.value = value;
  nextTick(() => {
    popupRef.value && popupRef.value.open();
  });
};

const editPayPassword = () => {
  if (userInfo.value.setpaypass) {
    pinStep.value = "old";
    pinModalTitle.value = "输入原PIN码进行验证";
  } else {
    pinStep.value = "new";
    pinModalTitle.value = "输入PIN码进行验证";
  }
  showPinModal.value = true;
};

// 处理PIN码输入完成
const handlePinComplete = async (pinCode) => {
  try {
    if (pinStep.value === "old") {
      // 验证原密码
      const res = await verifyOldPayPassword(pinCode);
      if (res.success) {
        oldPinCode.value = pinCode;
        pinStep.value = "confirm";
        pinModalTitle.value = "输入新PIN码进行验证";
      } else {
        Toast(res.msg);
      }
    } else if (pinStep.value === "new") {
      // 设置新密码
      newPinCode.value = pinCode;
      await updatePayPassword();
    } else if (pinStep.value === "confirm") {
      // 确认新密码
      newPinCode.value = pinCode;
      await updatePayPassword();
    }
  } catch (error) {
    Toast(error.msg);
    showPinModal.value = false;
  }
};

// 处理PIN码弹框关闭
const handlePinClose = () => {
  showPinModal.value = false;
  // 重置状态
  pinStep.value = "";
  oldPinCode.value = "";
  newPinCode.value = "";
};

// 验证原交易密码
const verifyOldPayPassword = async (pinCode) => {
  try {
    const res = await USER_CHECK_PAYPASS(pinCode);
    return { success: true, data: res };
  } catch (error) {
    return { success: false, msg: error.msg };
  }
};

// 更新交易密码
const updatePayPassword = async () => {
  try {
    const params = {
      newpass: newPinCode.value,
    };

    // 如果已设置过密码，需要传入原密码
    if (userInfo.value.setpaypass) {
      params.oldpass = oldPinCode.value;
    }

    const res = await USER_EDIT_PAYPASS(params);
    Toast(res.msg, 1000).then(() => {
      handlePinClose();
      useUser.getUserInfo();
    });
  } catch (error) {
    Toast(error.msg);
    showPinModal.value = false;
  }
};

onMounted(() => {
  useUser.getUserInfo();
});
</script>
<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  background: var(--bg);
  min-height: 100vh;

  .content {
    padding: 24rpx;

    .cont_item {
      background-color: var(--light);
      border-radius: 16rpx;
      padding: 32rpx;

      .item_top {
        .flex_position(space-between);

        .top_title {
          color: var(--text);
          .size();
          font-weight: 700;
          line-height: 60rpx;
        }

        .top_btn {
          border-radius: 16rpx;
          height: 64rpx;
          margin-left: 24rpx;
          min-width: 164rpx;
          background-color: var(--black);
          color: var(--light);
          .flex_center();
          .size(24rpx);
        }
      }

      &:last-child {
        margin-top: 32rpx;
      }

      .item_tip {
        margin-top: 16rpx;
        color: var(--text-01);
        .size(24rpx);
        line-height: 40rpx;
      }
    }
  }
}

.form {
  width: 100%;

  /deep/ .u-form {
    margin-top: 16px;
  }

  /deep/ .u-form-item {
    padding-bottom: 20rpx;

    .u-form-item__body {
      padding: 0;
    }

    .u-form-item__body__left__content__label {
      color: var(--text);
      .size(28rpx);
      font-weight: 700;
      line-height: 60rpx;
      min-width: 200rpx;
    }

    .u-form-item__body__right__message {
      margin-top: 10rpx;
    }

    .u-form-item__body__right__content {
      .u-input {
        padding: 16rpx 24rpx !important;
        border-radius: 16rpx !important;
        background-color: var(--bg);

        &:hover {
          box-shadow: 0 0 0 1px var(--primary) inset;
        }
      }

      .u-input__content__field-wrapper__field {
        height: 32px;
        line-height: 32px;

        .input-placeholder,
        .uni-input-input {
          font-size: 28rpx !important;
        }
      }
    }
  }
}

.footer_btn {
  .btn {
    background-color: var(--black);
    padding: 16rpx 30rpx;
    border-radius: 16rpx;
    height: 76rpx;
    .flex_center();
    .size(24rpx);
    color: var(--light);
  }
}

.popup_content {
  text-align: center;
  line-height: 1.5;
  font-size: 30rpx;
}

.popup__footer {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;

  .popup__footer-btn {
    padding: 8rpx 36rpx;
    border: 1rpx solid #333;
    border-radius: 12rpx;
    font-size: 28rpx;
  }

  .popup__footer-btn__confirm {
    display: flex;
    align-items: center;
    background-color: var(--black);
    color: var(--light);
  }
}
</style>