<template>
  <div class="userPage flex-col">
    <div class="userPageBox">
      <s-header :name="sys ? sys.title : $t('user.personalCenter')" :noback="true" :isFixed="false"></s-header>

      <div class="userBaseBox">
        <!-- 基本信息 -->
        <div class="baseRow flex-row justify-between">
          <div class="group2 flex-col"></div>
          <span class="baseText">{{ $t("user.essentialInformation") }}</span>
        </div>

        <div class="userMessage flex-row justify-between">
          <!-- 初始份额 stockNum -->
          <div class="userId">
            <!-- <p class="userText">{{ accountDetail.stockNum }}</p> -->
            <p class="userText">5000</p>
            <p class="userText">剩余份额</p>
          </div>
          <!-- 竖线 -->
          <div class="userLine"></div>
          <!-- 会员等级 level -->
          <div class="userId">
            <van-image v-for="(icon, index) in icons" :key="index" :src="icon" round width="0.4rem" height="0.4rem"
              @click="showTop = true"></van-image>
            <van-popup v-model:show="showTop" round position="top"
              :style="{ height: '10%' }"><br />一个⭐代表1贡献值<br />一个🌙代表5贡献值</van-popup>
            <p class="userText">奋斗贡献值</p>
          </div>
          <div class="userLine"></div>
          <!-- 用户名 userName -->
          <div class="userId">
            <p class="userText">{{ accountDetail.userName }}</p>
            <!-- <p class="userText">test</p> -->
            <p class="userText">用户名</p>
          </div>
        </div>

        <div class="userInfoBox">
          <!-- 手机号码 -->
          <div v-if="!phoneNumberShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.phoneNumber") }}: </span>
            <div>
              <van-field class="relationClass" v-model="cofficentForm.phone" :placeholder="$t('user.phoneNumberPlace')">
                <template #button>
                  <van-button type="primary" @click="mailboxChg(cofficentForm.phone, 1)">{{ $t("user.confirmLog") }}
                  </van-button>
                </template>
              </van-field>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(1)" />
          </div>
          <div v-else class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.phoneNumber") }}: </span>
            <span>{{ accountDetail.phone }}</span>
            <van-icon name="edit" class="editIcon" @click="editClk(1)" />
          </div>
          <!-- 邮箱 -->
          <div v-if="!mailboxShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.mailbox") }}: </span>
            <div>
              <van-field class="relationClass" v-model="cofficentForm.mailBox" :placeholder="$t('user.mailboxPlace')">
                <template #button>
                  <van-button type="primary" @click="mailboxChg(cofficentForm.mailBox, 2)">{{ $t("user.confirmLog") }}
                  </van-button>
                </template>
              </van-field>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(2)" />
          </div>
          <div v-else class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.mailbox") }}: </span>
            <span>{{ accountDetail.email }}</span>
            <van-icon name="edit" class="editIcon" @click="editClk(2)" />
          </div>

          <!-- 支付宝账号 payeeCode -->
          <div class="userInfo l-flex-between">
            <span class="userInfoLeft">支付宝账号: </span>
            <span>{{ accountDetail.payeeCode }}</span>
          </div>

          <!-- 银行卡号 cardNo -->
          <div class="userInfo l-flex-between">
            <span class="userInfoLeft">银行卡号: </span>
            <span>{{ eyeOpen ? cardNo : hiddenCardNo }}</span>
            <van-icon class="l-eye" :name="eyeOpen ? 'eye-o' : 'closed-eye'" size="20" @click="clickEye" />
          </div>

        </div>

      </div>

      <div class="lineBox"></div>
      <div class="commonOperBox">
        <!-- 常用操作 -->
        <div class="baseRow flex-row justify-between">
          <div class="group2 flex-col"></div>
          <span class="baseText">{{ $t("user.commonOperations") }}</span>
        </div>
        <!-- TODO: 后面这里改成 Grid 宫格 -->
        <div class="operListBox">
          <!-- 系统管理 -->
          <div class="taskListRow flex-col" @click="pushPageList('/taskMessage')">
            <div class="taskIcon taskMessageIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">系统管理</div>
            </div>
          </div>

          <!-- 买家确认付款 -->
          <div class="taskListRow flex-col" @click="pushPageList('/buyConfList')">
            <div class="taskIcon buyConfIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                买入付款确认
              </div>
            </div>
          </div>

          <!-- 卖家收款确认 -->
          <div class="taskListRow flex-col" @click="pushPageList('/sellConfList')">
            <div class="taskIcon sellConfIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                卖家收款确认
              </div>
            </div>
          </div>


          <!-- 首页通知 -->
          <div class="taskListRow flex-col" @click="pushPageList('/announcement')">
            <div class="taskIcon announcementIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                首页通知
              </div>
            </div>
          </div>

          <!-- 异议反馈 -->
          <div class="taskListRow flex-col" @click="pushPageList('/objectionFeedback')">
            <div class="taskIcon feedbackIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                异议反馈
              </div>
            </div>
          </div>

          <!-- 修改密码 -->
          <div class="taskListRow flex-col" @click="pushPageList('/changepassword')">
            <div class="taskIcon changePasswordIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.changePassword") }}</div>
            </div>
          </div>

          <!-- 退出登录 -->
          <div class="taskListRow flex-col" @click="onperExitSys()">
            <div class="taskIcon logoutIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.logOut") }}</div>
            </div>
          </div>

          <div style="height: 100px;"></div>
        </div>
      </div>
    </div>
    <!-- <nav-bar></nav-bar> -->
    <!-- 退出登录弹窗 -->
    <kDialog :dialogTitle="$t('user.logOutTips')" :cancelBtnTxt="$t('user.cancelLog')"
      :confirmBtnTxt="$t('user.confirmLog')" ref="kDialogRef" :dialogContent="$t('user.logOutContent')"
      @confirmclk="confirmClk">
    </kDialog>

  </div>
</template>

<script>
// 导入接口
import { getLoginInfo } from "@/service/merchantManage";
import { updateAdmin } from "@/service/merchantManage";
// 引入弹窗
import kDialog from "@/components/commom/kDialog/index.vue";
import { onMounted, reactive, ref, computed } from "vue";
import sHeader from "@/components/SimpleHeader";
import {
  getLoginUser,
  $M_EmailAvailable,
  $M_PhoneTest,
} from "@/common/js/utils";
import { useRouter } from "vue-router";
import { showToast } from 'vant';
import { useI18n } from "vue-i18n";
import { styleUrl } from "@/common/js/utils";

export default {
  components: { sHeader, kDialog },
  setup() {
    // 引入语言
    const { t } = useI18n();
    // 账户信息
    const accountDetail = ref({});
    // 控制手机显示隐藏
    const phoneNumberShow = ref(true);
    // 控制邮箱显示隐藏
    const mailboxShow = ref(true);

    const diyPassword = ref("");

    const sunzeePay = ref(false);
    const sevencloudPay = ref(false);

    const user = getLoginUser();
    const router = useRouter();
    const relationAdminName = ref("");

    const level = ref('');
    level.value = user.level;

    const cardNo = ref('');
    cardNo.value = user.cardNo;

    const starsCount = ref(Math.floor(level.value % 5));
    const moonsCount = ref(Math.floor(level.value / 5));

    const icons = computed(() => {
      const iconsArray = [];
      for (let i = 0; i < moonsCount.value; i++) {
        iconsArray.push(require('@/assets/user/moon.png'));
      }
      for (let i = 0; i < starsCount.value; i++) {
        iconsArray.push(require('@/assets/user/star.png'));
      }
      return iconsArray;
    });

    const showTop = ref(false);

    const sys = ref(null);
    // 修改的个人信息
    const cofficentForm = reactive({
      associateParent: relationAdminName.value,
      mailBox: accountDetail.value.email,
      phone: accountDetail.value.phone,
      area: "",
      currencySymbol: accountDetail.value.currencySymbol,
    });
    // 
    const params = reactive({
      id: '', // 用户ID	
    });
    // 点击修改图标
    const editClk = (idx) => {
      switch (idx) {
        case 1:
          cofficentForm.phone = accountDetail.value.phone;
          phoneNumberShow.value = !phoneNumberShow.value;
          mailboxShow.value = true;
          break;
        case 2:
          cofficentForm.mailBox = accountDetail.value.email;
          phoneNumberShow.value = true;
          mailboxShow.value = !mailboxShow.value;
          break;
      }
    };
    // 点击邮箱的确定按钮
    const mailboxChg = async (e, idx) => {
      switch (idx) {
        case 1:
          if (!e) {
            showToast(t("user.phoneNumberPlace"));
          } else if (!$M_PhoneTest(e)) {
            showToast(t("user.corrPhonePlace"));
          } else {
            const params = {
              id: user.id,
              phone: e,
            };
            const { data } = await updateAdmin(params);
            phoneNumberShow.value = true;
            if (data.code === "00000") {
              showToast(data.message);
              setTimeout(() => {
                getAcccountDetail();
              }, 500);
            }
          }
          break;
        case 2:
          if (!e) {
            showToast(t("user.mailboxPlace"));
          } else if (!$M_EmailAvailable(e)) {
            showToast(t("user.corrEmailPlace"));
          } else {
            const params = {
              id: user.id,
              email: e,
            };
            const { data } = await updateAdmin(params);
            mailboxShow.value = true;
            if (data.code === "00000") {
              showToast(data.message);
              setTimeout(() => {
                getAcccountDetail();
              }, 500);
            }
          }
          break;
      }
    };

    const hiddenCardNo = ref('');
    if(user.cardNo) {
      hiddenCardNo.value = user.cardNo.replace(/^(\d{4}).*?(\d{4})$/, "$1********$2");
    }

    const eyeOpen = ref(false);
    const clickEye = () => {
      eyeOpen.value = !eyeOpen.value;
    }

    // 获取账户详情
    const getAcccountDetail = () => {
      getLoginInfo().then((res) => {
        accountDetail.value = res.data.data;
      });
    };

    // 退出登录弹窗
    const kDialogRef = ref(null);
    // 点击右侧按钮
    const confirmClk = () => {
      // 获取缓存的语言
      const savedCredentials = localStorage.getItem('savedCredentials');
      const curLang = localStorage.getItem("curLang");
      // 清空缓存
      localStorage.clear();
      localStorage.setItem("curLang", curLang);
      if (savedCredentials) {
        localStorage.setItem('savedCredentials', savedCredentials);
      }
      if (sys.value) {
        setTimeout(() => {
          router.push({
            path: "login",
            query: { relation_admin_id: sys.value.relationAdminId },
          });
        }, 200);
      } else {
        setTimeout(() => {
          router.push({ path: "login" });
        }, 200);
      }
    };

    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl('user');
      // if (localStorage.getItem("loginSys")) {
      //   const loginSysString = localStorage.getItem("loginSys");
      //   sys.value = JSON.parse(loginSysString);
      // }

      // 获取账户
      getAcccountDetail();

    });

    const operUnipay = () => {
      router.push({ path: "uniPay" });
    };
    const onperExitSys = () => {
      kDialogRef.value.openDialog();
    };
    const pushPageList = (url) => {
      router.push({ path: url });
    };

    // const roleCheck = () => {
    //   if (user.isAdmined) {
    //     return true;
    //   } else {
    //     const menuList = user.menuCodeList.filter((item) => item === "M6");
    //     return menuList.length > 0;
    //   }
    // };

    // 选择地区完成
    const areaPopFinish = async (e) => {
      console.log("e", e);
      accountDetail.value.areaId = e.selectId;
      const params = {
        id: user.id,
        areaId: e.selectId,
      };
      const { data } = await updateAdmin(params);
      // areaShow.value = true;
      if (data.code === "00000") {
        showToast(data.message);
        setTimeout(() => {
          getAcccountDetail();
        }, 500);
      }
    };
    const isInWeChat = ref(false);

    // 是否内陆或海外
    const isInland = ref(true);
    const isAbroad = ref(false);
    // 是否有上级账号
    const haveRelation = ref(false);
    const haveRelationCheck = () => {
      if (user.relationAdminId !== null) {
        haveRelation.value = true;
      }
    }

    const checkIsAbroad = async () => {
      try {
        const userInfo = localStorage.getItem("loginUser");
        const userIfForeign = JSON.parse(userInfo);
        // console.log("用户的海内外信息" + userIfForeign.ifForeign);
        // console.log("看下user是什么***" + user.menuCodeList);
        if (userIfForeign.ifForeign === '1') {
          isAbroad.value = true;
          isInland.value = false;
        }
      } catch (error) {
        console.error(error);
      }
    };

    onMounted(() => {
      checkIsAbroad();
      haveRelationCheck();
    })

    return {
      user,
      operUnipay,
      onperExitSys,
      relationAdminName,
      pushPageList,
      sys,
      kDialogRef,
      confirmClk,
      mailboxChg,
      editClk,
      cofficentForm,
      params,
      accountDetail,
      areaPopFinish,
      isInWeChat,
      isAbroad,
      haveRelation,
      checkIsAbroad,
      isInland,
      diyPassword,
      sunzeePay,
      sevencloudPay,
      level,
      icons,
      showTop,
      hiddenCardNo,
      phoneNumberShow,
      mailboxShow,
      clickEye,
      eyeOpen,
      cardNo
    };
  }
};
</script>

<style lang="less" scoped>
@import "../../common/style/mixin.less";
@import "../../styles/user/index.less";
</style>
