<script setup>
/**
 * name：
 * user：sa0ChunLuyu
 * date：2023年7月27日 10:46:18
 */
import {
  $image,
  $response,
  ImageCaptchaCreateAction,
  AdminLoginAction,
  AdminQuitAction,
} from '~/api'
import {useSaveTokenType, useToken, useSessionToken, useStore, useConfig} from "~/store";
import {onBeforeRouteUpdate} from "vue-router";
import $router from '~/router'
import {getInfo} from "~/tool/info";

const $config = useConfig()
const $store = useStore()
const $save_token_type = useSaveTokenType()
const $session_token = useSessionToken()
const $token = useToken()
const login_input_data = ref({
  account: '',
  password: '',
  code: '',
  hash: '',
  time: '',
  uuid: '',
})

const default_page_options = {
  f: '/',
  m: 0
}
const page_options = ref(default_page_options)
onBeforeRouteUpdate((to) => {
  routerChange(to.query)
})

const routerChange = (query) => {
  page_options.value = {
    f: query.f || default_page_options.f,
    m: Number(query.m) || default_page_options.m,
  }
  if (page_options.value.m === 1) proxyManaShow()
}
const getCaptchaCreate = (reload = true) => {
  if (login_type_active.value === 'password') {
    if (reload && Number($store.config['后台密码登录验证']) !== 0) {
      switch (Number($store.config['后台密码登录验证'])) {
        case 1:
          ImageCaptchaCreate()
          break
      }
    }
  }
}
onMounted(() => {
  routerChange($router.currentRoute.value.query)
  getCaptchaCreate()
  AdminQuit()
})
const captcha_loading = ref(false)
const ImageCaptchaCreate = async () => {
  if (captcha_loading.value) return
  captcha_loading.value = true
  const response = await ImageCaptchaCreateAction()
  captcha_loading.value = false
  $response(response, () => {
    login_input_data.value = {
      ...login_input_data.value,
      ...response.data
    }
  })
}

const login_type_active = ref('password')
const loginTypeChange = (type) => {
  login_type_active.value = type
  getCaptchaCreate(false)
}
const loading_active = ref(false)
const AdminLogin = async () => {
  const account_ = login_input_data.value.account.replace(/^\s+|\s+$/g, "")
  if (account_ === '') return window.$message().error('请输入账号')
  if (login_input_data.value.password === '') return window.$message().error('请输入密码')
  if (loading_active.value) return
  loading_active.value = true
  const response = await AdminLoginAction({
    account: account_,
    password: login_input_data.value.password,
    code: login_input_data.value.code,
    hash: login_input_data.value.hash,
    time: login_input_data.value.time,
    uuid: login_input_data.value.uuid,
  })
  loading_active.value = false
  $response(response, () => {
    const token = response.data.token
    saveToken(token)
  })
}
const local_token = ref(false)
const saveToken = (token) => {
  if (local_token.value) {
    $save_token_type.value = 'local'
    $session_token.value = ''
    $token.value = token
  } else {
    $save_token_type.value = 'session'
    $session_token.value = token
    $token.value = ''
  }
  getInfo()
  $router.push(decodeURIComponent(page_options.value.f))
}

const AdminQuit = async () => {
  if (!$token.value && !$session_token.value) return
  const response = await AdminQuitAction()
  $response(response, () => {
    if ($save_token_type.value === 'local') {
      $token.value = ''
    } else {
      $session_token.value = ''
    }
  })
}
const proxy_list = ref([])
const proxy_mana_show = ref(false)
const proxyManaShow = () => {
  proxy_list.value = JSON.parse(JSON.stringify($config.value.api.url))
  proxy_mana_show.value = true
}

const add_proxy_data = ref({
  name: '',
  url: '',
  active: false
})

const addApiClick = () => {
  if (!add_proxy_data.value.name) return window.$message().error('请输入名称')
  if (!add_proxy_data.value.url) return window.$message().error('请输入接口地址')
  if (add_proxy_data.value.url.indexOf('http') !== 0) return window.$message().error('请输入正确的接口地址')
  if (add_proxy_data.value.active) {
    proxy_list.value.forEach((item) => {
      item.active = false
    })
  }
  proxy_list.value.unshift(JSON.parse(JSON.stringify(add_proxy_data.value)))
  add_proxy_data.value = {
    name: '',
    url: '',
    active: false
  }
}

const proxyDelClick = (k) => {
  if (proxy_list.length === 1) return
  let active = proxy_list.value[k]
  proxy_list.value.splice(k, 1)
  if (!!active) {
    proxy_list.value[0].active = true
  }
}
const proxyActiveChange = (e, k) => {
  if (!!e) {
    proxy_list.value.forEach((item) => {
      item.active = false
    })
    proxy_list.value[k].active = true
  } else {
    proxy_list.value[k].active = false
    proxy_list.value[0].active = true
  }
}

const proxySaveClick = () => {
  const active_item = $config.value.api.url.filter((item) => {
    return item.active
  })
  const change_item = proxy_list.value.filter((item) => {
    return item.active
  })
  $config.value.api.url = JSON.parse(JSON.stringify(proxy_list.value))
  proxy_mana_show.value = false
  if (change_item[0].url !== active_item[0].url) {
    if (page_options.value.m === 1) {
      window.location.href = '/#/login'
    } else {
      window.location.reload()
    }

  }
}

const proxyResetClick = () => {
  window.$box.confirm(
    '确定要重置代理配置吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
    localStorage.setItem('APP_CONFIG', JSON.stringify(window.CONFIG_RESET_DATA))
    window.location.reload()
  }).catch(() => {
  })
}
</script>
<template>
  <div>
    <div class="login_wrapper" :style="{
      backgroundImage: 'url(' + $image($store.config['Login背景图']) + ')'
    }">
      <el-card :body-style="{ padding: '0px' }">
        <div class="login_card_wrapper">
          <div class="login_cover_wrapper" :style="{
            backgroundImage: 'url(' + $image($store.config['Login欢迎图片']) + ')',
            backgroundColor: $store.config['Login背景色']
          }">
            <div class="login_cover_title_wrapper">{{ $store.config['网站名称'] }}</div>
            <div class="login_cover_desc_wrapper">{{ $store.config['网站介绍'] }}</div>
          </div>
          <div>
            <div v-loading="loading_active" class="login_input_wrapper">
              <div class="login_input_title_wrapper">登录</div>
              <div class="login_input_change_wrapper">
                <div class="login_input_change_active_wrapper" :style="{
                  left: login_type_active === 'password' ? '0px' : '76px'
                }"></div>
                <div class="login_input_change_item_wrapper">
                  <div v-if="login_type_active === 'password'" class="login_input_change_show_wrapper">密码登录</div>
                  <el-button @click="loginTypeChange('password')" class="login_input_change_button_wrapper" v-else text
                             size="small">密码登录
                  </el-button>
                </div>
              </div>
              <div v-if="login_type_active === 'password'" class="login_input_box_wrapper">
                <div class="login_input_line_wrapper">
                  <el-input v-model="login_input_data.account" class="login_input_input_wrapper"
                            placeholder="请输入登录账号">
                    <template #prefix>
                      <el-icon>
                        <Icon type="people"></Icon>
                      </el-icon>
                    </template>
                  </el-input>
                </div>
                <div class="login_input_line_wrapper">
                  <el-input type="password" v-model="login_input_data.password" class="login_input_input_wrapper"
                            placeholder="请输入登录密码">
                    <template #prefix>
                      <el-icon>
                        <Icon type="lock"></Icon>
                      </el-icon>
                    </template>
                  </el-input>
                </div>
                <div class="login_input_line_wrapper" v-if="Number($store.config['后台密码登录验证']) === 0"></div>
                <div class="login_input_line_wrapper" v-if="Number($store.config['后台密码登录验证']) === 1">
                  <el-input v-model="login_input_data.code" class="login_input_code_input_wrapper"
                            placeholder="请输入验证码">
                    <template #prefix>
                      <el-icon>
                        <Icon type="protect"></Icon>
                      </el-icon>
                    </template>
                  </el-input>
                  <div v-loading="captcha_loading && !login_input_data.image"
                       @click="ImageCaptchaCreate()"
                       class="login_input_code_image_wrapper">
                    <div w-full h-full v-if="!!login_input_data.image" :style="{
                    backgroundImage: 'url(' + $image(login_input_data.image) + ')'
                  }"></div>
                  </div>
                </div>
                <div class="login_checkbox_wrapper">
                  <el-checkbox v-model="local_token"/>
                  <div ml-2>记住密码</div>
                </div>
                <div text-center mt-4>
                  <el-button @click="AdminLogin()" v-loading="loading_active" class="login_button_wrapper"
                             type="primary">登录
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <el-dialog v-model="proxy_mana_show" title="代理设置" width="610px"
                 :close-on-click-modal="false">
        <div>
          <table class="table-fixed">
            <thead>
            <tr>
              <th>状态</th>
              <th class="w-1/4">名称</th>
              <th class="w-1/2">接口地址</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr>
              <td>
                <el-switch size="small" v-model="add_proxy_data.active"/>
              </td>
              <td>
                <el-input size="small" v-model="add_proxy_data.name" class="proxy_name_input_wrapper"
                          placeholder="请输入名称">
                </el-input>
              </td>
              <td>
                <el-input size="small" v-model="add_proxy_data.url" class="proxy_url_input_wrapper"
                          placeholder="请输入接口地址">
                </el-input>
              </td>
              <td>
                <el-button @click="addApiClick()" type="primary" size="small">
                  <el-icon>
                    <Icon type="plus"></Icon>
                  </el-icon>
                </el-button>
              </td>
            </tr>
            <tr v-for="(i,k) in proxy_list" :key="k">
              <td>
                <el-switch size="small" v-model="proxy_list[k].active" @change="(e)=>{proxyActiveChange(e,k)}"/>
              </td>
              <td>
                <el-input size="small" class="proxy_name_input_wrapper" v-model="proxy_list[k].name" placeholder="名称">
                </el-input>
              </td>
              <td>
                <el-input size="small" class="proxy_url_input_wrapper" v-model="proxy_list[k].url" placeholder="接口地址">
                </el-input>
              </td>
              <td>
                <el-button @click="proxyDelClick(k)" :disabled="proxy_list.length === 1" type="danger" size="small">
                  <el-icon>
                    <Icon type="delete"></Icon>
                  </el-icon>
                </el-button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="proxyResetClick()">重置</el-button>
            <el-button @click="proxy_mana_show = false">关闭</el-button>
            <el-button @click="proxySaveClick()" type="primary">
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>

      <div class="proxy_mana_wrapper">
        <el-button @click="proxyManaShow()" text>
          <Icon type="link-four"></Icon>
        </el-button>
      </div>
    </div>
  </div>
</template>
<style scoped>
.proxy_name_input_wrapper {
  width: 170px;
}

.proxy_url_input_wrapper {
  width: 300px;
}

.proxy_item_wrapper {
  display: flex;
  align-items: center;
}

.proxy_mana_wrapper {
  position: fixed;
  right: 50px;
  bottom: 50px;
}

.login_qrcode_box_wrapper {
  width: 160px;
  height: 160px;
  background: #ffffff;
  border-radius: 6px;
  margin: 10px;
  line-height: 160px;
  text-align: center;
  color: #1d1d1f;
}

.login_qrcode_wrapper {
  width: 180px;
  height: 180px;
  background: #f5f5f5;
  border-radius: 6px;
  margin: 35px auto 0;
  overflow: hidden;
}

.login_input_change_show_wrapper {
  color: #1d1d1f;
  font-size: 12px;
  font-weight: bold;
  width: 76px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  position: relative;
  z-index: 2;
}

.login_input_change_button_wrapper {
  font-size: 12px;
  width: 76px;
  height: 22px;
  position: relative;
  z-index: 2;
}

.login_input_change_active_wrapper {
  width: 76px;
  height: 22px;
  background: #ffffff;
  border-radius: 6px;
  position: absolute;
  top: 0;
  z-index: 1;
  transition: left 0.3s ease-in-out;
}

.login_input_change_wrapper {
  position: relative;
  display: flex;
  background: #f6f6f6;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  width: 76px;
  height: 22px;
  border: #f6f6f6 solid 4px;
  margin-left: 50px;
  margin-top: 20px;
}

.login_button_wrapper {
  width: 320px;
  height: 40px;
  margin: 0 auto;
}

.login_checkbox_wrapper {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-left: 50px;
  margin-top: 15px;
}

.login_input_box_wrapper {
  margin-top: 20px;
}

.login_input_line_wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 320px;
  margin: 20px auto 0;
  height: 40px;
}

.login_input_code_input_wrapper {
  width: 200px;
  height: 40px;
}

.login_input_input_wrapper {
  width: 320px;
  height: 40px;
}

.login_input_code_image_wrapper {
  width: 110px;
  height: 40px;
  background-repeat: no-repeat;
  background-size: cover;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  overflow: hidden;
}

.login_input_title_wrapper {
  font-size: 24px;
  color: #1d1d1f;
  margin-top: 35px;
  margin-left: 50px;
}

.login_cover_title_wrapper {
  color: #fffffa;
  font-size: 26px;
  font-weight: 400;
  margin-top: 50px;
}

.login_cover_desc_wrapper {
  color: #fffffc;
  font-size: 16px;
  font-weight: 400;
  margin-top: 10px;
}

.login_input_wrapper {
  width: 420px;
  height: 450px;
  overflow: hidden;
}

.login_cover_wrapper {
  width: 500px;
  height: 450px;
  text-align: center;
  background-repeat: no-repeat;
  background-position: bottom;
  background-size: contain;
  overflow: hidden;
}

.login_card_wrapper {
  width: 920px;
  display: flex;
}

.login_wrapper {
  min-height: 100vh;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
<route>
{"meta":{"layout":"none","title":"登录"}}
</route>

