<template>
  <div class="userPage 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 l-flex-RC">
          <div class="group2"></div>
          <span class="baseText">{{ $t("user.essentialInformation") }}</span>
        </div>
        <div class="userMessage">
          <div class="userId leftCol">
            <p class="infoValue">{{ accountDetail.managerId }}</p>
            <p class="infoLabel">{{ $t("user.systemId") }}</p>
          </div>
          <div class="verticalDivider"></div>
          <div class="userId rightCol">
            <p class="infoValue">{{ accountDetail.username }}</p>
            <p class="infoLabel">{{ $t("user.myAccount") }}</p>
          </div>
        </div>
        <div class="userInfoBox">
          <!-- 地区 -->
          <div
            v-if="user.type == '2' && !areaShow"
            class="userInfo l-flex-between"
          >
            <span class="userInfoLeft">{{ $t("user.region") }}</span>
            <div class="cust_vantBorder">
              <div class="filedInpPad">
                <van-field
                  @click-input="clickShowArea"
                  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="clickShowArea" name="arrow-down" />
                    </div>
                  </template>
                </van-field>
              </div>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(4)" />
          </div>
          <div
            v-if="user.type == '2' && areaShow"
            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
            v-if="user.type != '0' && !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-if="user.type != '0' && mailboxShow"
            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="user.type != '0' && !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, 3)"
                    >{{ $t("user.confirmLog") }}
                  </van-button>
                </template>
              </van-field>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(3)" />
          </div>
          <div
            v-if="user.type != '0' && phoneNumberShow"
            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="!symbolShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.currencySymbol") }}</span>
            <div>
              <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="user.type > 1 && !timezoneShow"
            class="userInfo l-flex-between"
          >
            <span class="userInfoLeft">{{ $t("user.setTheTimezone") }}: </span>
            <div class="cust_vantBorder">
              <div class="filedInpPad">
                <van-field
                  @click-input="tzFieldValueInpClk"
                  readonly
                  clearable
                  v-model="tzFieldValue"
                  :placeholder="$t('user.setTheTimezonePlace')"
                >
                  <template #right-icon>
                    <div class="l-flex-RC">
                      <van-icon
                        v-if="tzFieldValue"
                        @click="
                          tzFieldValue = '';
                          accountDetail.timeZone = '';
                        "
                        class="o-mr-6"
                        name="clear"
                      />
                      <van-icon @click="tzFieldValueInpClk" name="arrow-down" />
                    </div>
                  </template>
                </van-field>
              </div>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(7)" />
          </div>
          <div
            v-if="user.type > 1 && timezoneShow"
            class="userInfo l-flex-between"
          >
            <span class="userInfoLeft">{{ $t("user.setTheTimezone") }} </span>
            <span>{{ tzFieldValue }}</span>
            <van-icon name="edit" class="editIcon" @click="editClk(7)" />
          </div>

          <!-- DIY使用密码 -->
          <div
            v-if="user.type == '0' && !diyPasswordShow"
            class="userInfo l-flex-between"
          >
            <span class="userInfoLeft">{{ $t("user.diyPassword") }}</span>
            <div>
              <van-field
                class="relationClass"
                v-model="diyPassword"
                :placeholder="$t('user.diyPasswordPlace')"
              >
                <template #button>
                  <van-button type="primary" @click="mailboxChg(diyPassword, 6)"
                    >{{ $t("user.confirmLog") }}
                  </van-button>
                </template>
              </van-field>
            </div>
            <van-icon name="edit" class="editIcon" @click="editClk(6)" />
          </div>
          <div
            v-if="user.type == '0' && diyPasswordShow"
            class="userInfo l-flex-between"
          >
            <span class="userInfoLeft">{{ $t("user.diyPassword") }}</span>
            <van-icon name="edit" class="editIcon" @click="editClk(6)" />
          </div>

          <!-- 切换支付平台 -->
          <div v-if="chaSzPayShow" class="userInfo l-flex-between">
            <span class="userInfoLeft">{{ $t("user.szPayType") }}</span>
            <div class="cust_vantBorder">
              <van-switch
                :model-value="sunzeePay"
                active-color="#0090fa"
                inactive-color="#30c25c"
                style="font-size: 0.5rem"
                @update:model-value="changeSunzeePay"
              />
            </div>
            <span class="o-pl-10"
              >{{ $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">
              <van-switch
                :model-value="sevencloudPay"
                active-color="#0090fa"
                inactive-color="#30c25c"
                style="font-size: 0.5rem"
                @update:model-value="changeSevenCloudPay"
              />
            </div>
            <span class="o-pl-10"
              >{{ $t("user.currentChoose") }}:
              {{ sevencloudPay ? "汇付" : "汇聚" }}</span
            >
          </div>
          <!-- 订单通知 -->
          <div v-if="isInWeChat && user.type == '2'" class="userInfo l-flex-RC">
            <span class="userInfoLeft l-flex-RC"
              >{{ $t("user.orderNotice") }}:
            </span>
            <div class="cust_vantBorder">
              <van-switch
                :model-value="orderNotice"
                active-color="#0090fa"
                style="font-size: 20px"
                @update:model-value="changeOrderNotice"
              />
            </div>
          </div>
          <!-- 设备上下线提醒 -->
          <div
            v-if="(isInWeChat || user.ifForeign === '1') && user.type == '2'"
            class="userInfo l-flex-RC"
          >
            <span class="userInfoLeft l-flex-RC"
              >{{ $t("user.onOffNotice") }}
            </span>
            <div class="cust_vantBorder">
              <van-switch
                :model-value="onOffNotice"
                style="font-size: 25px"
                @update:model-value="changeOnOffNotice"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="commonOperBox">
        <!-- 常用操作 -->
        <div class="baseRow l-flex-RC">
          <div class="group2"></div>
          <span class="baseText">{{ $t("user.commonOperations") }}</span>
        </div>
        <div class="operListBox">
          <!-- 常用工具 -->
          <div
            class="taskListRow l-flex-RC"
            @click="pushPageList('/commonTools')"
          >
            <div class="taskIcon commonToolsIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("home.commonTools") }}</div>
            </div>
          </div>

          <!-- 任务消息 -->
          <div
            v-if="roleCheck()"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/taskMessage')"
          >
            <div class="taskIcon taskMessageIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.taskMessage") }}</div>
            </div>
          </div>

          <!-- 提现帐号 -->
          <!-- <div v-if="isInland && (user.type == 2 || user.type == 3)" class="taskListRow l-flex-RC"
            @click="pushPageList('/settlement')">
            <div class="taskIcon joinPayMchIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.settlementAccount") }}</div>
            </div>
          </div> -->
          <!-- 提现帐号 -->
          <div
            v-if="user.type == 0"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/bindBankCard')"
          >
            <div class="taskIcon joinPayMchIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">绑定银行卡</div>
            </div>
          </div>
          <!-- 提现帐号 -->
          <div
            v-if="isInland && (user.type == 2 || user.type == 3)"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/purse')"
          >
            <div class="taskIcon joinPayMchIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">钱包</div>
            </div>
          </div>

          <!-- 公告编辑 -->
          <div
            v-if="user.type == '0'"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/announcement')"
          >
            <div class="taskIcon announcementIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                {{ $t("user.announcement") }}
              </div>
            </div>
          </div>

          <!-- 绑定微信 -->
          <div
            v-if="isInWeChat"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/bindWechat')"
          >
            <div class="taskIcon bindWechatIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                {{ $t("user.bindWechat") }}
              </div>
            </div>
          </div>

          <!-- 定位修改 -->
          <div
            v-if="user.type <= '1'"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/modifyLoc')"
          >
            <div class="taskIcon modifyLocIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                {{ $t("user.modifyLoc") }}
              </div>
            </div>
          </div>

          <!-- 数据同步 -->
          <div
            v-if="user.type == '0'"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/syncOldData')"
          >
            <div class="taskIcon syncOldDataIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">
                {{ $t("user.syncOldData") }}
              </div>
            </div>
          </div>

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

          <!-- 意见反馈 -->
          <div
            v-if="user.type > 1"
            class="taskListRow l-flex-RC"
            @click="pushPageList('/feedback')"
          >
            <div class="taskIcon feedbackIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.feedback") }}</div>
            </div>
          </div>

          <div class="taskListRow l-flex-RC" @click="onperExitSys()">
            <div class="taskIcon loginOutIcon"></div>
            <div class="taskRight">
              <div class="taskTitle">{{ $t("user.logOut") }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 时区弹窗 -->
    <kTimezone
      @gettimezone="getTimezone"
      :selectId="accountDetail.timezone"
      @timezonepopfinish="timezonePopFinish"
      ref="kTimezoneRef"
    ></kTimezone>
    <!-- 省市选择弹窗 -->
    <van-popup v-model:show="showArea" position="bottom">
      <van-cascader
        :title="$t('register.areaRequired')"
        :options="areaOptions"
        @close="showArea = false"
        @finish="onConfirmArea"
      />
    </van-popup>
    <!-- 国家选择弹窗 -->
    <van-popup v-model:show="showCountry" round position="bottom">
      <van-cascader
        :title="$t('register.chooseCountryCity')"
        :options="countryOptions"
        @close="showCountry = false"
        @finish="onConfirmCountry"
      >
        <template #options-top="{ tabIndex }">
          <van-search
            v-if="tabIndex === 0"
            v-model="searchValue"
            class="searchCity"
            :placeholder="$t('kSelectPop.searchKey')"
            @update:model-value="valueChange(tabIndex)"
          />
        </template>
      </van-cascader>
    </van-popup>
  </div>
</template>

<script>
// 导入时区弹窗
import kTimezone from "@/components/commom/kTimezone/index.vue";
// 导入接口
import { getAdmin } from "@/service/merchantManage";
import { updateAdmin } from "@/service/merchantManage";
import { onMounted, reactive, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import {
  getLocal,
  getLoginUser,
  $M_EmailAvailable,
  $M_PhoneTest,
} from "@/common/js/utils";
import { useRouter } from "vue-router";
import {
  tAdminGetRelation,
  updatePayPlatform,
  updateDIYPassword,
  updateOrderNotice,
  updateOnOffNotice,
  getAreaById,
  updateArea,
  getCitiesById,
} from "@/service/user";
import {
  showFailToast,
  showToast,
  showSuccessToast,
  showConfirmDialog,
} from "vant";
import { useI18n } from "vue-i18n";
import { countriesData } from "@/common/js/countries";
import { countriesDataEn } from "@/common/js/countries-en";
import { useCascaderAreaData } from "@vant/area-data";

export default {
  components: { sHeader, kTimezone },
  setup() {
    let languageName = ref(getLocal("curLang"));
    // 引入语言
    const { t } = useI18n();
    // 账户信息
    const accountDetail = ref({});
    // 控制地区显示隐藏
    const areaShow = ref(true);
    // 控制手机显示隐藏
    const phoneNumberShow = ref(true);
    // 控制邮箱显示隐藏
    const mailboxShow = ref(true);
    // 控制货币显示隐藏 货币符号，默认“￥”
    const symbolShow = ref(true);
    // 控制DIY使用密码显示隐藏
    const diyPasswordShow = ref(true);
    // 控制时区显示隐藏
    const timezoneShow = ref(true);
    // 控制切换支付平台按钮显示隐藏
    const chaSzPayShow = ref(false);
    const chaScPayShow = ref(false);

    const diyPassword = ref("");

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

    // 订单通知开关状态
    const orderNotice = ref(false);
    // 设备上/离线通知开关状态
    const onOffNotice = ref(false);
    // 弹窗省市
    const showArea = ref(false);
    const areaOptions = ref();
    // 弹窗国家
    const showCountry = ref(false);
    const countryOptions = ref(
      languageName.value == "zh" ? countriesData : countriesDataEn
    );

    // 弹窗控制
    const clickShowArea = () => {
      if (user.ifForeign == 0) {
        showArea.value = true;
      } else {
        showCountry.value = true;
      }
    };

    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,
      timeZone: accountDetail.value.timeZone,
    });
    //
    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;
          diyPasswordShow.value = true;
          timezoneShow.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;
          diyPasswordShow.value = true;
          timezoneShow.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;
          diyPasswordShow.value = true;
          timezoneShow.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;
          diyPasswordShow.value = true;
          timezoneShow.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;
          diyPasswordShow.value = true;
          timezoneShow.value = true;
          break;
        case 6:
          cofficentForm.currencySymbol = accountDetail.value.currencySymbol;
          relationType.value = true;
          mailboxShow.value = true;
          phoneNumberShow.value = true;
          areaShow.value = true;
          symbolShow.value = true;
          diyPasswordShow.value = !diyPasswordShow.value;
          timezoneShow.value = true;
          break;
        case 7:
          cofficentForm.timeZone = accountDetail.value.timeZone;
          relationType.value = true;
          mailboxShow.value = true;
          phoneNumberShow.value = true;
          areaShow.value = true;
          symbolShow.value = true;
          diyPasswordShow.value = true;
          timezoneShow.value = !timezoneShow.value;
          break;
      }
    };

    // 点击邮箱的确定按钮
    const mailboxChg = async (e, idx) => {
      switch (idx) {
        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;
        case 3:
          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 5:
          if (!e) {
            showToast(t("user.currencySymbolPlace"));
          } else {
            const params = {
              id: user.id,
              currencySymbol: e,
            };
            const { data } = await updateAdmin(params);
            symbolShow.value = true;
            if (data.code === "00000") {
              showToast(data.message);
              // 更新本地存储缓存中的currencySymbol的值
              user.currencySymbol = e; // 将新的currencySymbol的值赋值给user
              localStorage.setItem("loginUser", JSON.stringify(user));
              setTimeout(() => {
                getAcccountDetail();
              }, 1000);
            }
          }
          break;
        case 6:
          if (!e) {
            showToast(t("user.diyPasswordPlace"));
          } else {
            const params = {
              diyPassword: e,
            };
            const { data } = await updateDIYPassword(params);
            diyPasswordShow.value = true;
            if (data.code === "00000") {
              showToast(t("user.changeSuccess"));
              setTimeout(() => {
                getAcccountDetail();
              }, 1000);
            }
          }
          break;
      }
    };
    // 地区ID
    const areaId = ref(null);
    // 获取账户详情
    const getAcccountDetail = async () => {
      getAdmin({ id: user.id }).then((res) => {
        accountDetail.value = res.data.data;
        if (
          accountDetail.value.areaId != null &&
          accountDetail.value.type == 2
        ) {
          areaId.value = accountDetail.value.areaId;
          // 查询地址回显
          if (accountDetail.value.ifForeign == "0") {
            getArea();
          } else {
            getCities();
          }
        }
        if (accountDetail.value.orderNotice == "1") {
          orderNotice.value = true;
        }
        if (accountDetail.value.onOffNotice == "1") {
          onOffNotice.value = true;
        }
        // 查询时区回显
        kTimezoneRef.value.init(accountDetail.value.timeZone);
      });
    };
    // 获取申泽支付平台
    const getSunzeeDetail = () => {
      getAdmin({ id: 2738 }).then((res) => {
        // sunzeePay.value = res.data.data.payPlatform;
        if (res.data.data.payPlatform == "1") {
          sunzeePay.value = true;
        }
      });
    };
    // 获取七云支付平台
    const getSevenCloudDetail = () => {
      getAdmin({ id: 2739 }).then((res) => {
        // sevencloudPay.value = res.data.data.payPlatform;
        if (res.data.data.payPlatform == "1") {
          sevencloudPay.value = true;
        }
      });
    };
    // 点击右侧按钮
    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);
      }
    };
    //切换申泽支付平台
    const changeSunzeePay = (value) => {
      showConfirmDialog({
        title: t("user.tips"),
        message: t("user.changeTips"),
      })
        .then(() => {
          params.id = 2738;
          if (value) {
            params.payPlatform = "1";
          } else {
            params.payPlatform = "0";
          }
          const { data } = updatePayPlatform(params);
          if (data.code) {
            showSuccessToast(t("user.changeSuccess"));
            sunzeePay.value = value;
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };
    //切换七云支付平台
    const changeSevenCloudPay = (value) => {
      showConfirmDialog({
        title: t("user.tips"),
        message: t("user.changeTips"),
      })
        .then(() => {
          params.id = 2739;
          if (value) {
            params.payPlatform = "1";
          } else {
            params.payPlatform = "0";
          }
          const { data } = updatePayPlatform(params);
          if (data.code) {
            showSuccessToast(t("user.changeSuccess"));
            sunzeePay.value = value;
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };
    // 切换订单通知开关
    const changeOrderNotice = (value) => {
      showConfirmDialog({
        title: t("user.tips"),
        message: orderNotice.value
          ? t("user.closeOrderNotice")
          : t("user.openOrderNotice"),
      })
        .then(async () => {
          const params = reactive({
            adminId: user.id,
            orderNotice: value ? "1" : "0",
          });
          const { data } = await updateOrderNotice(params);
          if (data.code == "00000") {
            showSuccessToast(
              value ? t("user.openSuccess") : t("user.closeSuccess")
            );
            orderNotice.value = value;
          } else if (data.code == "A0001") {
            showToast(t("user.pleaseBindWechat"));
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };

    // 切换设备通知开关
    const changeOnOffNotice = (value) => {
      showConfirmDialog({
        title: t("user.tips"),
        message: onOffNotice.value
          ? t("user.closeOnOffNotice")
          : t("user.openOnOffNotice"),
      })
        .then(async () => {
          const params = reactive({
            adminId: user.id,
            onOffNotice: value ? "1" : "0",
          });
          const { data } = await updateOnOffNotice(params);
          if (data.code == "00000") {
            showSuccessToast(
              value ? t("user.openSuccess") : t("user.closeSuccess")
            );
            onOffNotice.value = value;
          } else if (data.code == "A0001") {
            showToast(t("user.pleaseBindWechat"));
          } else {
            showFailToast(data.message);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };
    // 初始化页面获取列表
    onMounted(async () => {
      // 加载样式
      if (localStorage.getItem("loginSys")) {
        const loginSysString = localStorage.getItem("loginSys");
        sys.value = JSON.parse(loginSysString);
      }
      // 获取关联上级
      gettAdminGetRelation();
      // 获取账户
      getAcccountDetail();
      if (user.type == 0) {
        chaSzPayShow.value = true;
        chaScPayShow.value = true;
        getSunzeeDetail();
        getSevenCloudDetail();
      }
      // 省市选择器
      const areaData = useCascaderAreaData();
      areaData.forEach((province) => {
        province.children.forEach((city) => {
          // 删除城市中的区级信息
          delete city.children;
        });
      });
      // 删除台湾、澳门和香港
      const provincesToRemove = ["710000", "810000", "820000"];
      areaOptions.value = areaData.filter(
        (province) => !provincesToRemove.includes(province.value)
      );
    });
    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 = () => {
      showConfirmDialog({
        title: t("user.tips"),
        message: t("user.logOutContent"),
      })
        .then(() => {
          // 获取缓存的语言
          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);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    };
    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 fullName = ref("");
    const name = ref("");
    // 国内省市
    const getArea = async () => {
      try {
        const { data } = await getAreaById({
          areaId: areaId.value,
        });
        if (data.code === "00000") {
          fullName.value = data.data.fullName;
          name.value = data.data.name;
          if (fullName.value != name.value) {
            fullName.value = fullName.value.replace(name.value, "").trim();
            fullName.value = fullName.value + "/" + name.value;
          }
          fieldValue.value = fullName.value;
        }
      } catch (error) {
        console.error(error);
      }
    };
    const countryValue = ref("");
    const cityValue = ref("");
    // 国外城市
    const getCities = async () => {
      try {
        const { data } = await getCitiesById({
          areaId: areaId.value,
        });
        if (data.data != "") {
          const citiesCode = data.data.split("/")[0];
          const countriesCode = data.data.split("/")[1];
          countryOptions.value.find((item) => {
            if (item.value === countriesCode) {
              countryValue.value = item.text;
              item.children.find((item) => {
                if (item.value === citiesCode) {
                  cityValue.value = item.text;
                }
              });
            }
          });
          if (countryValue.value == cityValue.value) {
            fieldValue.value = cityValue.value;
          } else {
            fieldValue.value = countryValue.value + "/" + cityValue.value;
          }
        }
      } catch (error) {
        console.error(error);
      }
    };

    // 地区弹窗
    const fieldValue = ref("");
    // 地区参数值
    const areaValue = ref("");
    const onConfirmArea = async ({ selectedOptions }) => {
      if (selectedOptions[0]?.text == selectedOptions[1]?.text) {
        fieldValue.value = selectedOptions[0]?.text;
        if (user.ifForeign === "1") {
          areaValue.value = selectedOptions[1]?.value;
        } else {
          areaValue.value = selectedOptions[0]?.text;
        }
      } else {
        fieldValue.value =
          selectedOptions[0]?.text + "/" + selectedOptions[1]?.text;
        if (user.ifForeign === "1") {
          areaValue.value = selectedOptions[1]?.value;
        } else {
          areaValue.value = selectedOptions[0]?.text + selectedOptions[1]?.text;
        }
      }
      const params = {
        adminId: user.id,
        areaValue: areaValue.value,
      };
      const { data } = await updateArea(params);
      if (data.code === "00000") {
        getAcccountDetail();
      }

      showArea.value = false;
      areaShow.value = true;
    };
    const onConfirmCountry = async ({ selectedOptions }) => {
      if (selectedOptions[0]?.text == selectedOptions[1]?.text) {
        fieldValue.value = selectedOptions[1]?.text;
      } else {
        fieldValue.value = selectedOptions
          .map((option) => option.text)
          .join("/");
      }
      areaValue.value = selectedOptions[1]?.value;
      const params = {
        adminId: user.id,
        areaValue: areaValue.value,
      };
      const { data } = await updateArea(params);
      if (data.code === "00000") {
        getAcccountDetail();
      }
      showCountry.value = false;
      areaShow.value = true;
    };
    // 时区弹窗
    const tzFieldValue = ref("");
    const kTimezoneRef = ref(null);
    // 点击时区输入框
    const tzFieldValueInpClk = () => {
      kTimezoneRef.value.openPopup();
    };
    // 选择时区完成
    const timezonePopFinish = async (e) => {
      tzFieldValue.value = e.selectName;
      accountDetail.value.timeZone = e.selectId;
      const params = {
        id: user.id,
        timeZone: e.selectId,
      };
      const { data } = await updateAdmin(params);
      timezoneShow.value = true;
      if (data.code === "00000") {
        showToast(data.message);
        setTimeout(() => {
          getAcccountDetail();
        }, 500);
      }
    };

    const timezoneShowPicker = ref(false);
    const timezoneOnConfirm = ({ selectedOptions }) => {
      timezoneShowPicker.value = false;
      tzFieldValue.value = selectedOptions[0].text;
    };

    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 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);
        if (userIfForeign.ifForeign === "1") {
          isAbroad.value = true;
          isInland.value = false;
        }
      } catch (error) {
        console.error(error);
      }
    };

    onMounted(() => {
      checkInWechat();
      checkIsAbroad();
      haveRelationCheck();
    });
    // 获取时区回显的值
    const getTimezone = (e) => {
      tzFieldValue.value = e;
    };

    // 搜索关键词
    const searchValue = ref("");
    const countryData = ref(
      languageName.value == "zh" ? countriesData : countriesDataEn
    );
    // 搜索数据
    const valueChange = (index) => {
      let tempOptions = [];
      if (searchValue.value) {
        if (index === 0) {
          // 国家
          countryData.value.forEach((item) => {
            if (item.text.includes(searchValue.value)) {
              tempOptions.push(item);
            }
          });
          countryOptions.value = tempOptions;
        }
      } else {
        countryOptions.value = countryData.value;
      }
    };
    return {
      user,
      operUnipay,
      onperExitSys,
      relationAdminName,
      relationType,
      pushPageList,
      roleCheck,
      sys,
      confirmClk,
      mailboxShow,
      mailboxChg,
      phoneNumberShow,
      editClk,
      cofficentForm,
      params,
      areaShow,
      timezoneShow,
      accountDetail,
      fieldValue,
      tzFieldValue,
      kTimezoneRef,
      tzFieldValueInpClk,
      // areaPopFinish,
      timezonePopFinish,
      timezoneShowPicker,
      isInWeChat,
      getTimezone,
      isAbroad,
      haveRelation,
      checkIsAbroad,
      isInland,
      symbolShow,
      chaSzPayShow,
      chaScPayShow,
      diyPasswordShow,
      diyPassword,
      sunzeePay,
      sevencloudPay,
      changeSunzeePay,
      changeSevenCloudPay,
      orderNotice,
      changeOrderNotice,
      onOffNotice,
      changeOnOffNotice,
      timezoneOnConfirm,
      clickShowArea,
      showArea,
      areaOptions,
      onConfirmArea,
      showCountry,
      countryOptions,
      onConfirmCountry,

      searchValue,
      valueChange,
    };
  },
};
</script>

<style lang="less" scoped>
@blue: #4d6add;
@primary-color: #4d6add;
@text-secondary: #666;
.userPage {
  background: #f5f6f7;
  min-height: 100vh;

  .card-style() {
    // 卡片公共样式
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 12px;
    padding: 16px;
  }

  .userPageBox {
    height: calc(100% - 95px);
    overflow: auto;
    overflow-x: hidden;
    .userBaseBox,
    .commonOperBox {
      margin: 10px;
      .card-style();

      .baseRow {
        margin-bottom: 20px;
        .group2 {
          width: 4px;
          height: 18px;
          background: @primary-color;
          border-radius: 2px;
          margin-right: 12px;
        }
        .baseText {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }
      }

      .userMessage {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f5 100%);
        border-radius: 8px;
        margin: 10px 0;

        .userId {
          flex: 0 0 45%; // 控制两侧宽度
          text-align: center;
          padding: 0 5px;
          white-space: nowrap;

          .infoValue {
            font-size: 15px;
            font-weight: 600;
            color: @primary-color;
            margin-bottom: 6px;
            
          }

          .infoLabel {
            font-size: 12px;
            color: @text-secondary;
            letter-spacing: 0.5px;
          }
        }

        .verticalDivider {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          width: 1px;
          height: 40px;
          background: linear-gradient(
            180deg,
            rgba(200, 200, 200, 0) 0%,
            rgba(200, 200, 200, 1) 50%,
            rgba(200, 200, 200, 0) 100%
          );
        }

        // 添加伪元素强化分割线效果
        &::before {
          content: "";
          position: absolute;
          left: 50%;
          top: 0;
          bottom: 0;
          width: 2px;
          background: rgba(255, 255, 255, 0.5);
          transform: translateX(-50%);
        }
      }

      .userInfoBox {
        background: #ffffff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        padding: 0 16px;

        // 公共项样式
        .userInfo {
          display: flex;
          align-items: center;
          padding: 16px 0;
          border-bottom: 1px solid #f0f3f5;

          &:last-child {
            border-bottom: none;
          }

          .userInfoLeft {
            flex: 0 0 120px;
            color: #606266;
            font-size: 14px;
            font-weight: 500;
          }

          // 编辑图标
          .editIcon {
            color: @primary-color;
            font-size: 18px;
            margin-left: 12px;
            cursor: pointer;
            transition: opacity 0.3s;

            &:hover {
              opacity: 0.8;
            }
          }

          // 输入框区域
          .cust_vantBorder {
            flex: 1;
            margin: 0 12px;

            .van-cell {
              padding: 8px 12px;
              background: #f8fafb;
              border-radius: 6px;
              border: 1px solid #e4e7ed;

              &::after {
                display: none;
              }

              .van-field__control {
                color: #303133;
              }

              .van-icon {
                color: #c0c4cc;
              }
            }
          }

          // 带按钮的输入框
          .relationClass {
            .van-button {
              height: 32px;
              padding: 0 16px;
              border-radius: 6px;
              background: @primary-color;
              border: none;
              font-size: 13px;
              transition: all 0.3s;

              &:active {
                opacity: 0.9;
                transform: scale(0.98);
              }
            }
          }

          // 开关样式
          .van-switch {
            transform: scale(0.9);
          }

          // 状态显示文字
          > span:not(.userInfoLeft) {
            flex: 1;
            color: #303133;
            font-size: 14px;
            padding: 0 12px;
            word-break: break-word;
          }

          // 支付平台切换
          &[v-if*="PayShow"] {
            .cust_vantBorder {
              flex: none;
            }

            > span:last-child {
              flex: none;
              color: @text-secondary;
              font-size: 13px;
            }
          }
        }

        // 移动端适配
        @media (max-width: 768px) {
          padding: 0 12px;

          .userInfo {
            padding: 12px 0;
            flex-wrap: wrap;

            .userInfoLeft {
              flex: 1 1 100%;
              margin-bottom: 8px;
            }

            .cust_vantBorder,
            .relationClass {
              flex: 1;
              margin: 0;
            }

            .editIcon {
              margin-left: auto;
            }
          }
        }
      }
    }

    .operListBox {
      .taskListRow {
        padding: 14px 0;
        border-bottom: 1px solid #f0f0f0;

        &:active {
          background-color: #f8f8f8;
        }

        .taskIcon {
          width: 24px;
          height: 24px;
          margin-right: 12px;
          background-size: contain;

          &.commonToolsIcon {
            background-image: url(../assets/home/commonTools.png);
          }
          &.taskMessageIcon {
            background-image: url(../assets/user/taskMessageIcon.png);
          }
          &.joinPayMchIcon {
            background-image: url(../assets/user/joinPayMchIcon.png);
          }
          &.announcementIcon {
            background-image: url(../assets/user/announcementIcon.png);
          }
          &.bindWechatIcon {
            background-image: url(../assets/user/bindWechatIcon.png);
          }
          &.modifyLocIcon {
            background-image: url(../assets/user/modifyLocIcon.png);
          }
          &.syncOldDataIcon {
            background-image: url(../assets/user/syncOldDataIcon.png);
          }
          &.changePasswordIcon {
            background-image: url(../assets/user/changePasswordIcon.png);
          }
          &.feedbackIcon {
            background-image: url(../assets/user/feedback.png);
          }
          &.loginOutIcon {
            background-image: url(../assets/user/loginOut.png);
          }
        }

        .taskRight {
          flex: 1;
          .taskTitle {
            font-size: 15px;
            color: #333;
          }
        }
      }
    }
  }

  // 弹窗样式调整
  .van-popup {
    border-radius: 12px 12px 0 0;
    overflow: hidden;

    .van-cascader__options {
      height: 50vh;
    }

    .searchCity {
      padding: 8px 16px;
      background: #fff;
    }
  }
}

@media (max-width: 768px) {
  .userMessage {
    padding: 16px 0;

    .userId {
      padding: 0 12px;

      .infoValue {
        font-size: 16px;
      }
    }

    .verticalDivider {
      height: 30px;
    }
  }
}
</style>
