<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <el-dialog
    v-model="visible"
    :title="dataForm.supplierUserId? $t('table.edit'): $t('table.create')"
    width="600px"
    :close-on-click-modal="false"
    class="Mall4j"
    @close="close"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="dataFormRef"
      :rules="dataForm.supplierUserId? updateDataRule : dataRule"
      :model="dataForm"
      label-position="right"
      label-width="80px"
      style="width: 90%;"
      @submit.prevent
    >
      <!-- 昵称 -->
      <el-form-item
        :label="$t('multishop.shopUser.nickName')"
        prop="nickName"
      >
        <el-input
          v-model="dataForm.nickName"
          maxlength="30"
          show-word-limit
          :placeholder="$t('multishop.shopUser.nickNameTips')"
        />
      </el-form-item>
      <!-- 用户名 -->
      <el-form-item
        :label="$t('multishop.shopUser.username')"
        prop="username"
      >
        <el-input
          v-model="dataForm.username"
          maxlength="16"
          show-word-limit
          :placeholder="$t('register.username')"
        />
      </el-form-item>
      <!-- 手机号 -->
      <el-form-item
        :label="$t('multishop.shopUser.mobileNumber')"
        prop="phone"
      >
        <el-input
          v-model="dataForm.phone"
          maxlength="11"
          show-word-limit
          :placeholder="$t('register.mobile')"
          @input="phoneInput"
          @change="changePhone"
        />
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item
        v-if="validCodeVisible"
        :label="$t('multishop.shopUser.validCode')"
        prop="validCode"
      >
        <el-input
          v-model="dataForm.validCode"
          type="text"
          :placeholder="$t('shop.pleaseEnteCode')"
          maxlength="6"
          autocomplete="off"
        >
          <template #append>
            <el-button
              v-if="countdown === 0"
              @click="getCode"
            >
              {{ $t('shop.getVerificationCode') }}
            </el-button>
            <div
              v-else
              class="get-code"
            >
              {{ countdown }} s
            </div>
          </template>
        </el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item
        :label="$t('multishop.shopUserAccount.password')"
        prop="password"
      >
        <el-input
          v-model="dataForm.password"
          v-input-rule
          autocomplete="new-password"
          type="password"
          maxlength="20"
          show-password
          show-word-limit
          :placeholder="$t('login.passwordTips')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('multishop.shopUserAccount.email')"
        prop="email"
      >
        <el-input
          v-model="dataForm.email"
          maxlength="50"
          show-word-limit
          :placeholder="$t('multishop.shopUser.emailTips')"
        />
      </el-form-item>
      <!-- 选择角色 -->
      <el-form-item
        v-if="dataForm.isAdmin === 0"
        :label="$t('multishop.shopUser.selectRole')"
        prop="roleIds"
      >
        <el-select
          v-model="dataForm.roleIds"
          multiple
          :placeholder="$t('tip.select')"
        >
          <el-option
            v-for="item in roleOpts"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          />
        </el-select>
      </el-form-item>
      <!-- 状态 -->
      <el-form-item
        v-if="dataForm.isAdmin === 0"
        :label="$t('multishop.shopUserAccount.status')"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">
            {{ $t('table.normal') }}
          </el-radio>
          <el-radio :label="0">
            {{ $t('table.disable') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          plain
          @click="visible = false"
        >
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import * as api from '@/api/multishop/shop-user'
import * as roleApi from '@/api/rbac/role'
import { Debounce } from '@/utils/debounce'
import { MOBILE_REGEXP, STAR_MOBILE_REGEXP, USER_NAME_REGEXP, EMAIL_REGEXP, validNoEmptySpace, noSpacesBothSides, validPassword2 } from '@/utils/validate'
import { getAddShopUserCode } from '@/api/auth/auth'
import { encrypt } from '@/utils/crypto'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const validCodeVisible = ref(true)
// 未修改的手机号
let phoneDb = null
const countdown = ref(0)
const mobileErrTips = ref(false)
const dataForm = reactive({
  supplierUserId: null,
  userId: null,
  supplierId: null,
  nickName: null,
  username: null,
  password: null,
  comfirmPassword: null,
  isAdmin: 0,
  code: null,
  phone: null,
  phoneNum: null,
  validCode: null,
  email: null,
  hasAccount: null,
  status: 1,
  roleIds: []
})
const roleOpts = ref([])
// eslint-disable-next-line no-unused-vars
const validPassword = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('multishop.shopUser.pwdBlank')))
  } else if (noSpacesBothSides(value)) {
    callback(new Error($t('multishop.shopUser.pwdNoBlank')))
  } else if (!(dataForm.supplierUserId && !value) && !validPassword2(value)) {
    callback(new Error('密码由字母、数字和特殊符号三种字符组成8-20位半角字符，区分大小写'))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateComfirmPassword = (rule, value, callback) => {
  if (dataForm.password !== value) {
    callback(new Error($t('resetPassword.passwordError')))
  } else {
    callback()
  }
}

// 新增时的验证规则
const dataRule = reactive({
  nickName: [
    { required: true, message: $t('multishop.shopUser.nickNameEmpty'), trigger: 'blur' }
  ],
  phone: [
    { required: true, message: $t('multishop.shopUser.phoneEmpty'), trigger: 'blur' },
    { pattern: MOBILE_REGEXP, message: $t('multishop.shopUser.phoneError') }
  ],
  validCode: [
    { required: true, message: $t('register.validCode'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: $t('login.passwordTips'), trigger: 'blur' },
    { validator: validPassword, trigger: 'blur' }
  ],
  comfirmPassword: [
    { required: true, message: $t('login.passwordEmpty'), trigger: 'blur' },
    { validator: validateComfirmPassword, trigger: 'blur' }
  ],
  username: [
    { required: true, message: $t('multishop.shopUser.usernameEmpty'), trigger: 'blur' },
    { pattern: USER_NAME_REGEXP, message: $t('register.usernameErrTips') }
  ],
  email: [
    { pattern: EMAIL_REGEXP, message: $t('multishop.shopUser.emailError') }
  ]

})
// 修改时的验证规则
const updateDataRule = reactive({
  nickName: [
    { required: true, message: $t('multishop.shopUser.nickNameEmpty'), trigger: 'blur' }
  ],
  phone: [
    { required: true, message: $t('multishop.shopUser.phoneEmpty'), trigger: 'blur' },
    { pattern: STAR_MOBILE_REGEXP, message: $t('multishop.shopUser.phoneError') }
  ],
  validCode: [
    { required: true, message: $t('register.validCode'), trigger: 'blur' }
  ],
  password: [
    { min: 6, max: 20, message: $t('resetPassword.passwordTips3'), trigger: 'blur' },
    { validator: validPassword, trigger: 'blur' }
  ],
  comfirmPassword: [
    { required: true, message: $t('multishop.shopUser.comfirmPasswordEmpty'), trigger: 'blur' },
    { validator: validateComfirmPassword, trigger: 'blur' }
  ],
  username: [
    { required: true, message: $t('multishop.shopUser.usernameEmpty'), trigger: 'blur' },
    { pattern: USER_NAME_REGEXP, message: $t('register.usernameErrTips') }
  ],
  email: [
    { pattern: EMAIL_REGEXP, message: $t('multishop.shopUser.emailError') }
  ]
})

const dataFormRef = ref(null)
const init = (supplierUserId) => {
  dataForm.isAdmin = 0
  dataForm.validCode = null
  dataForm.comfirmPassword = null
  countdown.value = 0
  visible.value = true
  phoneDb = null
  nextTick(() => {
    validCodeVisible.value = !supplierUserId
    roleApi.list().then(data => {
      roleOpts.value = data
    })
    if (supplierUserId && supplierUserId !== 0) {
      api.get(supplierUserId).then(data => {
        dataForm.isAdmin = data.isAdmin
        dataForm.username = data.username
        dataForm.nickName = data.nickName
        dataForm.email = data.email
        dataForm.phoneNum = data.phoneNum
        dataForm.phone = data.phone
        dataForm.roleIds = data.roleIds
        dataForm.status = data.status
        dataForm.supplierUserId = supplierUserId || 0
        phoneDb = dataForm.phone
      })
    } else {
      dataForm.supplierUserId = 0
      setTimeout(() => {
        dataFormRef.value.resetFields()
        dataFormRef.value.clearValidate()
      }, 50)
    }
  })
}

let timer = null
const getCountdown = () => {
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const close = () => {
  dataFormRef.value.resetFields()
  dataFormRef.value.clearValidate()
}

/**
 * 获取验证码
 */
const getCode = Debounce(() => {
  mobileErrTips.value = false
  dataFormRef.value.validateField(['phone'], (valid) => {
    if (valid) {
      mobileErrTips.value = true
    }
  })
  if (mobileErrTips.value) {
    return
  }
  const phoneObj = {
    mobile: dataForm.phone,
    shopAccount: 1
  }

  // 在发送验证码之前，验证一下该电话号码是否存在
  const param = dataForm
  param.roleIds = []
  api.verifyAccount(param).then(data => {
    if (!data) {
      // 验证不通过
      mobileErrTips.value = true
    } else {
      getAddShopUserCode(phoneObj).then(() => {
        countdown.value = 60
        getCountdown()
      }).catch(() => {
      })
    }
  })
}, 1500)

// 修改手机号码
const changePhone = () => {
  if (!dataForm.supplierUserId) {
    return
  }
  validCodeVisible.value = phoneDb !== dataForm.phone
}

const phoneInput = (val) => {
  let rex = /[^\d]/g
  if (dataForm.supplierUserId) {
    rex = /[^\d|*]/g
  }
  dataForm.phone = val.replace(rex, '')
}

// 表单提交
const onSubmit = Debounce(() => {
  dataFormRef.value.validate(valid => {
    if (valid) {
      const data = JSON.parse(JSON.stringify(dataForm))
      // 删除comfirmPassword这个属性
      Reflect.deleteProperty(data, 'comfirmPassword')
      // 不填写密码默认是不更改
      if (data.password) {
        data.password = encrypt(data.password)
      }
      const request = data.supplierUserId ? api.update(data) : api.save(data)
      request.then(() => {
        ElMessage({
          message: $t('table.actionSuccess'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            countdown.value = 0
            clearInterval(timer)
            emit('refreshDataList')
            dataFormRef.value.resetFields()
          }
        })
      })
    }
  })
}, 1500)

defineExpose({ init })

</script>
