<!-- 角色编辑弹窗 -->
<template>
  <ele-modal
    :width="550"
    :visible="visible"
    :confirm-loading="loading"
    title="重置AppSecret"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    ok-text="重置"
    cancel-text="关闭"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :label-col="styleResponsive ? { md: 5, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <template v-if="!appSecret">
        <a-form-item label="手机号码" name="phone">
          <a-input
            :maxlength="20"
            :disabled="true"
            placeholder="请输入短信验证码"
            v-model:value="form.phone"
          />
        </a-form-item>
        <a-form-item label="短信验证码" name="code">
          <div class="login-input-group">
            <a-input
              placeholder="请输入验证码"
              v-model:value="form.code"
              :maxlength="6"
              allow-clear
            />
            <a-button
              class="login-captcha"
              :disabled="!!countdownTime"
              @click="openImgCodeModal"
            >
              <span v-if="!countdownTime" @click="sendCode">发送验证码</span>
              <span v-else>已发送 {{ countdownTime }} s</span>
            </a-button>
          </div>
        </a-form-item>
      </template>
      <template v-else>
        <a-form-item label="AppID" name="appId">
          <a-typography-text copyable code class="ele-text-secondary">{{
            appId
          }}</a-typography-text>
        </a-form-item>
        <a-form-item label="AppSecret" name="appSecret">
          <a-typography-text copyable code class="ele-text-secondary">{{
            appSecret
          }}</a-typography-text>
        </a-form-item>
      </template>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import { User } from '@/api/system/user/model';
  import { sendSmsCaptcha } from '@/api/passport/login';
  import { updateAppSecret } from '@/api/oa/app';
  import { createCode, encrypt } from '@/utils/common';
  import { pageAppUser } from '@/api/oa/app/user';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    appId?: number;
  }>();

  const formRef = ref<FormInstance | null>(null);
  // 验证码倒计时时间
  const countdownTime = ref(0);
  // 验证码倒计时定时器
  let countdownTimer: number | null = null;
  const loading = ref(false);
  const appSecret = ref('');

  // 表单数据
  const { form, resetFields } = useFormData<User>({
    phone: '',
    userId: undefined
  });

  /* 显示发送短信验证码弹窗 */
  const openImgCodeModal = () => {
    if (!form.phone) {
      message.error('请输入手机号码');
      return;
    }
  };
  /* 发送短信验证码 */
  const sendCode = () => {
    sendSmsCaptcha({ phone: form.phone }).then(() => {
      message.success('短信验证码发送成功, 请注意查收!');
      countdownTime.value = 60;
      // 开始对按钮进行倒计时
      countdownTimer = window.setInterval(() => {
        if (countdownTime.value <= 1) {
          countdownTimer && clearInterval(countdownTimer);
          countdownTimer = null;
        }
        countdownTime.value--;
      }, 1000);
    });
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    if (appSecret.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        updateAppSecret({
          phone: form.phone,
          appCode: form.code,
          appId: props.appId,
          appSecret: encrypt(createCode())
        })
          .then((res) => {
            loading.value = false;
            message.success(res.message);
            appSecret.value = String(res.data);
            // updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        pageAppUser({ appId: props.appId, role: 30 }).then((res) => {
          if (res?.list) {
            form.phone = res.list[0].phone;
          }
        });
        console.log(props.appId);
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>

<style lang="less" scoped>
  /* 验证码 */
  .login-input-group {
    display: flex;
    align-items: center;

    :deep(.ant-input-affix-wrapper) {
      flex: 1;
    }

    .login-captcha {
      width: 102px;
      height: 33px;
      margin-left: 10px;
      padding: 0;

      & > img {
        width: 100%;
        height: 100%;
      }
    }
  }
</style>
