<template>
  <el-dialog
    v-model="visible"
    class="confirm-dialog"
    title="信息确认"
    center
    destroy-on-close
    :close-on-click-modal="false"
    @closed="closed"
  >
    <div class="confirm-dialog-tip">
      <span>每个手机号每月只能生成 3 次出海分析报告。 </span>
      <span>为确保报告准确送达，请填写以下信息（全程加密处理），获得完整商情报告。</span>
    </div>
    <div class="confirm-dialog-content">
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" clearable>
            <template #prefix>
              <img :src="User" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model.number="form.phone" placeholder="请输入手机号" clearable>
            <template #prefix>
              <img :src="Phone" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="verifyCode">
          <el-input v-model="form.verifyCode" placeholder="请输入验证码">
            <template #prefix>
              <img :src="Code" />
            </template>
            <template #suffix>
              <el-button
                :disabled="!!countDownNumer"
                :loading="getVerifyCodeLoading"
                @click="acceptCode"
                ><span>{{ codeText }}</span>
                <span v-if="countDownNumer">{{ `(${countDownNumer})` }}</span></el-button
              >
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="sumbitLoading" @click="submitForm(ruleFormRef)"
          >查看并下载报告</el-button
        >
      </div>
    </template>
  </el-dialog>
  <el-dialog
    title="滑动验证"
    destroy-on-close
    width="500px"
    center
    modal-class="register-verify-model"
    v-model="modalVisible"
  >
    <SliderVerify
      :slideVerifyOptions="{ show: false, w: 450, h: 220 }"
      @onSuccess="verifySuccess"
      @onFail="verifyFail"
    />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, reactive } from 'vue';
import { useMainStore } from '@/store';
import { useRouter } from 'vue-router';
import SliderVerify from '@/components/SliderVerify.vue';
import { showMessage, startCountdown } from '@/utils/common';
import { verificationCode, getRecord } from '@/utils/api';
import User from '@/assets/images/login/User.png';
import Code from '@/assets/images/login/Code.png';
import Phone from '@/assets/images/login/Phone.png';

import type { FormInstance, FormRules } from 'element-plus';

interface RuleForm {
  companyName: string;
  phone: string;
  verifyCode: string;
}

const validatePhone = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号'));
  } else {
    if (!/(1[3-9]\d{9}$)/.test(value)) {
      callback(new Error('请输入正确的手机号'));
    } else {
      callback();
    }
  }
};

const router = useRouter();

const mainStore = useMainStore();

const emits = defineEmits(['update:visible']);

const sumbitLoading = ref<boolean>(false);

const ruleFormRef = ref<FormInstance>();
// 人机验证弹窗显示标识
const modalVisible = ref(false);

// 倒计时展示
const countDownNumer = ref(0);
// 重新获取验证码标识
const isReacquireCode = ref(false);

const getVerifyCodeLoading = ref(false);

const props = defineProps(['visible', 'callback']);

const visible = computed({
  get() {
    return props.visible;
  },
  set(val) {
    emits('update:visible', val);
  }
});

// 获取验证码的文案
const codeText = computed(() => {
  return isReacquireCode.value ? '重新获取' : '获取验证码';
});

const form = reactive<RuleForm>({
  companyName: '',
  phone: '',
  verifyCode: ''
});

const rules = reactive<FormRules<RuleForm>>({
  companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  phone: [{ validator: validatePhone, trigger: 'blur' }],
  verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
});

const acceptCode = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.validateField(['phone'], (isValidate) => {
      console.log(isValidate, 'isValidate');
      if (isValidate) {
        modalVisible.value = true;
      }
    });
  }
};

const closed = () => {
  visible.value = false;
};

// 获取验证码
const getVerifyCode = () => {
  getVerifyCodeLoading.value = true;
  return verificationCode(form.phone)
    .then((res) => {
      startCountdown(60, (time) => (countDownNumer.value = time));
      isReacquireCode.value = true;
    })
    .catch(err => {
      showMessage({
        type: 'error',
        message: err
      })
    })
    .finally(() => {
      getVerifyCodeLoading.value = false;
    });
};

// 人机验证成功
const verifySuccess = () => {
  modalVisible.value = false;
  showMessage({
    message: '验证通过, 即将发送验证码',
    type: 'success'
  });
  getVerifyCode();
};

// 人机校验失败
const verifyFail = () => {
  showMessage({
    message: '校验不通过',
    type: 'warning'
  });
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      sumbitLoading.value = true;
      return getRecord({
        ...form
      })
        .then((res) => {
          visible.value = false;
          mainStore.setPhone(form.phone);
          mainStore.setRecordId(res.data);
          props.callback && props.callback();
          router.push({
            path: `/record`
          });
        })
        .catch(err => {
          showMessage({
            type: 'warning',
            message: err
          })
        })
        .finally(() => {
          sumbitLoading.value = false;
        });
    } else {
      console.log('error submit!');
    }
  });
};
</script>

<style lang="scss">
.confirm-dialog {
  position: relative;
  display: flex;
  flex-direction: column;
  // justify-content: center;
  align-items: center;
  width: 487px;
  height: 598px;
  background-color: #f6f8fa;
  .el-dialog__header {
    font-weight: bold;
    font-size: 32px;
    color: #282e30;
  }

  &-tip {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 10px;
    span {
      font-weight: 400;
      font-size: 12px;
      color: rgba(40, 46, 48, 0.6);
    }
  }

  &-content {
    .el-input {
      width: 431px !important;
      height: 48px !important;
      background: #ffffff !important;
      border: 1px solid #dde1e6 !important;
      box-shadow: none;
      border-radius: none;
    }

    .el-form-item {
      margin-bottom: 32px;
    }

    .el-input__wrapper {
      box-shadow: none !important;
    }

    .el-input__inner {
      &::placeholder {
        position: relative;
        top: 1px;
        font-weight: 400;
        font-size: 16px;
        color: rgba(40, 46, 48, 0.6);
      }
    }

    .el-input__prefix {
      width: 17px;
      height: 19px;
      margin-left: 15px;
      margin-right: 5px;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .el-input__suffix {
      .el-button {
        width: 154px;
        height: 40px;
        line-height: 40px;
        font-weight: bold;
        font-size: 16px;
        color: #ffffff;
        background-color: var(--promotion--color-primary);
      }
    }

    .el-form-item__error {
      font-weight: 400;
      font-size: 16px;
      color: #d20000;
      padding-left: 20px;
    }
  }

  .el-dialog__footer {
    position: absolute;
    bottom: 80px;
    width: 100%;
    .dialog-footer {
      width: 100%;
      .el-button {
        width: 431px;
        height: 46px;
        font-weight: bold;
        font-size: 16px;
        color: #ffffff;
        background: var(--promotion--color-primary);
      }
    }
  }
}
</style>
<style lang="scss"></style>
