<template>
  <view class='u-flex-column'>
    <swiper class='swiper' :indicator-dots='true' :autoplay='true' :interval='3000' :duration='1000'
            @change='swiperChange'>
      <swiper-item v-for='(item, index) in companyConfigInfo?.bannerinx' :key='index'>
        <image :src='item.src||defaultImage' mode='aspectFill' />
      </swiper-item>
    </swiper>

    <view class='basic-view'>
      <view class='indicator-view'>
        <view v-for='(item,index) in companyConfigInfo?.bannerinx' :key='item' class='normal'
              :class="{'active': index === currentBannerIndex}">
        </view>
      </view>

      <view class='user-info-card' @click.stop='goPath("/pages/mine/index")'>
        <image class='user-avatar' :src='userInfo?.image||defaultAvatar' mode='aspectFill' />
        <text class='user-name primary-text-color'>{{ userInfo?.nickName || '点击注册会员' }}</text>
        <view class='integral-view primary-text-color' @click.stop='goPath("/pages/mine/subs/integral/index")'>
          <text>{{ userInfo?.integration || 0 }}</text>
          <text>积分</text>
        </view>
        <view class='divider' style='height: 83rpx' />
        <view class='balance-view' @click.stop='goPath("/pages/mine/subs/recharge/index")'>
          <text class='accent-text-color'>{{ userInfo?.balance || 0 }}</text>
          <text>余额(元)</text>
        </view>
        <view class='divider' style='height: 83rpx' />
        <view class='switch-view' @click.stop='switchCompany'>
          <image :src='assetsUrl("ic_switch_company.png")' />
        </view>
      </view>

      <view class='menu-view'>
        <view @click.stop='goPath("/pages/mine/subs/recharge/index")'>
          <image :src='assetsUrl("ic_member_card2.png")' style='width: 108rpx;height: 72rpx;padding: 11rpx 0' />
          <text>会员充值</text>
        </view>
        <view class='divider' style='margin: 0;height: 153rpx' />
        <view @click.stop='goPath("/pages/mine/subs/coupon/index")'>
          <image :src='assetsUrl("ic_coupon2.png")' style='width: 108rpx;height: 95rpx' />
          <text>优惠券</text>
        </view>
      </view>

      <view class='second-menu-view'>
        <view v-for='(item, index) in submenuList' :key='index'>
          <view class='menu-item' @click='goPath(item.path)'>
            <image :src='item.icon' />
            <text>{{ item.title }}</text>
          </view>
        </view>
      </view>

      <text class='hot-recommend'>热门推荐</text>

      <view class='bottom-banner-view'>
        <swiper :indicator-dots='true' :autoplay='true' :interval='3000' :duration='1000'>
          <swiper-item v-for='(item, index) in companyConfigInfo?.bannerhot' :key='index'>
            <image :src='item.src' mode='aspectFill' />
          </swiper-item>
        </swiper>
      </view>
    </view>
  </view>
  <CompanyDialog ref='companyDialogRef' :companyList='companyList' />
</template>

<script setup lang='ts'>
import CompanyDialog from '@/components/company-dialog.vue';
import { getCompanyList } from '@/api/company';
import { useUserStore } from '@/store';
import { assetsUrl, defaultAvatar, defaultImage } from '@/utils/assets';
import { getCompanyId, goPath, isLogin } from '@/utils';
import { storeToRefs } from 'pinia';
import { UserBean } from '@/store/modules/user/types';

const companyDialogRef = ref();
const userStore = useUserStore();
const { userInfo, companyConfigInfo } = storeToRefs(userStore);
const currentBannerIndex = ref(0);

const submenuList = [
  {
    title: '注册有礼',
    icon: assetsUrl('ic_register_gift2.png'),
    path: '/pages/common/register/reward'
  },
  {
    title: '团购秒杀',
    icon: assetsUrl('ic_groupbuy2.png'),
    path: '/pages/common/groupbuy/index'
  },
  {
    title: '入群有礼',
    icon: assetsUrl('ic_group_gift2.png'),
    path: '/pages/home/subs/group/join'
  }
];
const companyList = ref([]);
const userList = ref<UserBean[]>([]);

onMounted(() => {
  wx.getPrivacySetting({
    success: res => {
      console.log(res); // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
      if(res.needAuthorization) {
        // 需要弹出隐私协议
        // agreementPopupRef.value.show();
      } else {
        // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用隐私接口
      }
    },
    fail: (res) => {
      console.log('fail ', res);
    },
    complete: () => {
    }
  });
});

onLoad((e) => {
  console.log('home load e ', e);
});

onShow(async () => {
  if(isLogin()) {
    // userStore.getProfile();
    if(userInfo.value.maOpenId) {
      fetchCompanyList();
    } else {
      await userStore.getProfile();
    }
  } else {
    // setToken('42ae187265fb4688804fd294cbcf99f1')
  }
});

const switchCompany = () => {
  fetchCompanyList((companyList: any[], userList: any[]) => {
    companyDialogRef.value.show(getCompanyId(),(index: number) => {
      userStore.setUserInfo(userList[index]);
      userStore.setCompanyInfo(companyList[index]);
    });
  });
};

const fetchCompanyList = (fn: any = undefined) => {
  const maOpenId = userInfo.value?.maOpenId || (userList.value.filter((res: UserBean) => res?.maOpenId !== '')[0]?.maOpenId);
  getCompanyList(maOpenId).then(res => {
    companyList.value = res.map((res: { company: any }) => res.company);
    userList.value = res.map((res: { user: any }) => res.user);
    if(fn != undefined && fn instanceof Function) {
      fn(companyList.value, userList.value);
    } else {
      let index = companyList.value.findIndex((res: { id: string }) => res.id === getCompanyId());
      if(index < 0) {
        index = 0;
      }
      userStore.setUserInfo(userList.value[index]);
      userStore.setCompanyInfo(companyList.value[index]);
    }

    // uni.showActionSheet({
    //   itemList: companyList.map((res: { companyName: string }) => res.companyName),
    //   success: (res) => {
    // userStore.setUserInfo(userList[res.tapIndex]);
    // userStore.setCompanyInfo(companyList[res.tapIndex]);
    //   }
    // });
  });
};

const swiperChange = (e: any) => {
  currentBannerIndex.value = e.detail.current;
};
</script>

<style lang='scss'>
.swiper {
  display: flex;
  position: relative;
  width: 100%;
  height: 520rpx;

  image {
    width: 100%;
    height: 520rpx;
  }
}

.basic-view {
  display: flex;
  flex-direction: column;
  position: relative;
  top: -100rpx;
}

.indicator-view {
  display: flex;
  flex-direction: row;
  position: absolute;
  justify-content: center;
  left: 0;
  right: 0;
  top: -20rpx;

  .normal {
    width: 16rpx;
    height: 16rpx;
    background: #707070;
    border-radius: 50%;
    margin: 0 8rpx;
  }

  .active {
    @extend .normal;
    background: #333333;
  }
}

.card {
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  margin: 0 24rpx;
}

.user-info-card {
  @extend .card;
  display: flex;
  flex-direction: row;
  padding: 30rpx;
  align-items: center;
  margin-top: 14rpx;

  .user-avatar {
    width: 88rpx;
    height: 88rpx;
    border-radius: 50%;
  }

  .user-name {
    display: flex;
    flex: 1;
    font-size: 30rpx;
    font-weight: bold;
    margin-left: 16rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-right: 20rpx;
  }

  .integral-view {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    text:nth-child(1) {
      font-size: 36rpx;
      font-weight: bold;
    }

    text:nth-child(2) {
      font-size: 26rpx;
      font-weight: 400;
      margin-top: 10rpx;
    }
  }

  .balance-view {
    @extend .integral-view;

    text:nth-child(1) {
      font-size: 36rpx;
      font-weight: bold;
    }
  }

  .switch-view {
    image {
      width: 50rpx;
      height: 50rpx;
    }
  }
}

.divider {
  margin: 0 30rpx;
  width: 0.5rpx;
  height: 100%;
  background: #C7C7C7;
}

.menu-view {
  @extend .card;
  display: flex;
  flex-direction: row;
  position: relative;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0 32rpx 0;
  margin-top: 20rpx;

  view:not(:nth-of-type(2)):nth-of-type(n+1) {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex: 1;
  }

  text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-top: 16rpx;
  }
}

.second-menu-view {
  @extend .menu-view;

  image {
    width: 88rpx;
    height: 88rpx;
  }

  text {
    font-size: 28rpx;
    color: #333333;
    margin-top: 23rpx;
  }
}

.hot-recommend {
  margin-top: 30rpx;
  margin-left: 24rpx;
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.bottom-banner-view {
  display: flex;
  flex-direction: column;
  margin: 20rpx 24rpx 0 24rpx;
  border-radius: 20rpx;
  height: 285rpx;

  swiper {
    width: 100%;
    height: 100%;

    image {
      width: 100%;
      height: 100%;
      border-radius: 20rpx;
    }
  }
}
</style>
