import { getTotpImage, queryTotpStatus, resetTotp, setTotp } from '@/api/user';
import {
  Card,
  Form,
  FormItem,
  VerificationCode,
  Image,
  Button,
  InputPassword,
  type FormInstance,
  Space
} from '@arco-design/web-vue';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import './css/totp.less';

export const StepTwoForm = defineComponent({
  emits: { submit: () => true },
  setup(_, { emit }) {
    const formData = reactive({
      code: ''
    });
    const formRef = ref<FormInstance>();
    const rules = {
      code: [
        {
          required: true,
          message: '验证码不能为空'
        }
      ]
    };
    const state = reactive<{ showImage: boolean; image: string }>({
      showImage: false,
      image: ''
    });
    return () => (
      <Space direction='vertical' fill>
        {state.image ? (
          <div>
            <Image src={state.image} />
            <Button
              status='warning'
              onClick={() => {
                state.showImage = false;
                state.image = '';
                formData.code = '';
              }}
              long
            >
              关闭验证图像
            </Button>
          </div>
        ) : (
          <div>
            <Form ref={formRef} model={formData} rules={rules}>
              <FormItem field='code' required label='验证码'>
                <VerificationCode v-model={formData.code} />
              </FormItem>
            </Form>
            <Button
              status='success'
              onClick={() => {
                formRef.value.validate().then(res => {
                  if (res) return;
                  getTotpImage(formData).then(res => {
                    state.image = res.data.image;
                    state.showImage = true;
                  });
                });
              }}
              long
            >
              查看两步验证
            </Button>
          </div>
        )}
        <Button
          status='danger'
          onClick={() => {
            formRef.value.validate().then(res => {
              if (res) return;
              resetTotp(formData).then(() => {
                emit('submit');
              });
            });
          }}
          long
        >
          删除两步验证
        </Button>
      </Space>
    );
  }
});

export const StepOneForm = defineComponent({
  props: {
    QrImage: {
      type: String,
      required: true
    },
    otpKey: {
      type: String,
      required: true
    },
    otpSecret: {
      type: String,
      required: true
    }
  },
  emits: ['submit'],
  setup(props, { emit }) {
    const formData = reactive<{ password: string; code: string }>({
      password: '',
      code: ''
    });
    const formDataRef = ref<FormInstance>();
    const rules = {
      password: [
        {
          required: true,
          message: '密码不能为空'
        }
      ],
      code: [
        {
          required: true,
          message: '验证码不能为空'
        }
      ]
    };
    return () => (
      <div>
        <Image src={props.QrImage} />
        <Form ref={formDataRef} model={formData} rules={rules}>
          <FormItem field='password' label='密码' required>
            <InputPassword v-model={formData.password} />
          </FormItem>
          <FormItem field='code' required label='二步验证'>
            <VerificationCode
              class='totp-verification-code'
              v-model={formData.code}
            />
          </FormItem>
          <FormItem>
            <Button
              type='primary'
              long
              onClick={() => {
                formDataRef.value.validate().then(res => {
                  if (res) return;
                  setTotp({
                    otpSecret: props.otpSecret,
                    otpKey: props.otpKey,
                    ...formData
                  }).then(() => {
                    emit('submit');
                  });
                });
              }}
            >
              提交
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
});

export default defineComponent({
  setup() {
    const state = reactive<{
      totpStatus: boolean;
      QrImage: string;
      otpSecret: string;
      otpKey: string;
    }>({
      totpStatus: false,
      QrImage: '',
      otpSecret: '',
      otpKey: ''
    });
    const getTotpStatus = () => {
      console.log('wobwdnysle');
      queryTotpStatus().then(res => {
        state.totpStatus = res.data.status;
        if (!state.totpStatus) {
          state.QrImage = res.data.image;
          state.otpSecret = res.data.otpSecret;
          state.otpKey = res.data.otpKey;
        }
      });
    };
    onMounted(() => {
      getTotpStatus();
    });
    return () => (
      <Card
        class='general-card'
        title='二步验证'
        v-slots={{ extra: () => (state.totpStatus ? '已开启' : '未开启') }}
      >
        <div class='totp-inner-card'>
          {state.totpStatus ? (
            <StepTwoForm onSubmit={getTotpStatus} />
          ) : (
            <StepOneForm
              QrImage={state.QrImage}
              otpKey={state.otpKey}
              otpSecret={state.otpSecret}
              onSubmit={getTotpStatus}
            />
          )}
        </div>
      </Card>
    );
  }
});
