<template>
  <div class="page flex-col">
    <s-header :name="sys ? sys.title : $t('user.personalCenter')" :noback="true" :isFixed="false"></s-header>
    <div class="userPageBox">
      <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">
          <div class="userId">
            <p class="userText">{{ accountDetail.managerId }}</p>
            <p class="userText">{{ $t("user.systemId") }}</p>
          </div>
          <div class="userLine"></div>
          <div class="userId">
            <p class="userText">{{ accountDetail.username }}</p>
            <p class="userText">{{ $t("user.myAccount") }}</p>
          </div>
          <div class="userLine"></div>
          <div class="userId">
            <p class="userText">{{ accountDetail.name }}</p>
            <p class="userText">{{ $t("user.myName") }}</p>
          </div>
        </div>
        <div class="userInfoBox">
          <!-- 地区 -->
          <div v-if="isInland">
            <div v-if="!areaShow" class="userInfo l-flex-between">
              <span class="userInfoLeft">{{ $t("user.region") }}: </span>
              <div class="cust_vantBorder">
                <div class="filedInpPad">
                  <van-field @click-input="fieldValueInpClk" readonly clearable v-model="fieldValue"
                    :placeholder="$t('user.regionPlace')">
                    <template #right-icon>
                      <div class="l-flex-RC">
                        <van-icon v-if="fieldValue" @click="
                          fieldValue = '';
                        accountDetail.areaId = '';
                        " class="o-mr-6" name="clear" />
                        <van-icon @click="fieldValueInpClk" name="arrow-down" />
                      </div>
                    </template>
                  </van-field>
                </div>
              </div>
              <van-icon name="edit" class="editIcon" @click="editClk(4)" />
            </div>
            <div v-else class="userInfo l-flex-between">
              <span class="userInfoLeft">{{ $t("user.region") }}: </span>
              <span>{{ fieldValue }}</span>
              <van-icon name="edit" class="editIcon" @click="editClk(4)" />
            </div>
          </div>
          <!-- 手机号 -->
          <div v-if="!phoneNumberShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.phoneNumber") }}: </span>
            <div class="cust_vantBorder">
              <van-field class="relationClass" v-model="cofficentForm.phone" :placeholder="$t('user.phoneNumberPlace')">
                <template #button>
                  <van-button type="primary" @click="mailboxChg(cofficentForm.phone, 3)">{{ $t("user.confirmLog") }}
                  </van-button>
                </template>
              </van-field>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(3)" />
          </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(3)" />
          </div>
          <!-- 邮箱 -->
          <div v-if="!mailboxShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.mailbox") }}: </span>
            <div class="cust_vantBorder">
              <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>
          <!-- 关联上级 -->
          <div v-if="isInland">
            <div v-if="!relationType" class="userInfo l-flex-between">
              <span class="userInfoLeft">{{ $t("user.associateParent") }}: </span>
              <div class="cust_vantBorder">
                <van-field class="relationClass" v-model="cofficentForm.associateParent"
                  :placeholder="$t('user.associateParentPlace')">
                  <template #button>
                    <van-button type="primary" @click="mailboxChg(cofficentForm.associateParent, 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.associateParent") }}: </span>
              <span>{{ relationAdminName }}</span>
              <van-icon name="edit" class="editIcon" @click="editClk(1)" />
            </div>
          </div>

          <!-- 自定义货币符号 -->
          <div v-if="!symbolShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.currencySymbol") }}: </span>
            <div class="cust_vantBorder">
              <van-field class="relationClass" v-model="cofficentForm.currencySymbol"
                :placeholder="$t('user.currencySymbolPlace')">
                <template #button>
                  <van-button type="primary" @click="mailboxChg(cofficentForm.currencySymbol, 5)">{{
                    $t("user.confirmLog") }}
                  </van-button>
                </template>
              </van-field>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(5)" />
          </div>
          <div v-else class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.currencySymbol") }}: </span>
            <span>{{ accountDetail.currencySymbol }}</span>
            <van-icon name="edit" class="editIcon" @click="editClk(5)" />
          </div>

          <!-- 切换支付平台 -->
          <div v-if="chaSzPayShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.szPayType") }}: </span>
            <div class="cust_vantBorder o-pl-15">
              <van-switch :model-value="sunzeePay" active-color="#0090fa" inactive-color="#30c25c" size="21px"
                @update:model-value="changeSunzeePay" />
            </div>
            <span class="o-pl-50">{{ $t("user.currentChoose") }}: {{ sunzeePay ? "汇付" : "汇聚" }}</span>
          </div>

          <div v-if="chaScPayShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.scPayType") }}: </span>
            <div class="cust_vantBorder o-pl-15">
              <van-switch :model-value="sevencloudPay" active-color="#0090fa" inactive-color="#30c25c" size="21px"
                @update:model-value="changeSevenCloudPay" />
            </div>
            <span class="o-pl-50">{{ $t("user.currentChoose") }}: {{ sevencloudPay ? "汇付" : "汇聚" }}</span>
          </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>
        <div class="operListBox">
          <!-- 任务消息 -->
          <div v-if="roleCheck()" class="taskListRow flex-col" @click="pushPageList('/taskMessage')">
            <div class="taskIcon taskMessageIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.taskMessage") }}</div>
            </div>
          </div>

          <!-- 提现帐号 -->
          <div v-if="isInland" class="taskListRow flex-col" @click="pushPageList('/settlement')">
            <div class="taskIcon joinPayMchIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.settlementAccount") }}</div>
            </div>
          </div>

          <!-- 提现帐号 -->
          <!-- <div v-if="isInland" class="taskListRow flex-col" @click="pushPageList('/joinpayMch')">
            <div class="taskIcon joinPayMchIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.withdrawalAccountNo") }}</div>
            </div>
          </div> -->

          <!-- Airwallex 钱包 -->
          <div v-if="isAbroad && user.companyType != '1'" class="taskListRow flex-col"
            @click="pushPageList('/airwallex')">
            <div class="taskIcon airwallexIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.airwallex") }}</div>
            </div>
          </div>

          <!-- 备用提现账号 -->
          <!-- <div v-if="isInland" class="taskListRow flex-col" @click="pushPageList('/huifuMch')">
            <div class="taskIcon shandeMchIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                {{ $t("user.standbyWithdrawalAccountNo") }}
              </div>
            </div>
          </div> -->
          <!--          <div class="taskListRow flex-col" @click="pushPageList('/shandeMch')">
                      <div class="taskIcon shandeMchIcon"></div>
                      <div class="taskRight">
                        <div class="taskTitle">
                          {{ $t("user.standbyWithdrawalAccountNo") }}
                        </div>
                      </div>
                    </div>-->
          <!-- 绑定微信 -->
          <div v-if="isInWeChat" class="taskListRow flex-col" @click="pushPageList('/bindWechat')">
            <!--          <div class="taskListRow flex-col" @click="pushPageList('/bindWechat')">-->
            <div class="taskIcon bindWechatIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                {{ $t("user.bindWechat") }}
              </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 v-if="isInland" class="taskListRow flex-col" @click="operUnipay()">
            <div class="taskIcon selfPayIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.selfRecharging") }}</div>
            </div>
          </div> -->

          <div class="taskListRow flex-col" @click="onperExitSys()">
            <div class="taskIcon loginOutIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.logOut") }}</div>
            </div>
          </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>
    <!-- 地区弹窗 -->
    <kCascader @getareaname="getAreaName" :selectId="accountDetail.areaId" @areapopfinish="areaPopFinish"
      ref="kCascaderRef"></kCascader>
  </div>
</template>

<script>
// 导入地区弹窗
import kCascader from "@/components/commom/kCascader/index.vue";
// 导入接口
import { getAdmin } from "@/service/merchantManage";
import { updateAdmin } from "@/service/merchantManage";
// 引入弹窗
import kDialog from "@/components/commom/kDialog/index.vue";
import { onMounted, reactive, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import navBar from "@/components/NavBar";
import {
  getLoginUser,
  $M_EmailAvailable,
  $M_PhoneTest,
} from "@/common/js/utils";
import { useRouter } from "vue-router";
import { tAdminGetRelation, tAdminSetRelationAdmin, updatePayPlatform } from "@/service/user";
import { Toast, Dialog } from "vant";
import { useI18n } from "vue-i18n";
import { styleUrl } from "../common/js/utils";

export default {
  components: { sHeader, navBar, kDialog, kCascader },
  setup() {
    // 引入语言
    const { t } = useI18n();
    // 账户信息
    const accountDetail = ref({});
    // 控制地区显示隐藏
    const areaShow = ref(true);
    // 控制手机显示隐藏
    const phoneNumberShow = ref(true);
    // 控制邮箱显示隐藏
    const mailboxShow = ref(true);
    // 控制货币显示隐藏 货币符号，默认“￥”
    const symbolShow = ref(true);
    // 控制切换支付平台按钮显示隐藏
    const chaSzPayShow = ref(false);
    const chaScPayShow = ref(false);


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

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

    const relationType = ref(true);
    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	
      payPlatform: '', //支付平台	
    });
    // 点击修改图标
    const editClk = (idx) => {
      switch (idx) {
        case 1:
          cofficentForm.associateParent = relationAdminName.value;
          relationType.value = !relationType.value;
          mailboxShow.value = true;
          phoneNumberShow.value = true;
          areaShow.value = true;
          symbolShow.value = true;
          break;
        case 2:
          cofficentForm.mailBox = accountDetail.value.email;
          relationType.value = true;
          mailboxShow.value = !mailboxShow.value;
          phoneNumberShow.value = true;
          areaShow.value = true;
          symbolShow.value = true;
          break;
        case 3:
          cofficentForm.phone = accountDetail.value.phone;
          relationType.value = true;
          mailboxShow.value = true;
          phoneNumberShow.value = !phoneNumberShow.value;
          areaShow.value = true;
          symbolShow.value = true;
          break;
        case 4:
          cofficentForm.area = accountDetail.value.area;
          relationType.value = true;
          mailboxShow.value = true;
          phoneNumberShow.value = true;
          areaShow.value = !areaShow.value;
          symbolShow.value = true;
          break;
        case 5:
          cofficentForm.currencySymbol = accountDetail.value.currencySymbol;
          relationType.value = true;
          mailboxShow.value = true;
          phoneNumberShow.value = true;
          areaShow.value = true;
          symbolShow.value = !symbolShow.value;
          break;
      }
    };
    // 点击邮箱的确定按钮
    const mailboxChg = async (e, idx) => {
      switch (idx) {
        case 1:
          if (!e) {
            Toast(t("user.associateParentPlace"));
          } else {
            const { data } = await tAdminSetRelationAdmin({
              adminId: user.id,
              username: e,
            });
            relationType.value = true;
            if (data.code === "00000") {
              Toast(data.message);
              setTimeout(() => {
                gettAdminGetRelation();
              }, 500);
            }
          }
          break;
        case 2:
          if (!e) {
            Toast(t("user.mailboxPlace"));
          } else if (!$M_EmailAvailable(e)) {
            Toast(t("user.corrEmailPlace"));
          } else {
            const params = {
              id: user.id,
              email: e,
            };
            const { data } = await updateAdmin(params);
            mailboxShow.value = true;
            if (data.code === "00000") {
              Toast(data.message);
              setTimeout(() => {
                getAcccountDetail();
              }, 500);
            }
          }
          break;
        case 3:
          if (!e) {
            Toast(t("user.phoneNumberPlace"));
          } else if (!$M_PhoneTest(e)) {
            Toast(t("user.corrPhonePlace"));
          } else {
            const params = {
              id: user.id,
              phone: e,
            };
            const { data } = await updateAdmin(params);
            phoneNumberShow.value = true;
            if (data.code === "00000") {
              Toast(data.message);
              setTimeout(() => {
                getAcccountDetail();
              }, 500);
            }
          }
          break;
        case 5:
          if (!e) {
            Toast(t("user.currencySymbolPlace"));
          } else {
            const params = {
              id: user.id,
              currencySymbol: e,
            };
            const { data } = await updateAdmin(params);
            symbolShow.value = true;
            if (data.code === "00000") {
              Toast(data.message);
              // 更新本地存储缓存中的currencySymbol的值
              user.currencySymbol = e; // 将新的currencySymbol的值赋值给user
              localStorage.setItem("loginUser", JSON.stringify(user));
              setTimeout(() => {
                getAcccountDetail();
              }, 500);
            }
          }
          break;
      }
    };
    // 获取账户详情
    const getAcccountDetail = () => {
      getAdmin({ id: user.id }).then((res) => {
        accountDetail.value = res.data.data;
        // 查询地址回显
        kCascaderRef.value.init(accountDetail.value.areaId);
      });
    };
    // 获取申泽支付平台
    const getSunzeeDetail = () => {
      getAdmin({ id: 2738 }).then((res) => {
        // sunzeePay.value = res.data.data.payPlatform;
        if (res.data.data.payPlatform == '1') {
          sunzeePay.value = true;
        }
        console.log("sunzeePay", sunzeePay.value)
      });
    };
    // 获取七云支付平台
    const getSevenCloudDetail = () => {
      getAdmin({ id: 2739 }).then((res) => {
        // sevencloudPay.value = res.data.data.payPlatform;
        if (res.data.data.payPlatform == '1') {
          sevencloudPay.value = true;
        }
        console.log("sevencloudPay", sevencloudPay.value)
      });
    };
    // 退出登录弹窗
    const kDialogRef = ref(null);
    // 点击右侧按钮
    const confirmClk = () => {
      // 获取缓存的语言
      const curLang = localStorage.getItem("curLang");
      // 清空缓存
      localStorage.clear();
      localStorage.setItem("curLang", curLang);
      if (sys.value) {
        setTimeout(() => {
          router.push({
            path: "login",
            query: { relation_admin_id: sys.value.relationAdminId },
          });
        }, 200);
      } else {
        setTimeout(() => {
          router.push({ path: "login" });
        }, 200);
      }
    };
    //切换申泽支付平台
    const changeSunzeePay = (value) => {
      Dialog.confirm({
        title: t('user.tips'),
        message: t('user.changeTips'),
      }).then(() => {
        // checked.value = newValue;
        console.log(value);
        params.id = 2738;
        if (value) {
          params.payPlatform = '1';
        } else {
          params.payPlatform = '0';
        }
        const { data } = updatePayPlatform(params);
        if (data.code) {
          Toast.success(t('user.changeSuccess'));
          sunzeePay.value = value;
        } else {
          Toast.fail(data.message);
        }
      }).catch((error) => {
        console.error(error);
      })
    }
    //切换七云支付平台
    const changeSevenCloudPay = (value) => {
      Dialog.confirm({
        title: t('user.tips'),
        message: t('user.changeTips'),
      }).then(() => {
        // checked.value = newValue;
        console.log(value);
        params.id = 2739;
        if (value) {
          params.payPlatform = '1';
        } else {
          params.payPlatform = '0';
        }
        const { data } = updatePayPlatform(params);
        if (data.code) {
          Toast.success(t('user.changeSuccess'));
          sunzeePay.value = value;
        } else {
          Toast.fail(data.message);
        }
      }).catch((error) => {
        console.error(error);
      })
    }

    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      styleUrl('user');
      if (localStorage.getItem("loginSys")) {
        const loginSysString = localStorage.getItem("loginSys");
        sys.value = JSON.parse(loginSysString);
      }
      // 获取关联上级
      gettAdminGetRelation();
      // 获取账户
      getAcccountDetail();
      if (user.id == 1 ) {
        chaSzPayShow.value = true;
        chaScPayShow.value = true;
        getSunzeeDetail();
        getSevenCloudDetail();
      } 
      // else if (user.id == 2738) {
      //   chaSzPayShow.value = true;
      //   getSunzeeDetail();
      // } else if (user.id == 2739) {
      //   chaScPayShow.value = true;
      //   getSevenCloudDetail();
      // }
    });
    const gettAdminGetRelation = async () => {
      const { data } = await tAdminGetRelation({
        relationAdminId: user.relationAdminId,
      });
      if (typeof data === "string") {
        relationAdminName.value = data;
      }
    };
    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 fieldValue = ref("");
    const kCascaderRef = ref(null);
    // 点击地区输入框
    const fieldValueInpClk = () => {
      kCascaderRef.value.openPop();
    };
    // 选择地区完成
    const areaPopFinish = async (e) => {
      console.log("e", e);
      fieldValue.value = e.selectName;
      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") {
        Toast(data.message);
        setTimeout(() => {
          getAcccountDetail();
        }, 500);
      }
    };
    const isInWeChat = ref(false);
    const checkInWechat = () => {
      const ua = window.navigator.userAgent.toLowerCase();
      // 如果是在微信中打开
      if (/MicroMessenger/i.test(ua)) {
        isInWeChat.value = true;
      }
    };
    // 是否内陆或海外
    const isInland = ref(true);
    const isAbroad = ref(false);
    // const checkIsAbroad = async () => {
    //   try {
    //     const { data } = await getIfForeign(user.id);
    //     console.log("isAbroad >>> ", data);

    //     if (data.data === '1') {
    //       // TODO: 这里先把isAbroad设置为fasle，等开发完成再改成true；
    //       isAbroad.value = false;
    //       isInland.value = false;
    //     }
    //   } catch (error) {
    //     console.error(error);
    //   }
    // };
    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(() => {
      checkInWechat();
      checkIsAbroad();
    })
    // 获取回显的值
    const getAreaName = (e) => {
      fieldValue.value = e;
    };
    return {
      user,
      operUnipay,
      onperExitSys,
      relationAdminName,
      relationType,
      pushPageList,
      roleCheck,
      sys,
      kDialogRef,
      confirmClk,
      mailboxShow,
      mailboxChg,
      phoneNumberShow,
      editClk,
      cofficentForm,
      params,
      areaShow,
      accountDetail,
      fieldValue,
      kCascaderRef,
      fieldValueInpClk,
      areaPopFinish,
      isInWeChat,
      getAreaName,
      isAbroad,
      checkIsAbroad,
      isInland,
      symbolShow,
      chaSzPayShow,
      chaScPayShow,
      sunzeePay,
      sevencloudPay,
      changeSunzeePay,
      changeSevenCloudPay,
    };
  }
};
</script>

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