<template>
  <!-- 商户管理 -->
  <div class="merchantPage flex-col">
    <s-header :name="$t('merchantManage.merchantManagement')" :noback="false"></s-header>
    <div class="merchantBox flex-col">
      <van-list v-model:loading="loading" v-model:error="error" :error-text="$t('public.requestFailed')"
        :finished="finished" :finished-text="$t('public.noMore')" offset="300" :immediate-check="false" @load="onLoad">
        <div class="searchRow flex-row justify-between">
          <div class="flex-col">
            <div class="flex-row justify-between bd3">
              <span class="info2">{{ $t('merchantManage.total') }}</span>
              <span class="info3">{{ adminTotal }}</span>
              <span class="info4">{{ $t('merchantManage.recordsInTotal') }}</span>
            </div>
          </div>
          <div class="flex-col">
            <div class="main5 flex-row justify-between" @click="searchClick">
              <img class="label2" src="../../assets/device/searchIcon.png" />
            </div>
          </div>
        </div>
        <div class="main4 flex-col">
          <div class="bd1 flex-col" v-for="(item, index) in adminList" :key="index">
            <div class="outer2 flex-col">
              <div class="box2 flex-row justify-between">
                <span class="word3" v-html="item.username + '&nbsp;' + item.name"></span>
                <!-- <div class="group6 flex-col"></div> -->
              </div>
              <span class="word4"
                v-html="`${$t('merchantManage.telephone')}：` + (item.phone == null ? '' : item.phone)"></span>
              <span class="word5"
                v-html="`${$t('merchantManage.mailbox')}：` + (item.email == null ? '' : item.email)"></span>
              <span class="word6"
                v-html="`${$t('merchantManage.loginTime')}：` + (item.loginDate == null ? '' : Format_time(item.loginDate))"></span>
              <span class="info6"
                v-html="`${$t('merchantManage.loginIPAddress')}：` + (item.loginIp == null ? '' : item.loginIp)"></span>
              <span class="txt2"
                v-html="`${$t('merchantManage.managementSystemId')}：` + (item.managerId == null ? '' : item.managerId)"></span>
              <div class="box3 flex-col">
                <span class="txt3" v-html="`${$t('merchantManage.creationTime')}：` + Format_time(item.createDate)"></span>
              </div>
              <div class="button-container">
                <van-button v-if="user.type < 2" class="btn1" round type="success"
                  @click="autoLogin(item.id)">切换登陆</van-button>
                <van-button class="btn1" round style="background-color: #2d87c8; border-color: #2d87c8;"  type="primary" @click="merchantSet(item)">详细信息</van-button>
              </div>
            </div>
          </div>
          <van-back-top style="background-color: #2d87c8;" right="3vw" bottom="5vh" />
        </div>
      </van-list>
    </div>
    <merchantSearch ref="searchRef" @search="search($event)"></merchantSearch>
  </div>
</template>
<script>
import { onMounted, reactive, ref } from "vue";
import sHeader from "../../components/SimpleHeader";
import { getAdminList, autoLoginMerchant } from '../../service/merchantManage';
import { getLoginUser, Format_time, styleUrl, setLocal } from "../../common/js/utils";
import { showFailToast, showSuccessToast, showConfirmDialog } from 'vant';
import merchantSearch from './merchantSearch.vue';
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";


export default {
  components: { sHeader, merchantSearch },
  setup() {
    const { t } = useI18n();
    const user = getLoginUser();
    const router = useRouter();
    const searchRef = ref(null);
    const adminList = ref([]);
    const adminTotal = ref(0); // 列表总数
    const loading = ref(false); // 加载状态
    const error = ref(false); // 错误状态
    const finished = ref(false); // 结束翻页状态
    let searchParams = reactive({
      id: user.id,
      current: 1, // 页数
      size: 20, // 页大小
    });
    onMounted(async () => {
      // 加载样式
      styleUrl('merchantManage');
      searchGetList();
    });
    // 查询列表
    const searchGetList = () => {
      adminList.value = [];
      searchParams.current = 1;
      getList();
    }
    // 滚动加载
    const onLoad = () => { if (!finished.value) { searchParams.current = searchParams.current + 1; getList(); } };
    // 获取设备列表数据
    const getList = async () => {
      const { data } = await getAdminList(Object.assign({}, searchParams));
      if (data.code === "00000") {
        // 列表值叠加
        adminList.value = adminList.value.concat(data.data.records);
        adminTotal.value = data.data.total;
        if (adminList.value.length === data.data.total) { finished.value = true; }
        loading.value = false;
      } else { showFailToast(data.message); }
    };
    // 搜索点击
    const searchClick = () => { searchRef.value.showSearch(); };
    // 搜索弹窗触发搜索
    const search = (data) => {
      searchParams = Object.assign(searchParams, data);
      searchGetList();
    };
    // 跳转设备编辑
    const merchantSet = (e) => { router.push({ path: 'merchantSet', query: { merchantId: e.id } }) }
    // 切换登陆
    const autoLogin = (id) => {
      showConfirmDialog({
        title: t('merchantManage.tips'),
        message: t('merchantManage.autoLogin'),
      }).then(() => {
        autoLoginMerchant({ id }).then(res => {
          if (res.data.code === "00000") {
            // 获取缓存的语言
            const curLang = localStorage.getItem("curLang");
            const savedCredentials = localStorage.getItem('savedCredentials');
            // 清空缓存
            localStorage.clear();
            localStorage.setItem("curLang", curLang);
            if (savedCredentials) {
              localStorage.setItem('savedCredentials', savedCredentials);
            }
            setLocal("loginUser", JSON.stringify(res.data.data));
            // console.log('loginUser JSON：', JSON.stringify(data.data));
            showSuccessToast(t('login.loginSucess'));
            // 需要刷新页面，否则 axios.js 文件里的 token 不会被重置
            window.location.href = '/sc/';
            setTimeout(() => {
              router.push("/home");
            }, 200);
          } else {
            showFailToast(res.data.message);
          }
        });
      }).catch((error) => {
        console.error(error);
      })
    }
    return {
      adminList,
      adminTotal,
      loading,
      error,
      finished,
      onLoad,
      searchClick,
      searchRef,
      search,
      merchantSet,
      autoLogin,
      Format_time,
      user,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common.less";
</style>
