<template>
  <div class="login-container">
    <div class="logo">
      <el-image :src="logo" style="width: 180px"></el-image>
    </div>
    <div class="form-wrap">
      <div style="flex: 1">
        <!-- <div class="reg-wrap">
        <router-link :to="{ name: 'register' }">
          <el-link type="primary">注册</el-link>
        </router-link>
      </div> -->
        <div class="header">
          <span class="t1">银收客</span>
          <span class="t2">收银、库存、营销、支付等业务一体化解决方案</span>
        </div>
        <el-form ref="formRef" :model="form" :rules="rules" label-position="top" hide-required-asterisk>
          <el-form-item>
            <el-radio-group v-model="form.loginType">
              <el-radio-button label="商户" :value="0"></el-radio-button>
              <el-radio-button label="员工" :value="1"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商户号" prop="username">
            <el-input v-model="form.username" placeholder="请输入商户号"></el-input>
          </el-form-item>
          <el-form-item label="用户号" prop="username" v-if="form.loginType == 1">
            <el-input v-model="form.staffUserName" placeholder="请输入用户号"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="form.password" :type="passwordType" placeholder="请输入登录密码">
              <template #suffix>
                <el-icon class="el-input__icon" v-if="passwordType == 'password'" @click="passwordType = 'text'">
                  <Hide />
                </el-icon>
                <el-icon class="el-input__icon" v-else @click="passwordType = 'password'">
                  <View />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <div class="code_wrap">
              <div class="ipt" style="flex: 1;">
                <el-input v-model="form.code" placeholder="请输入验证码" style="width: 100%;"></el-input>
              </div>
              <el-image :src="codeUrl" style="width: 150px;height: 40px;border-radius: 4px;background-color: #fff;"
                fit="contain" @click="captchaAjax" v-loading="codeUrlLoading"
                element-loading-spinner="loading"></el-image>
            </div>
          </el-form-item>
          <!-- <el-form-item>
            <div style="width: 100%; display: flex; justify-content: flex-end">
              <router-link :to="{ name: 'register' }">
                <el-link type="info">忘记密码</el-link>
              </router-link>
            </div>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" style="width: 100%" :loading="loading" @click="submitHandle">
              <span v-if="!loading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button plain style="width: 100%" @click="logout">退出</el-button>
          </el-form-item>
        </el-form>
        <div class="version">
          <el-text size="large">Ver{{ packageData.version }}</el-text>
          <el-text size="large">陕西超掌柜科技有限公司</el-text>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import packageData from "../../package.json";
import logo from "@/assets/logo.png";
import { ElMessage, ElMessageBox } from "element-plus";
import { Hide, View } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ipcRenderer } from "electron";
import { RandomNumBoth } from "@/utils";
import useStorage from "@/utils/useStorage";
import { douyincheckIn } from "@/api/group";
import { useUser } from "@/store/user.js";
import { useGlobal } from '@/store/global.js'
import { useGoods } from '@/store/goods.js'

import { captcha } from '@/api/account.js'

const global = useGlobal()

const store = useUser();
const goodsStore = useGoods()

const router = useRouter();
const formRef = ref(null);
const loading = ref(false);
const passwordType = ref('password')

const codeUrl = ref('')
const codeUrlLoading = ref(false)

const form = reactive({
  username: "",
  staffUserName: '',
  password: "",
  code: "",
  uuid: "",
  loginType: 0, // 0: 商户 1: 员工
});

const rules = reactive({
  username: [
    {
      required: true,
      message: " ",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: " ",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: " ",
      trigger: "blur",
    },
  ],
});

// 提交
const submitHandle = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      store
        .userlogin(form)
        .then(async (res) => {
          // 登录成功后保存商户号
          useStorage.set('merchantLoginAccount', form.username)
          ElMessage.success("登录成功");
          goodsStore.initGoods()
          setTimeout(() => {
            router.replace({
              name: "home",
            });
          }, 1000);
          const douyin = await douyincheckIn({
            token: store.token,
            loginName: form.username,
            clientType: 'pc'
          })
          useStorage.set('douyin', douyin.userInfo)
          // global.updateData(true)
        })
        .catch((err) => {
          console.log(err);
          loading.value = false;
          // 重新获取验证码
          captchaAjax()
        });
    }
  });
};

const logout = () => {
  ElMessageBox.confirm("确定要关闭软件吗？")
    .then(() => {
      ipcRenderer.send("quitHandler", "退出吧");
    })
    .catch(() => { });
};

// 获取验证码
async function captchaAjax() {
  try {
    codeUrlLoading.value = true
    const res = await captcha()
    codeUrl.value = res.code
    form.uuid = res.uuid
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    codeUrlLoading.value = false
  }, 500);
}


onMounted(() => {
  store.initRoute()
  global.updateData(false)
  captchaAjax()
  let merchantLoginAccount = useStorage.get('merchantLoginAccount')
  if (merchantLoginAccount) {
    form.username = merchantLoginAccount
    form.loginType = useStorage.get('loginType')
  }
})
</script>

<style scoped lang="scss">
.login-container {
  width: 100vw;
  display: flex;
  height: 100vh;
  background-color: #efefef;

  :deep(.el-form-item__label) {
    font-size: var(--el-font-size-base);
  }

  .logo {
    flex: 1;
    height: inherit;
    background-color: var(--el-color-primary);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-wrap {
    flex: 1.5;
    height: inherit;
    padding: 0 50px;
    display: flex;
    align-items: center;
  }

  .reg-wrap {
    display: flex;
    justify-content: flex-end;
    padding-bottom: 30px;
  }

  .header {
    display: flex;
    flex-direction: column;
    padding-bottom: 20px;

    .t1 {
      font-size: 42px;
      color: #999;
    }

    .t2 {
      font-size: var(--el-font-size-base);
      color: #999;
    }
  }
}

.version {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.code_wrap {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 10px;

  .code_img {
    flex: 1;
  }
}
</style>
