<script setup>
import { ref, onMounted, computed } from 'vue'
import QrCode from '@/components/QrCode.vue'
import { post } from '@/utils/request'
import { userToken } from '@/composables/config'
import { userApi } from '@/api/user'
import { ucardApi } from '@/api/ucard'
import { customApi } from '@/service/custom'
import useGlobalStore from '@/stores/use-global-store'
import useUserStore from '@/stores/use-user-store'
import useRouter from '@/hooks/useRouter'
import { useI18n } from 'vue-i18n'
import companyLogo from '@/static/images/logo4.png'
import LoginHeaderGroup from './components/LoginHeaderGroup.vue'
import LiveChatService from '@/utils/liveChat.js'
import { useWindowWidth } from '@/composables/useWindowWidth'
const windowWidth = useWindowWidth(300)
const isMobile = computed(() => windowWidth.value <= 991)
const router = useRouter()
const { t } = useI18n()
const userStore = useUserStore()
const globalStore = useGlobalStore()
const modeStore = computed(() => globalStore.mode)
// 响应式表单数据
const form = ref({
  loginName: '',
  password: '',
})

function submit() {
  if (!form.value.loginName) {
    uni.$u.toast(t('signin.form.email'))
    return
  }
  if (!form.value.password) {
    uni.$u.toast(t('signin.form.password'))
    return
  }

  handleLogin()
}

const customStyle = {
  height: '44px',
  'border-radius': '8px',
  background: '#f7f8fa',
  padding: '0 20px !important',
  position: 'relative',
}
const remenber = ref([])
const checkboxChange = (e) => {
  remenber.value = e
}
const fetchUserList = (params) => post('/Login/AcctLogin', params)

async function handleLogin() {
  try {
    const res = await userApi.login({
      loginName: form.value.loginName,
      password: form.value.password,
    })
    if (res.code === 200) {
      userToken.value = res.data
      uni.$u.toast(t('login.msg0_1'))
      getCustomLoginInfo()
      // getCardUserInfo();
      reasonsRefusalList()
      if (remenber.value.length) {
        userStore.saveAccountInfo({
          loginName: form.value.loginName,
          password: form.value.password,
          rememberPassword: true,
        })
      } else {
        userStore.saveAccountInfo({
          loginName: '',
          password: '',
          rememberPassword: false,
        })
      }
      //  console.log(1111);
    } else {
      uni.showToast({ title: res.msg })
      //  console.log(12112);
    }
  } catch (error) {
    // console.log(error)
    uni.showToast({ title: error.msg, icon: 'none' })
    //  console.log(error, 19089);
  }
}

async function getCustomLoginInfo() {
  try {
    const res = await userApi.getUserInfo()
    userStore.saveUserInfo(res.data)
    uni.$emit('updateSystemList', 'login')
    if (res.code === 200) {
      switch (modeStore.value) {
        case 'customer':
          router.reLaunch('/pages/customer/index')
          break;
        case 'ib':
          router.reLaunch('/pages/ib/index')
          break;
        case 'follow':
          router.reLaunch('/pages/follow/index')
          break;

        default:
          break;
      }
    } else {
      uni.$u.toast(res.msg || t('login.msg0'))
    }
  } catch (error) {
    //  console.log(error, 111);
  }
}

async function getCardUserInfo() {
  try {
    const res = await ucardApi.getSingle()
    userStore.saveUserInfo(res.data)
    if (res.code === 200) {
      if (!res.data || res.data.approveStatus != 2) {
        router.push('/pages/mine/improve')
      } else {
        router.push('/pages/card/index')
      }
    } else {
      uni.$u.toast(res.msg || t('login.msg0'))
    }
  } catch (error) {
    //  console.log(error, 111);
  }
}

async function reasonsRefusalList() {
  try {
    const res = await customApi.reasonsRefusalList()
    if (res.code === 200) {
      pickFields(res.data)
    } else {
      uni.$u.toast(res.msg || t('login.msg0'))
    }
  } catch (error) {
    //  console.log(error, 111);
  }
}

function pickFields(source, fields = ['content', 'enContent']) {
  const result = {}

  Object.entries(source).forEach(([key, value]) => {
    result[key] = fields.reduce((acc, f) => {
      acc[f] = value[f] ?? null
      return acc
    }, {})
  })
  userStore.saveReasonsOptions(result)
}
const init = ref(false)
onMounted(() => {
  console.log('kaiaaa')
  if (init.value)return
  init.value = true
  uni.$emit('updateSystemList','login')
  const accountInfo = userStore.accountInfo
  if (accountInfo?.rememberPassword) {
    form.value.loginName = accountInfo?.loginName || ''
    form.value.password = accountInfo?.password || ''
    remenber.value = ['记住我']
  } else {
    form.value.loginName = ''
    form.value.password = ''
    remenber.value = []
  }
})
const inputType = ref('password')
const isChatIconExpanded = ref(false)
// 处理聊天图标点击
const handleChatIconClick = () => {
  // 如果还没显示 → 先滑出来
  if (!isChatIconExpanded.value) {
    isChatIconExpanded.value = true
    return
  }
  if (isMobile.value) {
    router.push('/pages/common/chat')
  } else {
    if (LiveChatService) {
      LiveChatService.showChat();
    }
  }
  setTimeout(() => {
    isChatIconExpanded.value = false
  }, 300)
}
</script>

<template>
  <view class="login-page" :isHeaderFixed="true" :isLoginPage="true">

    <view class="fixed" />
    <view class="main-content">
      <cwg-match-media :min-width="991">
        <view class="global-header-bar pc-header">
          <view class="header-inner">
            <view class="logo-placeholder"></view> <!-- 左侧可预留放logo或留空 -->
            <LoginHeaderGroup text-color="#fff" icon-color="#fff" />
          </view>
        </view>
      </cwg-match-media>

      <!-- 移动端顶部栏：悬浮在上方，深色文字 -->
      <cwg-match-media :max-width="991">
        <view class="mobile-header-bar">
          <!--          <view class="fixed"/>-->

          <LoginHeaderGroup text-color="#141d22" icon-color="#141d22" />
        </view>
      </cwg-match-media>

      <uni-row class="demo-uni-row">
        <cwg-match-media :min-width="991">
          <uni-col :xs="24" :sm="24" :md="12" :lg="14" :xl="16">
            <view class="left-bg">
              <view class="left-box">
                <view class="inner">
                  <view class="section-title">
                    <text class="bg-secondary-opacity subtitle w-40" v-t="'newLoop.item11'"></text>
                  </view>
                  <view class="title w-700">
                    {{ `${t('newLoop.item12')} ` }}
                    <text class="color-white" v-t="'newLoop.item13'"></text>
                  </view>
                  <view class="text-white" v-t="'newLoop.item14'"></view>
                </view>
                <image src="/static/images/trust-pilot.png" class="img-fluid mt--10" mode="widthFix"></image>
                <view class="left-content">
                  <view class="des text-white">
                    <text v-html="t('newSignin.item12')"></text>
                    <br />
                    <text v-html="t('newSignin.item12_1')"></text>
                    <br />
                    <text v-html="t('newSignin.item10')"></text>
                    <br />
                    <text v-html="t('newSignin.item11')"></text>
                    <br />
                    <text v-t="'newSignin.item13'"></text>
                    <cwg-link type="pdf" :title="'newSignin.item13_1'"
                      :url="`pdf/Risk-Disclosures-and-Acknowledgements-2020-08.pdf`" target="_blank"
                      v-t="'newSignin.item13_1'" class="doc-link" />
                    <text v-t="'newSignin.item13_2'"></text>
                    <!-- <view v-t="'newSignin.item13_3'"></view>
                    <text v-t="'newSignin.item13_4'"></text> -->
                  </view>
                </view>
              </view>
            </view>
          </uni-col>
        </cwg-match-media>
        <uni-col :xs="24" :sm="24" :md="12" :lg="10" :xl="8" class="right-f">
          <view class="account">
            <cwg-match-media :max-width="991">
              <view class="company u-flex-y u-flex-y-center">
                <image src="/static/images/logo-full.svg" class="company-icon" mode="widthFix"></image>
              </view>
            </cwg-match-media>
            <view class="title">
              <view class="tit1">{{ t('newSignin.item1') }}</view>
              <view class="tit2">{{ t('newSignin.item2') }}</view>
            </view>
            <view>
              <up-form :model="form" ref="uFormRef">
                <up-form-item label="" prop="loginName">
                  <up-input :customStyle="customStyle" v-model="form.loginName" border="none"
                    :placeholder="t('signin.form.email')">
                    <template #prefix>
                      <cwg-icon name="email-outline" :size="20" color="#000" />
                    </template>
                  </up-input>
                </up-form-item>

                <up-form-item label="" prop="password">
                  <up-input :customStyle="customStyle" v-model="form.password" :type="inputType" border="none"
                    :placeholder="t('signin.form.password')">
                    <template #prefix>
                      <cwg-icon name="lock-outline" :size="20" color="#000" />
                    </template>
                  </up-input>
                </up-form-item>
              </up-form>
            </view>
            <view class="u-flex u-flex-between u-flex-y-center mb1">
              <view class="check-box">
                <up-checkbox-group v-model="remenber" @change="checkboxChange">
                  <up-checkbox size="14" labelSize="14" labelColor="#666666" activeColor="#ea002a"
                    :label="t('newSignin.item5')" name="记住我" class="wcg-checkbox"></up-checkbox>
                </up-checkbox-group>
              </view>
              <navigator url="/pages/login/reset" class="account-tip">
                <text>{{ t('signin.forget') }}</text>
              </navigator>
            </view>
            <view class="cwg-button">
              <u-button type="primary" class="" @click="submit">
                {{ t('signin.login') }}
              </u-button>
            </view>
            <navigator url="/pages/login/regist" class="account-tip">
              {{ t('signin.words') }}
              <text>{{ t('signin.signup') }}</text>
            </navigator>
            <cwg-match-media :min-width="791">


              <!-- <view class="qr-container">
                <view class="qr-title">
                  <view class="line"></view>
                  <view class="qr-tit2">{{ t('newSignin.item2') }}</view>
                  <view class="line"></view>
                </view>
                <QrCode width="200" height="200" text="cardGuide" :logo="logoImage"></QrCode>
              </view> -->
            </cwg-match-media>
          </view>
        </uni-col>
      </uni-row>
    </view>
    <view class="chat-icon" :class="{ 'chat-icon-expanded': isChatIconExpanded, 'chat-icon-hidden': type == 'chat' }"
      @click="handleChatIconClick">
      <cwg-icon name="chat" color="#fff" />
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "@/uni.scss";

:deep(uni-content) {
  padding-left: 0 !important;
}

.login-page {
  height: 100vh;
  border: none;
  padding: 0;
  position: relative;
  display: flex;
  flex-direction: column;
}

.chat-icon {
  width: px2rpx(50);
  height: px2rpx(50);
  border-radius: 50%;
  background-color: #cf1322;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  bottom: px2rpx(25);
  right: px2rpx(-25);
  z-index: 999;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 px2rpx(8) px2rpx(20) rgba(0, 0, 0, 0.15);
  will-change: transform;
}

.chat-icon:hover {
  transform: scale(1.1);
}

.chat-icon-expanded {
  bottom: px2rpx(20);
  right: px2rpx(20);
  transform: scale(1.1);
  box-shadow: 0 px2rpx(12) px2rpx(30) rgba(0, 0, 0, 0.2);
}

.chat-icon-hidden {
  display: none;
}

.fixed {
  width: 100%;
  height: var(--status-bar-height);
  background-color: var(--color-white);
  z-index: 9;
}

.global-header-bar {
  width: 100%;
  height: px2rpx(60);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  z-index: 100;

  &.pc-header {
    background-color: transparent;
  }

  .header-inner {
    width: 100%;
    padding: 0 5%;
    display: flex;
    justify-content: space-between;
    /* 两端对齐，可放logo和组件 */
    align-items: center;
  }
}

.mobile-header-bar {
  //position: absolute;
  //top: px2rpx(20);
  //right: px2rpx(20);
  z-index: 10;
  width: 100%;
  display: flex;
  background-color: var(--color-white);
  justify-content: flex-end;
}

.main-content {
  flex: 1;
  overflow: hidden;
  background-image: url(/static/images/login-bg.jpeg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}

.demo-uni-row {
  height: 100%;
  margin: 0 !important;

  .left-bg {
    height: 100%;
    min-height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .left-box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      width: 60%;
      //margin-top: px2rpx(20);

      .inner {
        width: 100%;
        text-align: start;
        margin-bottom: px2rpx(20);

        .section-title {
          margin-top: px2rpx(10);
          margin-bottom: px2rpx(10);
        }


        .title {
          font-size: px2rpx(50);
          line-height: 1;
          color: #fff;
          font-weight: 700;
          text-align: left;
        }

        .w-700 {
          font-weight: 700;
        }

        .subtitle {
          width: 45%;
          font-size: px2rpx(18);
          letter-spacing: px2rpx(1);
          display: block;
          margin-bottom: px2rpx(24);
          color: #ffffff;
          line-height: px2rpx(15);
          font-weight: 500;
          padding: px2rpx(10) px2rpx(20);
          border-radius: px2rpx(100);
          text-transform: uppercase;
          background-color: #e61f1e;
          text-align: center;
        }

        .w-40 {
          max-width: 40%;
        }

        .text-white {
          margin-top: px2rpx(10);
          font-size: px2rpx(14);
          line-height: 1.6;
          color: #fff;
        }
      }

      .img-fluid {
        width: 100%;
        max-width: px2rpx(240);
      }

      .mt--10 {
        margin-top: px2rpx(10);
      }

      .h1 {
        // text-align: center;
        color: #fff;
        font-size: 30px;
        margin-top: 30px;
        line-height: 1.5;
      }

      .h6 {
        text-align: start;
        line-height: 20px;
        color: #fff;
        font-size: 14px;
        margin-top: 10px;
      }

      .company {
        padding: px2rpx(10) 0 px2rpx(10) 0;
        position: relative;
        align-items: flex-start !important;
        width: 100%;
      }
    }

    .left-content {
      width: 100%;

      .des {
        text-align: start;
        line-height: 24px;
        color: #fff;
        font-size: 14px;
        margin-top: px2rpx(20);

        :nth-child(n) {
          display: inline;
          word-break: break-all;
          word-wrap: break-word;
        }

        .doc-link {
          color: var(--color-error);
          text-decoration: underline;
          margin: 0 px2rpx(4);
        }
      }
    }
  }

  .right-f {
    background-color: var(--color-white);
    padding: 0 px2rpx(24);
    height: 100%;
    box-sizing: border-box;

    .account {
      background-color: var(--color-white);
      position: relative;
      height: calc(100vh - 120px);
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 0 10%;

      .company {
        padding: px2rpx(50) 0 px2rpx(20) 0;
        position: relative;
        align-items: center !important;
      }

      .company-icon {
        width: px2rpx(234);
      }
    }
  }
}

.bottom-box {
  width: 100%;
  height: 60px;
  background-color: var(--color-white);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #000;

  .bottom-title {

    text-align: center;
    font-size: px2rpx(14);
    font-weight: 500;
    line-height: 1.5;
    color: #666666;

  }

  .ellipsis {
    width: px2rpx(200);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .cwg-button {
    width: 120px !important;
    padding: px2rpx(4) 0 !important;
  }
}


button {
  background-color: #ea002a;
  font-size: px2rpx(14);
  font-weight: normal;
  height: px2rpx(44);
  line-height: px2rpx(44);
}

.right-f .account .company {
  padding: px2rpx(50) 0 px2rpx(200) 0;
  position: relative;
  align-items: flex-start !important;
}

.logo {
  margin-left: px2rpx(48);
}

.left-bg .company-icon {
  width: px2rpx(234);
}

.left-bg .left-content {
  position: relative;
  z-index: 1;
}

.title {
  margin: px2rpx(32) 0;
  font-size: px2rpx(24);
  font-weight: bolder;
  color: #e4e4e4;
  text-align: center;

  i {
    margin-right: px2rpx(10);
  }

  .tit1 {
    font-size: px2rpx(34);
    line-height: 1.5;
    font-weight: bold;
    color: #000000;
  }

  .tit2 {
    font-size: px2rpx(16);
    line-height: 1.5;
    color: #cecece;
    font-weight: 500;
  }
}

.qr-title {
  font-size: px2rpx(16);
  line-height: 1.5;
  color: #cecece;
  font-weight: 500;
  text-align: center;
  margin: px2rpx(40) 0;
  display: flex;
  align-items: center;
  justify-content: center;

  .line {
    flex: 1;
    height: 1px;
    background-color: #e4e4e4;
  }

  .qr-tit2 {
    margin: 0 px2rpx(12);

  }

}

.input {
  height: px2rpx(44);
  border-radius: px2rpx(8);
  background: #f7f8fa;
  padding: 0 px2rpx(20) !important;
  position: relative;
}

.account-icon {
  width: px2rpx(12);
  height: px2rpx(14) !important;
  margin-right: px2rpx(5);
}

:deep(.u-input__content__prefix-icon) {
  height: px2rpx(20);
}

.regiset-btn {
  margin: px2rpx(20) 0;
}

.account-tip {
  color: #666666;
  font-size: px2rpx(14);
  text-align: center;

  text {
    color: #ea002a;
  }
}

:deep(.u-form-item__body) {
  padding: 0 !important;
  padding-bottom: px2rpx(24) !important;
}

:deep(.wcg-checkbox) {
  padding: 0 !important;
}

.cwg-button {
  padding: px2rpx(34) 0 !important;
}
</style>
