<template>
  <div class="login" :style="'background-image:url(' + Background + ');'">
    <el-form ref="loginForm" :model="state.loginForm" :rules="state.loginRules" label-position="left" label-width="0px"
      class="login-form">
      <h3 class="title">银收客后台管理</h3>
      <el-form-item>
        <el-radio-group v-model="state.loginForm.loginType">
          <el-radio-button :value="0">商户</el-radio-button>
          <el-radio-button :value="1">员工</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!-- DEV-START -->
      <el-form-item label-width="0" v-if="env == 'development'">
        <div class="tips" style="font-size: 16px;color: #333;">开发版快捷登录</div>
        <div class="btn_wrap" style="display: flex;gap: 10px;flex-wrap: wrap;">
          <el-button :type="item.type" v-for="item in accountList" @click="accountHandle(item)">
            {{ item.label }}
          </el-button>
        </div>
      </el-form-item>
      <!-- DEV-END -->
      <el-form-item prop="username">
        <el-input v-model="state.loginForm.username" type="text" auto-complete="off" placeholder="商户号"></el-input>
      </el-form-item>
      <el-form-item prop="staffUserName" v-if="state.loginForm.loginType == 1">
        <el-input v-model="state.loginForm.staffUserName" type="text" auto-complete="off" placeholder="账号"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="state.loginForm.password" type="password" auto-complete="off" placeholder="密码"
          @keyup.enter="handleLogin"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <div class="code_wrap">
          <el-input v-model="state.loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
            @keyup.enter="handleLogin"></el-input>
          <div class="login-code">
            <img :src="state.codeUrl" @click="getCode" />
          </div>
        </div>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button :loading="state.loading" size="default" type="primary" style="width: 100%"
          @click.prevent="handleLogin">
          <span v-if="!state.loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <!-- <div id="el-login-footer">
      <span>⋅</span>
      <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank"></a>
    </div> -->
  </div>
</template>

<script setup>
import $API_login from "@/api/account/login";
import Cookies from "js-cookie";
import Background from "@/assets/images/background_img.jpg";
import { useUserStore } from "@/store";
import { useRoute } from "vue-router";
import router from "@/router";
import { $douyin_checkIn } from "@/api/coup/index";
import { getToken, getDouyinToken, setDouyinToken } from "@/utils/auth";
const route = useRoute();

const env = process.env.NODE_ENV

// DEV-START
const accountList = reactive([
  { username: "admin", type: 'primary', label: 'admin' },
  { username: "18049104914", type: 'warning', label: '东风的店铺' },
  { username: "19107220837", type: 'danger', label: '快乐时光店铺' },
  // { username: "18199991111", type: 'success', label: '草莓加盟主店可直接管理' },
  { username: "18821670757", type: 'success', label: '高歌的小店' },
  { username: "18821670757", staffUserName: '18821670758', type: 'primary', label: '高歌的小店的员工-张三' },
  { username: "191123456", type: 'primary', label: '酸橘子' },
]);

// 快捷模拟登录
function accountHandle(item) {
  state.loginForm.username = item.username;
  if (item.staffUserName) {
    state.loginForm.loginType = 1
    state.loginForm.staffUserName = item.staffUserName
  } else {
    state.loginForm.loginType = 0
  }
  state.loginForm.code = 666666
  const d = new Date();
  state.loginForm.password = `czg${d.getHours().toString().padStart(2, '0')}${d.getMinutes().toString().padStart(2, '0')}`;
  handleLogin()
}
// DEV-END

const state = reactive({
  Background: Background,
  codeUrl: "",
  cookiePass: "",
  loginForm: {
    username: "",
    password: "",
    // rememberMe: false,
    code: "",
    uuid: "",
    staffUserName: "",
    loginType: 0,
  },
  loginRules: {
    username: [{ required: true, trigger: "blur", message: "商户号不能为空" }],
    password: [{ required: true, trigger: "blur", message: "密码不能为空" }],
    code: [{ required: true, trigger: "change", message: "验证码不能为空" }],
    staffUserName: [{ required: true, trigger: "change", message: "用户名不能为空" }],
  },
  loading: false,
  redirect: undefined,
});

watch(
  () => state.loginForm.loginType,
  (newval) => {
    if (1) {
      delete state.loginForm.staffUserName;
    } else {
      state.loginForm.staffUserName = "";
    }
  }
);

onMounted(() => {
  // 获取验证码
  getCode();
  // // 获取用户名密码等Cookie
  // this.getCookie()
  // // token 过期提示
  // this.point()

  let getinfo = localStorage.getItem("MerchantId");
  let info = JSON.parse(getinfo);
  if (info && info.staffUserName) {
    state.loginForm.staffUserName = info.staffUserName;
    state.loginForm.username = info.username;
  }
});
function getCode() {
  $API_login.getCaptcha().then((res) => {
    console.log(res);
    state.codeUrl = res.code;
    state.loginForm.uuid = res.uuid;
  });
}
function getCookie() {
  const username = Cookies.get("username");
  let password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  // 保存cookie里面的加密后的密码
  state.cookiePass = password === undefined ? "" : password;
  password = password === undefined ? state.loginForm.password : password;
  state.loginForm = {
    username: username === undefined ? state.loginForm.username : username,
    password: password,
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
    code: "",
    loginType: 0,
  };
}

const loginForm = ref(null);
const userStore = useUserStore();

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect() {
  const query = route.query;
  const redirect = query.redirect ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}
function handleLogin() {
  loginForm.value.validate((valid) => {
    if (valid) {
      state.loading = true;
      const user = { ...state.loginForm };
      //      user.password = encrypt(user.password);
      console.log(user);
      userStore
        .login(user)
        .then(async (res) => {

          console.log('login===', res);

          localStorage.setItem('shopStaff', JSON.stringify(res.shopStaff))


          const token = getToken();
          console.log("token", token);
          $douyin_checkIn({
            loginName: userStore.userInfo.phone,
            token,
          }).then((checkInfo) => {
            console.log("checkInfo", checkInfo);
            if (checkInfo && checkInfo.userInfo) {
              userStore.meituan_douyin_info = checkInfo.userInfo;
              setDouyinToken(checkInfo.userInfo.token);
            }
          });
          localStorage.removeItem("shopName");
          let resData = await $API_login.getPermission();
          localStorage.setItem("permission", JSON.stringify(resData));
          localStorage.setItem("loginType", state.loginForm.loginType);

          const { path, queryParams } = parseRedirect();
          console.log(path, queryParams);
          // router.replace({ path: path, query: queryParams });
          router.replace({ path: "/" });
        })
        .catch(() => {
          state.loading = false;
          getCode();
        });
    } else {
      console.log("error submit!!");
      return false;
    }
  });
}
</script>

<style scoped lang="scss">
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-size: cover;
  padding-right: 15%;
}

.title {
  margin: 0 auto 50px auto;
  text-align: center;
  color: #707070;
  font-size: 36px;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 500px;
  padding: 50px 50px 50px 50px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.code_wrap {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.login-code {
  width: 33%;
  display: inline-block;
  height: 38px;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>
