<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'

// import captcha from './captcha.vue'
import { PageEnum } from '@/enums/pageEnum'
import { useUserStore } from '@/store/modules/user'
import { ResultEnum } from '@/enums/httpEnum'
import { getFilter, setFilter } from '@/api/home/filter'
import { getConfig } from '@/api/system/user'
import { forgetPassword, getCode } from '@/api/login/login'

import { asideMap } from '@/config/aside'

const emit = defineEmits(['close', 'forget'])
interface FormState {
  enterprisecode?: string
  username: string
  password: string
  captcha: string
}

interface FormForget {
  agentcode: string
  loginname: string
  phone: string
  phonecode: string
}

const formRef = ref()
const message = useMessage()
const loading = ref(false)
const autoLogin = ref(true)
const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const show = ref(false)
const flag = ref(false)
const formForget: FormForget = reactive({
  agentcode: '三方系统标识8',
  loginname: '13311111111',
  phone: '13311111111',
  phonecode: '',
})
const formInline: FormState = reactive({
  enterprisecode: '三方系统标识8',
  username: '13311111111',
  password: '123456',
  captcha: '',
})
const tab = ref(0)
const countTime = ref('获取验证码')
const rules = {
  enterprisecode: { required: true, message: '请输入企业编码', trigger: 'blur' },
  loginname: { required: true, message: '请输入用户名', trigger: 'blur' },
  password: { required: true, message: '请输入密码', trigger: 'blur' },
  captcha: { required: true, message: '请输入验证码', trigger: 'blur' },
  reenteredPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur'],
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input'],
    },
  ],
}

function validatePasswordSame(rule: any, value: string): boolean {
  return value === formInline.password
}

function handleSubmit(e) {
  e.preventDefault()
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const { loginname, phone, phonecode, agentcode } = formForget
      message.loading('登录中...')
      loading.value = true

      const params = {
        loginname,
        phone,
        phonecode,
        agentcode,
      }

      try {
        const res = await forgetPassword(params)
        console.log(res)
        const { code, message: msg } = await userStore.login(params)
        await userStore.getInformation()
        const response = await getFilter()

        // 添加个默认显示配置
        if (response.data === null) {
          const systemConfig = await getConfig()
          const onList: string[] = []
          Object.keys(systemConfig.data).forEach((key) => {
            // 系统配置开启且个人配置开启
            if (key.startsWith('iz') && systemConfig.data[key] === 'Y' && asideMap[key]?.isDefaultFilter)
              onList.push(key)
          })
          await setFilter({ searchcount: onList.join(',') })
        }

        message.destroyAll()
        if (code === ResultEnum.SUCCESS) {
          const toPath = decodeURIComponent((route.query?.redirect || '/') as string)
          message.success('登录成功，即将进入系统')
          if (route.name === LOGIN_NAME)
            router.replace('/')
          else router.replace(toPath)
        }
        else {
          message.info(msg || '登录失败')
        }
      }
      finally {
        loading.value = false
      }
    }
    else {
      message.error('请填写完整信息，并且进行验证码校验')
    }
  })
}

function close() {
  emit('close')
}

function switchTab(type: number) {
  tab.value = type
}

function computedForm() {
  return !formInline.enterprisecode || !formInline.username || !formInline.password
}

async function sendCode(value) {
  const res = await getCode({
    phone: 13311111111,
    agentcode: '三方系统标识8',
  })
  console.log(res)
  startCount()
}

function startCount() {
  let time = 60
  countTime.value = '60s'
  const timer = setInterval(() => {
    countTime.value = `${--time}s`
    if (time === 0) {
      clearInterval(timer)
      countTime.value = '获取验证码'
      flag.value = false
    }
  }, 1000)
}

function forget() {
  emit('forget')
}
</script>

<template>
  <div class="form-login">
    <img class="img-close" src="@/assets/images/login/close.png" alt="" @click="close">
    <div class="header flex justify-between">
      <div class="tab">
        忘记密码
      </div>
      <div class="back" @click="forget">
        &lt; 返回登录
      </div>
    </div>
    <div v-if="tab === 0" class="form-1">
      <n-form ref="formRef" label-placement="left" size="large" :model="formForget" :rules="rules">
        <n-form-item class="form-item" path="agentcode">
          <n-input v-model:value="formForget.agentcode" class="item-input" placeholder="请输入企业编码">
            <template #prefix>
              <svg-icon size="20" name="enterprise" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item class="form-item" path="loginname">
          <n-input v-model:value="formForget.loginname" class="item-input" placeholder="请输入用户名">
            <template #prefix>
              <svg-icon size="20" name="account" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item class="form-item" path="phone">
          <n-input v-model:value="formForget.phone" class="item-input" placeholder="请输入手机号">
            <template #prefix>
              <img class="img-phone" src="@/assets/images/login/phone.png" alt="" @click="close">
            </template>
          </n-input>
        </n-form-item>
        <n-form-item class="form-item" path="phonecode">
          <n-input v-model:value="formForget.phonecode" maxlength="6" class="item-input" placeholder="请输入验证码" clearable>
            <template #prefix>
              <img class="img-phone" src="@/assets/images/login/auth.png" alt="" @click="close">
            </template>
            <template #suffix>
              <div :class="{ 'code-count': countTime !== '获取验证码' }" class="code" @click="sendCode">
                {{ countTime }}
              </div>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item class="form-item">
          <n-button :class="{ 'btn-disabled': computedForm() }" class="btn" type="primary" size="large" :loading="loading" block @click="handleSubmit">
            下一步
          </n-button>
        </n-form-item>
      </n-form>
    </div>
    <div v-if="tab === 1" class="form-1">
      <n-form ref="formRef" label-placement="left" size="large" :model="formInline" :rules="rules">
        <n-form-item class="form-item" path="password">
          <n-input v-model:value="formInline.password" class="item-input" type="password" show-password-on="click" placeholder="请输入8-16位密码，必须包含英文及数字">
            <template #prefix>
              <svg-icon size="20" name="password" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item class="form-item" path="password">
          <n-input v-model:value="formInline.password" class="item-input" type="password" show-password-on="click" placeholder="请再次确认输入新密码">
            <template #prefix>
              <svg-icon size="20" name="password" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item class="form-item">
          <n-button :class="{ 'btn-disabled': computedForm() }" class="btn" type="primary" size="large" :loading="loading" block @click="handleSubmit">
            确定
          </n-button>
        </n-form-item>
      </n-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
.form-login {
  width: 420px;
  box-sizing: border-box;
  background: linear-gradient(136deg,rgba(226,236,255,0.80) 3%, rgba(251,251,251,0.80) 97%);
  border: 1px solid #ffffff;
  border-radius: 6px;
  box-shadow: 0px 6px 12px 0px rgba(0,0,0,0.04);
  backdrop-filter: blur(12px);
  position: relative;
  padding: 48px 27px 42px;

  .img-close{
    position: absolute;
    right: 0;
    top: -44px;
    width: 28px;
    height: 28px;
    cursor: pointer;
  }

  .tab{
    font-size: 24px;
    font-family: PingFang SC, PingFang SC-Medium;
    font-weight: Medium;
    text-align: left;
    color: #507afd;
  }

  .header{
    align-items: center;
  }

  .form-1{
    margin-top: 29px;

    .form-item{
      height: 60px;
    }

    .item-input{
      width: 366px;
      // height: 44px;
      background: rgba(255,255,255,0.50);
      border-radius: 4px;
    }

    .btn{
      width: 366px;
      height: 44px;
      background: linear-gradient(234deg,#96aaff 0%, #1c43ff 100%);
      border-radius: 3px;
      margin-top: 10px;
      margin-bottom: 14px;

      &-disabled{
        opacity: 0.5;
        background: linear-gradient(234deg,#96aaff 0%, #1c43ff 100%);
      }
    }
  }

  .img-phone{
    width: 20px;
    height: 20px;
  }

  .order-last{
    font-size: 14px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: Regular;
    color: #507afd;
  }

  .code{
    font-size: 15px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: Regular;
    color: #507afd;
    margin-left: 12px;

    &-count{
      font-size: 14px;
      color: #999999;
    }
  }
}
::v-deep(.n-form-item-feedback--error) {
  // color: #FF4E4F !important;
}
</style>
