import { defineComponent, reactive, ref } from 'vue';
import styles from '../index.module.less';
import lockIcon from '../images/lock-icon.png';
import useIcon from '../images/user-icon.png';
import openEye from '../images/openEye.png';
import closeEye from '../images/closeEye.png';
import {
  useMessage,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NCheckbox
} from 'naive-ui';
import { useRoute, useRouter } from 'vue-router';
import { PageEnum } from '/src/enums/pageEnum';
import { storage } from '@/utils/storage';
import { useUserStore } from '/src/store/modules/users';

interface FormState {
  username: string;
  password: string;
  grant_type?: string;
  loginType?: string;
  client_id?: string;
  client_secret?: string;
  clientId?: string;
  clientSecret?: string;
}

export default defineComponent({
  name: 'codeLogin',
  props: {
    phone: {
      type: String,
      default: ''
    }
  },
  emits: ['changType', 'update:phone'],
  setup(props, { emit }) {
    const router = useRouter();
    // const route = useRoute();
    const formRef = ref();
    const message = useMessage();
    const loading = ref(false);
    // const autoLogin = ref(true);
    // const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;
    const showPwd = ref(false);

    const userStore = useUserStore();
    let formInline = reactive({
      username: '',
      password: '',
      isCaptcha: false
    });
    const formInlineHistory = storage.get('userInfo-teacher');
    if (formInlineHistory) {
      formInline = reactive({ ...JSON.parse(formInlineHistory) });
    }

    if (formInline.username) {
      if (formInline.username !== props.phone && props.phone) {
        formInline.username = props.phone;
      } else {
        emit('update:phone', formInline.username);
      }
    } else {
      if (props.phone) {
        formInline.username = props.phone;
      }
    }

    const handleSubmit = async () => {
      formRef.value.validate(async (errors: any) => {
        if (!errors) {
          const { username, password } = formInline;
          loading.value = true;

          const params: FormState = {
            username,
            password,
            loginType: 'PASSWORD',
            grant_type: 'password',
            client_id: 'cooleshow-teacher',
            client_secret: 'cooleshow-teacher'
          };

          try {
            await userStore.login(params);
            message.destroyAll();
            //  判断是否勾选自动登录
            if (formInline.isCaptcha) {
              storage.set('userInfo-teacher', JSON.stringify(formInline));
            } else {
              storage.set(
                'userInfo-teacher',
                JSON.stringify({
                  ...formInline,
                  password: '',
                  isCaptcha: false
                })
              );
            }

            // route.query?.redirect ||
            const toPath = decodeURIComponent('/' as string);
            console.log(toPath, 'toPath');
            message.success('登录成功，即将进入系统');
            router.replace(toPath);
            // if (route.name === LOGIN_NAME) {
            //   router.replace('/');
            // } else router.replace(toPath);
          } catch (e: any) {
            console.log(e, 'e');
          } finally {
            loading.value = false;
          }
        }
      });
    };
    return () => (
      <div class={styles['view-account-form-wrap']}>
        {/* <div class={styles.formTitle}>
      <div class={styles.dot}></div>
      酷乐秀课堂乐器
    </div> */}
        <NForm
          ref={formRef}
          label-placement="left"
          size="large"
          model={formInline}>
          <NFormItem
            path="username"
            rule={[
              { required: true, message: '请输入用户名', trigger: 'blur' }
            ]}>
            <NInput
              maxlength={11}
              v-model:value={formInline.username}
              placeholder="请输入用户名"
              onInput={(val: any) => {
                emit('update:phone', val);
              }}>
              {{
                prefix: () => (
                  <img src={useIcon} class={styles.prefixIcon} alt="" />
                )
              }}
            </NInput>
          </NFormItem>
          <NFormItem
            path="password"
            rule={[{ required: true, message: '请输入密码', trigger: 'blur' }]}>
            <NInput
              v-model:value={formInline.password}
              type="text"
              showPasswordOn="click"
              placeholder="请输入密码"
              inputProps={{ autocomplete: 'off' }}
              class={[showPwd.value ? '' : styles['no-pwd']]}
              onKeydown={(e: KeyboardEvent) => {
                if (e.code === 'Enter' || e.code === 'NumpadEnter') {
                  handleSubmit();
                }
              }}>
              {{
                prefix: () => (
                  <img src={lockIcon} class={styles.prefixIcon} alt="" />
                ),
                suffix: () => (
                  <img
                    src={showPwd.value ? openEye : closeEye}
                    class={styles.pwdIcon}
                    alt=""
                    onClick={() => {
                      showPwd.value = !showPwd.value;
                    }}
                  />
                )
              }}
            </NInput>
          </NFormItem>
          <NFormItem class={styles['default-color']}>
            <div class={[styles['flex'], styles['justify-between']]}>
              <div class={styles['flex-initial']}>
                <NCheckbox v-model:checked={formInline.isCaptcha}>
                  记住密码
                </NCheckbox>
              </div>
            </div>
          </NFormItem>
          <NFormItem>
            <NButton
              class={styles.submitBtm}
              type="primary"
              onClick={handleSubmit}
              size="large"
              disabled={loading.value}
              loading={loading.value}
              block>
              立即登录
            </NButton>
          </NFormItem>
          <NFormItem>
            <NButton
              text
              class={styles.forgetBtm}
              onClick={() => {
                emit('changType');
              }}
              size="large"
              block>
              忘记密码
            </NButton>
          </NFormItem>
        </NForm>
      </div>
    );
  }
});
