<template>
  <div class="login flex flex-col">
    <div class="flex-1 flex items-center justify-center">
      <div class="login-card flex rounded-md">
        <div class="flex-1 h-full hidden md:inline-block">
          <image-contain :src="config.webBackdrop" :width="400" height="100%"/>
        </div>
        <div
            class="login-form bg-body flex flex-col justify-center px-10 py-10 md:w-[400px] w-[375px] flex-none mx-auto"
        >
          <div class="text-center text-3xl font-medium mb-8">{{ config.webName }}</div>
          <div v-if="!showMerchant">
            <el-form ref="formRef" :model="formData" size="large" :rules="rules">
              <el-form-item prop="account">
                <el-input
                    v-model.trim="formData.account"
                    placeholder="请输入账号"
                    @keyup.enter="handleEnter"
                >
                  <template #prepend>
                    <icon name="el-icon-User"/>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                    ref="passwordRef"
                    v-model="formData.password"
                    show-password
                    placeholder="请输入密码"
                    @keyup.enter="handleLogin"
                >
                  <template #prepend>
                    <icon name="el-icon-Lock"/>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <div class="mb-5">
              <el-checkbox v-model="remAccount" label="记住账号"></el-checkbox>
            </div>
            <el-button class="w-80" type="primary" size="large" :loading="isLock" @click="lockLogin">
              登录
            </el-button>
          </div>
          <!-- 商户列表 -->
          <div v-if="showMerchant">
            <el-table
                :data="tableData" class="w-80" height="180"
                highlight-current-row
                highlight-selection-row
                :showHeader="false"
                @current-change="handleCurrentChange">
              <el-table-column
                  prop="name"
                  label="店铺名称">
              </el-table-column>
            </el-table>
            <el-button class="w-80" type="primary" size="large" @click="handleEnterStore" style="margin-top: 15px">
              进入店铺
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <layout-footer/>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref, shallowRef} from 'vue'
import type {FormInstance, InputInstance} from 'element-plus'
import LayoutFooter from '@/layout/components/footer.vue'
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import cache from '@/utils/cache'
import {ACCOUNT_KEY, SHOP_ID} from '@/enums/cacheEnums'
import {PageEnum} from '@/enums/pageEnum'
import {useLockFn} from '@/hooks/useLockFn'
import {getShopConfigList} from "@/api/shop";
import feedback from "@/utils/feedback";
import {clearAuthInfo} from "@/utils/auth";

const passwordRef = shallowRef<InputInstance>()
const formRef = shallowRef<FormInstance>()
const appStore = useAppStore()
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const remAccount = ref(false)
const config = computed(() => appStore.config)
const showMerchant = ref(false)
const currentRow = ref({})
const formData = reactive({
  account: '',
  password: '',
  // code: '',
  uuid: ''
})
const rules = {
  account: [
    {
      required: true,
      message: '请输入账号',
      trigger: ['blur']
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: ['blur']
    }
  ]
}
const tableData = ref([])
const handleCurrentChange = (row: any) => {
  currentRow.value = row
}
const handleEnterStore = () => {
  if (!currentRow.value.id) {
    feedback.msgWarning('请选择一个店铺进入平台')
    return
  }
  if (currentRow.value.id) {
    cache.set(SHOP_ID, currentRow.value.id)
    window.localStorage.setItem("like_admin_houseId", currentRow.value.houseId)
    config.value.webName = currentRow.name
    if(currentRow.image){
      config.value.webLogo = currentRow.image
    }
    const {
      query: {redirect}
    } = route
    const path = typeof redirect === 'string' ? redirect : PageEnum.INDEX
    router.push(path)
  }
}
// 回车按键监听
const handleEnter = () => {
  if (!formData.password) {
    return passwordRef.value?.focus()
  }
  handleLogin()
}
const handleShopConfig = (params: any) => {
  getShopConfigList({"contactTel": formData.account, houseIds: params}).then((res) => {
    if (res && res.length > 0) {
      if (res.length == 1) {
        cache.set(SHOP_ID, res[0].id)
        window.localStorage.setItem("like_admin_houseId",res[0].houseId)
        config.value.webName = res[0].name
        if(res[0].image){
          config.value.webLogo = res[0].image
        }
        const {
          query: {redirect}
        } = route
        const path = typeof redirect === 'string' ? redirect : PageEnum.INDEX
        router.push(path)
      } else {
        showMerchant.value = true
        tableData.value = res.map((item: any) => {
          return {
            id: item.id,
            name: item.name,
            houseId: item.houseId,
            image: item.image
          }
        })
      }
    } else {
      clearAuthInfo()
      router.push(PageEnum.ERROR_403)
    }
  })
}
// 登录处理
const handleLogin = async () => {
  await formRef.value?.validate()
  // 记住账号，缓存
  cache.set(ACCOUNT_KEY, {
    remember: remAccount.value,
    account: formData.account
  })
  try {
    let _data = {
      "mobile": formData.account,
      "passWord": formData.password,
      "platform": 1,//平台 1.大麦数字营销 2.大麦后台 3.麦芽 4.淘房客 5.电商中心
    }
    await userStore.login(_data).then((res: any) => {
      if(res.type === 1){
        clearAuthInfo()
        router.push(PageEnum.ERROR_403)
      } else {
        const houseIds = res.houseList.map((item: any) => item.houseId)
        handleShopConfig(houseIds)
      }
    })
  } catch (error) {
    // getLoginCaptcha()
  }

  /*const {
    query: {redirect}
  } = route
  const path = typeof redirect === 'string' ? redirect : PageEnum.INDEX
  router.push(path)*/
}
const {isLock, lockFn: lockLogin} = useLockFn(handleLogin)

onMounted(() => {
  const value = cache.get(ACCOUNT_KEY)
  // getLoginCaptcha()
  if (value?.remember) {
    remAccount.value = value.remember
    formData.account = value.account
  }
})
</script>

<style lang="scss" scoped>
.login {
  background-image: url('./images/login_bg.png');
  @apply min-h-screen bg-no-repeat bg-center bg-cover;
  .login-card {
    height: 400px;

    :deep(.el-input-group__prepend) {
      padding: 0 15px;
    }
  }
}
</style>
