<template>
  <div class="bind-user-phone-form">
    <el-drawer
      :title="$t('pages.userAuthForm.drawer.title')"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div v-loading="authLoading" class="user-auth-type" style="padding: 10px;">
        <el-card class="box-card" style="margin-top:0px;">
          <div slot="header" class="clearfix">
            <span>{{ $t('pages.userAuthForm.section.authenticatedTypes') }}</span>
          </div>
          <div class="text item" style="">
            <div
              style="display: flex;
                  flex-wrap: wrap;
                  flex-direction: column;
                  justify-content: space-between;"
            >
              <div
                v-for="(item, index) in userAuthList"
                :key="index"
                style="display: flex; align-items: center; justify-content: space-between; height: 1.2rem;"
              >
                <div style="margin-right: 0.5rem;"><el-tag type="success">{{ item.type }}</el-tag></div>
                <div>{{ item.openId }}</div>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="box-card" style="margin-top: 10px;">
          <div slot="header" class="clearfix">
            <span>{{ $t('pages.userAuthForm.section.phoneBinding') }}</span>
            <el-button v-if="!(userMobileAuth || {}).id" type="text" @click="handleCreate()">{{ $t('pages.userAuthForm.action.bind') }}</el-button>
          </div>
          <div v-if="(userMobileAuth || {}).id && editBoxVisible == false" class="text item">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <div>{{ userMobileAuth.phonePrefix }}-{{ userMobileAuth.phoneNumber }}</div>
              <div><el-tag type="success">{{ $t('pages.userAuthForm.status.bound') }}</el-tag></div>
              <div>
                <el-button type="text" @click="handleUpdateMobileAuth()">{{ $t('pages.userAuthForm.action.rebind') }}</el-button>
                <el-button type="text" @click="handleDelete()">{{ $t('pages.userAuthForm.action.delete') }}</el-button>
              </div>
            </div>
          </div>
          <div v-if="editBoxVisible" class="text item">
              <el-form
              ref="formData"
              v-loading="listLoading"
              :rules="localizedRules"
              :model="formData"
              label-position="left"
              label-width="70px"
              style="width: 400px; margin-left:50px;"
            >

              <el-form-item>
                <el-col :span="7">
                  <el-form-item prop="phonePrefix">
                    <el-input
                      v-model.trim="formData.phonePrefix"
                      v-number
                      :placeholder="$t('pages.userAuthForm.placeholder.phonePrefix')"
                      maxlength="7"
                    />
                  </el-form-item>
                </el-col>
                <el-col class="line" :span="2" style="text-align: center;">-</el-col>
                <el-col :span="15">
                  <el-form-item prop="phoneNumber">
                    <el-input
                      v-model.trim="formData.phoneNumber"
                      v-number
                      :placeholder="$t('pages.userAuthForm.placeholder.phoneNumber')"
                      maxlength="20"
                    />
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item prop="pwd">
                <el-input
                  v-model="formData.pwd"
                  :placeholder="$t('pages.userAuthForm.placeholder.password')"
                />
              </el-form-item>
              <div style="text-align: center;">
                <el-button @click="handleCancel()">
                  {{ $t('pages.userAuthForm.action.cancel') }}
                </el-button>
                <el-button
                  type="primary"
                  @click="handleSubmit()"
                >
                  {{ $t('pages.userAuthForm.action.submit') }}
                </el-button>
              </div>
            </el-form>
          </div>
        </el-card>
        <el-card class="box-card" style="margin-top: 10px;">
          <div slot="header" class="clearfix">
            <span>{{ $t('pages.userAuthForm.section.accountPasswordLoginCount') }}</span>
            <el-button type="text" @click="initAccountLogin()">{{ $t('pages.userAuthForm.action.reset') }}</el-button>
            <br>
            <span>{{ $t('pages.userAuthForm.section.accountLogin') }}</span>
            <el-button type="text" @click="deleteAccountLogin()">{{ $t('pages.userAuthForm.action.delete') }}</el-button>
          </div>
        </el-card>
        <el-card class="box-card" style="margin-top: 10px;">
          <div slot="header" class="clearfix">
            <span>{{ $t('pages.userAuthForm.section.payPasswordErrorCount') }}</span>
            <el-button type="text" @click="initPayAuth()">{{ $t('pages.userAuthForm.action.reset') }}</el-button>
            <br>
            <span>{{ $t('pages.userAuthForm.section.payPassword') }}</span>
            <el-button type="text" @click="deletePayAuth()">{{ $t('pages.userAuthForm.action.delete') }}</el-button>
          </div>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getUserAuthTypeDetails, editUserMobileAuth, deleteUserMobileAuth, initUserAccountLogin, deleteUserAccountLogin, initUserPayAuth, deleteUserPayAuth } from '@/api/app-user'
function getFormData() {
  return {
    phonePrefix: '',
    phoneNumber: '',
    pwd: '',
    userId: '',
    id: ''
  }
}
export default {
  name: 'UserAuthForm',
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      listLoading: false,
      authLoading: false,
      userAuthList: [],
      userMobileAuth: {},
      editBoxVisible: false,
      formData: getFormData()
    }
  },
  computed: {
    localizedRules() {
      const commonRules = [this.getRequiredRule()]
      return {
        phonePrefix: commonRules,
        phoneNumber: commonRules,
        pwd: commonRules
      }
    }
  },
  watch: {
    userId: {
      handler(newVal) {
        if (newVal) {
          this.renderData()
        }
      },
      immediate: true
    }
  },
  methods: {
    getRequiredRule() {
      return {
        required: true,
        message: this.$t('pages.userAuthForm.validation.requiredField'),
        trigger: 'blur'
      }
    },
    renderData() {
      const that = this
      that.authLoading = true
      getUserAuthTypeDetails(that.userId).then(res => {
        that.userAuthList = res.body.auths
        that.userMobileAuth = res.body.userMobileAuth
        that.authLoading = false
        // Object.assign(that.formData, res.result)
      }).catch(er => {
        that.authLoading = false
      })
    },
    handleDelete() {
      const that = this
      that.$confirm(that.$t('pages.userAuthForm.confirm.delete'), that.$t('pages.userAuthForm.confirm.title'), {
        type: 'warning'
      }).then(() => {
        that.listLoading = true
        deleteUserMobileAuth(that.userId).then((res) => {
          that.listLoading = false
          that.$message.success(that.$t('pages.userAuthForm.message.deleteSuccess'))
          that.$emit('success', {})
          that.renderData()
          that.handleCancel()
        })
      }).catch(() => {

      })
    },
    handleSubmit() {
      const that = this
      that.$refs.formData.validate((valid) => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        if (Number((that.formData.phonePrefix + '').substring(0, 1)) <= 0) {
          that.$message.error(that.$t('pages.userAuthForm.validation.phonePrefixCannotStartWithZero'))
          return
        }
        that.listLoading = true
        editUserMobileAuth(that.formData).then(res => {
          that.listLoading = false
          that.$emit('success', Object.assign({}, that.formData))
          that.renderData()
          that.handleCancel()
        }).catch(err => {
          that.listLoading = false
          that.$emit('fial', err)
        })
      })
    },
    handleCreate() {
      this.formData = getFormData()
      this.formData.userId = this.userId
      this.editBoxVisible = true
    },
    initAccountLogin() {
      const that = this
      that.$confirm(that.$t('pages.userAuthForm.confirm.reset'), that.$t('pages.userAuthForm.confirm.title'), {
        type: 'warning'
      }).then(() => {
        that.listLoading = true
        initUserAccountLogin(that.userId).then((res) => {
          that.listLoading = false
          that.$message.success(that.$t('pages.userAuthForm.message.resetSuccess'))
          that.$emit('success', {})
          that.renderData()
          that.handleCancel()
        })
      }).catch(() => {

      })
    },
    deleteAccountLogin() {
      const that = this
      that.$confirm(that.$t('pages.userAuthForm.confirm.delete'), that.$t('pages.userAuthForm.confirm.title'), {
        type: 'warning'
      }).then(() => {
        that.listLoading = true
        deleteUserAccountLogin(that.userId).then((res) => {
          that.listLoading = false
          that.$message.success(that.$t('pages.userAuthForm.message.deleteSuccess'))
          that.$emit('success', {})
          that.renderData()
          that.handleCancel()
        })
      }).catch(() => {
      })
    },
    initPayAuth() {
      const that = this
      that.$confirm(that.$t('pages.userAuthForm.confirm.reset'), that.$t('pages.userAuthForm.confirm.title'), {
        type: 'warning'
      }).then(() => {
        that.listLoading = true
        initUserPayAuth(that.userId).then((res) => {
          that.listLoading = false
          that.$message.success(that.$t('pages.userAuthForm.message.resetSuccess'))
          that.$emit('success', {})
          that.renderData()
          that.handleCancel()
        })
      }).catch(() => {

      })
    },
    deletePayAuth() {
      const that = this
      that.$confirm(that.$t('pages.userAuthForm.confirm.delete'), that.$t('pages.userAuthForm.confirm.title'), {
        type: 'warning'
      }).then(() => {
        that.listLoading = true
        deleteUserPayAuth(that.userId).then((res) => {
          that.listLoading = false
          that.$message.success(that.$t('pages.userAuthForm.message.deleteSuccess'))
          that.$emit('success', {})
          that.renderData()
          that.handleCancel()
        })
      }).catch(() => {
      })
    },
    resetForm() {
      this.formData = getFormData()
    },
    handleUpdateMobileAuth() {
      this.formData.id = this.userMobileAuth.id
      this.formData.userId = this.userId
      this.formData.phonePrefix = this.userMobileAuth.phonePrefix
      this.formData.phoneNumber = this.userMobileAuth.phoneNumber
      this.editBoxVisible = true
    },
    handleCancel() {
      this.editBoxVisible = false
      this.resetForm()
    },
    handleClose() {
      this.$emit('close')
    }
  }
}
</script>
