<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { system } from '@/stores/modules/system'
import { user } from '@/stores/modules/user'
import { useGlobal } from '@/composables'
import { validatorMobile, verifyPwd, validatorLoginMobile } from '@/utils/verification'
import { loginApi, getSmsApi, weixinApi, getUserInfoApi, registerApi, forgetApi, phoneLoginApi } from '@/api/login'
import Captcha from '@/base/components/Captcha.vue'
import type { captchaInfo } from '@/types/login'
import { getEnterpriseAPI } from '@/api/system'
import type { useInfoResult } from '@/types/login'

const userStore = user()
const systemStore = system()
// 表单信息
const form = ref({
  username: '',
  password: '',
  code: '',
  phonenumber: '',
  smsCode: '',
  type: 2,
  uuid: '',
  openId: ''
})

// 表单校验
const rules: UniHelper.UniFormsRules = {
  username: {
    rules: [
      {
        required: true,
        errorMessage: '请输入手机号'
      },
      {
        maxLength: useGlobal().textMax,
        errorMessage: '限制{maxLength}个字符'
      },
      {
        validateFunction: validatorLoginMobile
      }
    ]
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: '请输入密码'
      }
    ]
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: '请输入验证码'
      }
    ]
  },
  phonenumber: {
    rules: [
      {
        required: true,
        errorMessage: '请输入手机号'
      },
      {
        validateFunction: validatorMobile
      }
    ]
  },
  smsCode: {
    rules: [
      {
        required: true,
        errorMessage: '请输入验证码'
      }
    ]
  }
}
// 表单组件实例
const formRef = ref<UniHelper.UniFormsInstance>()
// 登录方式 1短信验证码登录 2密码登录
const loginTypeChange = () => {
  form.value.type = form.value.type === 1 ? 2 : 1
}
// 是否展示验证码
let isShowCaptcha: boolean = true
let uuid: string = ''
const captchaRef = ref()
const getCaptchaInfo = (val: captchaInfo) => {
  isShowCaptcha = val.captchaEnabled
  if (type.value === 1) {
    uuid = val.uuid
    form.value.code = val.code
  } else {
    registerForm.value.uuid = val.uuid
    registerForm.value.code = val.code
  }
}
// 短信验证码
let isDisabled = ref(false)
let countdown = ref(0)
const getSmsCode = (type: number) => {
  if (type === 1 && !form.value.phonenumber) {
    useGlobal().tips('请输入手机号')
    return
  }
  if (type === 2 && !pwdForm.value.phonenumber) {
    useGlobal().tips('请输入手机号')
    return
  }
  getSmsApi({ phonenumber: type === 1 ? form.value.phonenumber : pwdForm.value.phonenumber, type }).then(() => {
    uni.showToast({
      title: '操作成功',
      icon: 'none'
    })
    isDisabled.value = true
    countdown.value = 60
    const timerInterval = setInterval(() => {
      if (countdown.value > 1) {
        countdown.value--
      } else {
        isDisabled.value = false
        clearInterval(timerInterval)
      }
    }, 1000)
  })
}
// 存储用户信息
const refreshUserInfo = () => {
  // 获取用户信息
  getUserInfoApi().then((response) => {
    const result = {
      ...response?.data?.user,
      secretary: 1
    }
    // 党员是否为书记
    if (result.type & 32) {
      result.secretary = response?.data?.secretary
    }
    // 存储用户信息
    userStore.setUserInfo(result as useInfoResult)
    // 存储权限
    let permissions = []
    if (response?.data?.permissions) {
      for (let item of response.data.permissions) {
        permissions.push(item)
      }
    }
    userStore.setPermissions(permissions)
    // 登录成功返回上一页
    uni.navigateBack()
  }).catch(() => {
    uni.navigateBack()
  })
}
// 登录
const handleSubmit = async () => {
  formRef.value?.validate?.((err, formData) => {
    if (!err) {
      let params = ref()
      form.value.uuid = isShowCaptcha && form.value.type === 2 ? uuid : ''
      if (isBind.value === 1) {
        // 微信绑定
        params.value = {
          username: form.value.username,
          password: form.value.password,
          uuid: form.value.uuid,
          openId: openId.value,
          platform: 'pc'
        }
      } else {
        params.value = form.value
      }
      uni.showLoading()
      loginApi(params.value, isBind.value)
        .then((res) => {
          // 存储token
          userStore.setToken(res?.data?.token)
          setTimeout(() => {
            refreshUserInfo()
          }, 100)
        })
        .catch((err) => {
          captchaRef.value?.getCaptchaImage()
        })
    }
  })
  // try {
  //   // 表单校验
  //   await formRef.value?.validate?.()
  //   // 校验通过后再发送请求
  // } catch (error) {
  //   //
  // }
}
// 清空密码
const handleClear = () => {
  form.value.password = ''
}
// 注册
const handleRegister = () => {
  uni.navigateTo({ url: '/base/register' })
}
// 忘记密码
const handleForget = () => {
  uni.navigateTo({ url: '/base/forget' })
}
// 微信登录
let openId = ref('')
// 微信是否绑定系统用户 1未绑定 0已绑定
let isBind = ref(0)
const handleUserProfile = () => {
  uni.showLoading()
  uni.login({
    provider: 'weixin',
    success: function (res) {
      weixinApi({ code: res.code }).then((result) => {
        console.log(result, 'res.code')
        if (result.code === 409) {
          // 用户不存在需要用户手动绑定
          uni.showToast({
            title: '微信账号未绑定系统用户，请先绑定',
            icon: 'none',
            duration: 3000
          })
          isBind.value = 1
          openId.value = result.msg
        } else {
          isBind.value = 0
          // 存储token
          userStore.setToken(result?.data?.token)
          // 返回用户token，正常存储登录
          setTimeout(() => {
            refreshUserInfo()
          }, 100)
        }
      })
    },
    complete: function () {
      uni.hideLoading()
    }
  })
}

// 注册
// 表单校验
const registerRules: UniHelper.UniFormsRules = {
  // username: {
  //   rules: [
  //     {
  //       required: true,
  //       errorMessage: '请输入用户名'
  //     },
  //     {
  //       maxLength: useGlobal().textMax,
  //       errorMessage: '限制{maxLength}个字符'
  //     }
  //   ]
  // },
  realname: {
    rules: [
      {
        required: true,
        errorMessage: '请输入姓名'
      },
      {
        maxLength: useGlobal().textMax,
        errorMessage: '限制{maxLength}个字符'
      }
    ]
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: '请输入密码'
      },
      {
        validateFunction: verifyPwd
      }
    ]
  },
  passwordAgain: {
    rules: [
      {
        required: true,
        errorMessage: '请再次输入密码'
      },
      {
        validateFunction: function (rule, value, data, callback) {
          if (value !== data.password) {
            callback('两次输入密码不一致')
          }
          return true
        }
      }
    ]
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: '请输入验证码'
      }
    ]
  },
  mobile: {
    rules: [
      {
        required: true,
        errorMessage: '请输入手机号'
      },
      {
        validateFunction: validatorMobile
      }
    ]
  }
}
// 表单组件实例
const registerRef = ref<UniHelper.UniFormsInstance>()
// 表单信息
const registerForm = ref({
  // username: '',
  realname: '',
  password: '',
  mobile: '',
  uuid: '',
  code: '',
  passwordAgain: ''
})

const getRegisterCaptchaInfo = (val: captchaInfo) => {
  isShowCaptcha = val.captchaEnabled
  registerForm.value.uuid = val.uuid
  registerForm.value.code = val.code
}

const handleRegisterSubmit = () => {
  registerRef.value?.validate?.((err, formData) => {
    if (!err) {
      uni.showLoading()
      registerApi(registerForm.value)
        .then(() => {
          // 注册成功，返回登录
          uni.showToast({
            title: '操作成功',
            icon: 'none'
          })
          type.value = 1
        })
        .catch(() => {
          captchaRef.value?.getCaptchaImage()
        })
    }
  })
}

// 忘记密码
// 表单信息
const pwdForm = ref({
  passwordAgain: '',
  password: '',
  phonenumber: '',
  smsCode: ''
})
// 表单校验
const pwdRules: UniHelper.UniFormsRules = {
  password: {
    rules: [
      {
        required: true,
        errorMessage: '请输入密码'
      },
      {
        validateFunction: verifyPwd
      }
    ]
  },
  passwordAgain: {
    rules: [
      {
        required: true,
        errorMessage: '请再次输入密码'
      },
      {
        validateFunction: function (rule, value, data, callback) {
          if (value !== data.password) {
            callback('两次输入密码不一致')
          }
          return true
        }
      }
    ]
  },
  phonenumber: {
    rules: [
      {
        required: true,
        errorMessage: '请输入手机号'
      },
      {
        validateFunction: validatorMobile
      }
    ]
  },
  smsCode: {
    rules: [
      {
        required: true,
        errorMessage: '请输入验证码'
      }
    ]
  }
}
const pwdFormRef = ref<UniHelper.UniFormsInstance>()
const handlePwdSubmit = async () => {
  pwdFormRef.value?.validate?.((err, formData) => {
    if (!err) {
      uni.showLoading()
      forgetApi(form.value).then(() => {
        // 注册成功，返回登录
        uni.showToast({
          title: '操作成功',
          icon: 'none'
        })
        type.value = 1
      })
    }
  })
}

let type = ref(1) // 1登录 2注册
const changeType = (index: number) => {
  type.value = index
  if (index === 2) {
    registerForm.value = {
      // username: '',
      realname: '',
      password: '',
      mobile: '',
      uuid: '',
      code: ''
    }
    registerRef.value?.setRules?.(registerRules)
    registerRef.value?.clearValidate()
  } else if (type.value === 3) {
    pwdForm.value = {
      passwordAgain: '',
      password: '',
      phonenumber: '',
      smsCode: ''
    }
    pwdFormRef.value?.setRules?.(pwdRules)
    pwdFormRef.value?.clearValidate()
  } else {
    form.value = {
      username: '',
      password: '',
      code: '',
      phonenumber: '',
      smsCode: '',
      type: 2,
      uuid: '',
      openId: ''
    }
    formRef.value?.clearValidate()
  }
}
// 获取手机号
const getphonenumber = (val: { detail: { code: string } }) => {
  if (val.detail && val.detail.code) {
    uni.showLoading()
    phoneLoginApi({ code: val.detail.code }).then((res) => {
      // 存储token
      userStore.setToken(res?.data?.token)
      setTimeout(() => {
        refreshUserInfo()
      }, 100)
    })
  }
}
// 取消绑定
const cancelBind = () => {
  isBind.value = 0
}

onLoad(async () => {
  await systemStore.getConfigData()
})
onReady(() => {
  formRef.value?.setRules?.(rules)
})
// 下拉刷新
// onPullDownRefresh(async () => {
//   await systemStore.getConfigData()
//   uni.stopPullDownRefresh()
// })
</script>

<template>
  <view class="login-box">
    <view class="login-top flex a-ccenter f20 white-color f-wrap pl20">
      <view class="w100">您好，</view>
      <view>欢迎使用{{ systemStore.config.name || '智慧园区管理系统' }}</view>
    </view>
    <view class="flex j-sb a-c w100 login-action">
      <view v-if="type < 3" class="w50 tc f14" :class="[type === 1 && 'weight-600']" @click="changeType(1)">登录</view>
      <view v-if="type < 3 && systemStore.config.register === 'true'" class="w50 tc f14" :class="[type === 2 && 'weight-600']" @click="changeType(2)"
        >注册</view
      >
      <view v-if="type === 3" class="w50 tc f14 weight-600">忘记密码</view>
    </view>
    <view v-if="type === 1 || type === 3" class="triangle triangle-left"></view>
    <view v-if="type === 2" class="triangle triangle-right"></view>
    <view class="center-box">
      <!-- 登录 -->
      <uni-forms v-if="type === 1" ref="formRef" :model="form" :rules="rules" label-position="top" label-width="0">
        <!-- 短信登录 -->
        <template v-if="form.type === 1">
          <uni-forms-item name="phonenumber">
            <template #label>
              <view class="form-title">
                <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe6d9;</uni-icons>
                手机号
              </view>
            </template>
            <uni-easyinput type="text" v-model="form.phonenumber" placeholder="请输入手机号" />
          </uni-forms-item>
          <uni-forms-item name="smsCode">
            <template #label>
              <view class="form-title">
                <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe619;</uni-icons>
                验证码
              </view>
            </template>
            <view class="flex j-sb a-center w100">
              <uni-easyinput type="text" v-model="form.smsCode" placeholder="请输入验证码" />
              <view v-if="isDisabled" class="sms-btn weight-600 gray-color">
                {{ countdown + 's后重新获取' }}
              </view>
              <view v-else class="sms-btn weight-600 primary-color" @tap="getSmsCode(1)"> 获取验证码 </view>
            </view>
          </uni-forms-item>
        </template>
        <!-- 密码登录|微信绑定 -->
        <template v-if="form.type === 2 || isBind">
          <uni-forms-item name="username">
            <template #label>
              <view class="form-title">
                <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe6d9;</uni-icons>
                手机号
              </view>
            </template>
            <uni-easyinput type="text" v-model="form.username" placeholder="请输入手机号" @clear="handleClear" />
          </uni-forms-item>
          <uni-forms-item name="password">
            <template #label>
              <view class="form-title">
                <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe638;</uni-icons>
                密码
              </view>
            </template>
            <uni-easyinput type="password" v-model="form.password" placeholder="请输入密码" />
          </uni-forms-item>
          <uni-forms-item v-if="isShowCaptcha && systemStore.config.captcha === 'true' && !isBind" name="code">
            <template #label>
              <view class="form-title">
                <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe619;</uni-icons>
                验证码
              </view>
            </template>
            <Captcha ref="captchaRef" @getCaptchaInfo="getCaptchaInfo" class="w100" />
          </uni-forms-item>
        </template>
      </uni-forms>
      <!-- 注册 -->
      <uni-forms v-if="type === 2" ref="registerRef" :model="registerForm" :rules="registerRules" label-position="top" label-width="0">
        <uni-forms-item name="mobile">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe6d9;</uni-icons>
              手机号
            </view>
          </template>
          <uni-easyinput type="text" v-model="registerForm.mobile" placeholder="请输入手机号" />
        </uni-forms-item>
        <!-- <uni-forms-item name="username">
          <template #label>
            <view class="form-title">
              <uni-icons type="person" color="#2E62AF" size="14" />
              用户名
            </view>
          </template>
          <uni-easyinput type="text" v-model="registerForm.username" placeholder="请输入用户名" />
        </uni-forms-item> -->
        <uni-forms-item name="realname">
          <template #label>
            <view class="form-title">
              <uni-icons type="person-filled" color="#2E62AF" size="14" />
              姓名
            </view>
          </template>
          <uni-easyinput type="text" v-model="registerForm.realname" placeholder="请输入姓名" />
        </uni-forms-item>
        <uni-forms-item name="password">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe638;</uni-icons>
              密码
            </view>
          </template>
          <uni-easyinput type="password" v-model="registerForm.password" placeholder="请输入密码" />
        </uni-forms-item>
        <uni-forms-item name="passwordAgain">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe638;</uni-icons>
              确认密码
            </view>
          </template>
          <uni-easyinput type="password" v-model="registerForm.passwordAgain" placeholder="请再次输入密码" />
        </uni-forms-item>
        <uni-forms-item v-if="isShowCaptcha && systemStore.config.captcha === 'true'" name="code">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe619;</uni-icons>
              验证码
            </view>
          </template>
          <Captcha ref="captchaRef" @getCaptchaInfo="getCaptchaInfo" class="w100" />
        </uni-forms-item>
      </uni-forms>
      <!-- 忘记密码 -->
      <uni-forms v-if="type === 3" ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-position="top" label-width="0">
        <uni-forms-item name="phonenumber">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe6d9;</uni-icons>
              手机号
            </view>
          </template>
          <uni-easyinput type="text" v-model="pwdForm.phonenumber" placeholder="请输入手机号" />
        </uni-forms-item>
        <uni-forms-item name="smsCode">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe619;</uni-icons>
              验证码
            </view>
          </template>
          <view class="flex j-sb a-center w100">
            <uni-easyinput type="text" v-model="pwdForm.smsCode" placeholder="请输入验证码" />
            <view v-if="isDisabled" class="sms-btn weight-600 gray-color">
              {{ countdown + 's后重新获取' }}
            </view>
            <view v-else class="sms-btn weight-600 primary-color" @tap="getSmsCode(2)"> 获取验证码 </view>
          </view>
        </uni-forms-item>
        <uni-forms-item name="password">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe638;</uni-icons>
              新密码
            </view>
          </template>
          <uni-easyinput type="password" v-model="pwdForm.password" placeholder="请输入密码" />
        </uni-forms-item>
        <uni-forms-item name="passwordAgain">
          <template #label>
            <view class="form-title">
              <uni-icons fontFamily="iconfont" color="#2E62AF" size="14">&#xe638;</uni-icons>
              确认密码
            </view>
          </template>
          <uni-easyinput type="password" v-model="pwdForm.passwordAgain" placeholder="请再次输入新密码" />
        </uni-forms-item>
      </uni-forms>
      <!-- 登录操作 -->
      <template v-if="type === 1">
        <view v-if="systemStore.config.sms === 'true'" class="f12 mb20 mt10 primary-color weight-600 flex a-c j-sb">
          <text @tap="loginTypeChange">{{ form.type === 2 ? '短信验证码登录' : '密码登录' }}</text>
          <!-- <text @tap="handleForget">忘记密码</text> -->
          <text @tap="changeType(3)">忘记密码</text>
        </view>
        <view class="btn-b gradual-primary" @tap="handleSubmit">{{ isBind ? '绑 定' : '登 录' }}</view>
        <!-- #ifdef MP-WEIXIN -->
        <view v-if="!isBind" class="tc m10 gray-color f12">OR</view>
        <view v-if="!isBind" class="btn-b plain-bg primary-color mb10" @tap="handleUserProfile">微信一键登录</view>
        <!-- #endif -->
        <button v-if="!isBind" type="primary" open-type="getPhoneNumber" @getphonenumber="getphonenumber" class="btn-b plain-bg primary-color">
          手机号登录
        </button>
        <view v-if="isBind" class="f12 mt20 primary-color weight-600" @click="cancelBind"
          ><uni-icons type="left" size="12" color="#2e62af"></uni-icons>返回</view
        >
      </template>
      <!-- 注册 -->
      <view v-if="type === 2" class="btn-b gradual-primary" @tap="handleRegisterSubmit">确 定</view>
      <!-- 忘记密码 -->
      <template v-if="type === 3">
        <view class="f12 mb20 mt10 primary-color weight-600 flex a-c j-sb">
          <text @tap="changeType(1)">返回</text>
        </view>
        <view class="btn-b gradual-primary" @tap="handlePwdSubmit">确 定</view>
      </template>
    </view>
    <!-- <view v-if="type === 1" class="gray-color f12 tc w100 agreement"> 登录即代表已阅读并同意<text class="primary-color">《用户协议》</text></view> -->
  </view>
</template>

<style lang="scss" scoped>
.login-box {
  width: 100vw;
  height: 100vh;
  position: relative;
  background: #fff;
  .login-top {
    height: 550rpx;
    background: url('http://1.94.6.75:9000/zlhy-app/bg_activity.jpg') center no-repeat;
    background-size: 100% 100%;
  }
  .login-action {
    position: absolute;
    left: 0;
    top: 400rpx;
    color: #fff;
  }
  :deep(.center-box) {
    // width: calc(100vw - 100rpx);
    width: 100%;
    min-height: 200px;
    border-radius: 50rpx;
    background: #fff;
    position: absolute;
    left: 0;
    top: 480rpx;
    padding: 50rpx;
    .btn-b {
      width: 100% !important;
    }
    .is-input-border {
      border-radius: 0;
      border: 0;
      border-bottom: 1px solid #dcdfe6;
    }
    .form-title {
      font-size: 28rpx;
      font-weight: bold;
    }
  }
  .triangle {
    width: 0;
    height: 0;
    border-left: 100rpx solid #fff;
    border-top: 200rpx solid #fff;
    border-right: 200rpx solid transparent;
    border-bottom: 100rpx solid transparent;
    transform: rotate(45deg);
    border-top-left-radius: 5rpx;
    position: absolute;
    top: 520rpx;
  }
  .triangle-left {
    left: 37rpx;
  }
  .triangle-right {
    right: 37rpx;
  }
  .sms-btn {
    height: 35px;
    line-height: 35px;
    border-bottom: 1px solid #dcdfe6;
    border-radius: 0 !important;
    font-size: 24rpx;
  }
  .forget {
    .line {
      width: 1px;
      height: 10px;
      background-color: #333;
    }
  }
  .agreement {
    position: absolute;
    bottom: 50rpx;
    left: 0;
  }
}
</style>
