<template>
  <div class="main-content">
    <BaseTable
      :tableHeader="tableHeader"
      :tableData="tableData"
      :tableOperate="tableOperate"
      :searchParams="searchParams"
      @searchFn="searchFn"
      @resetFn="resetFn"
      @addFn="addFn"
    >
      <template #search>
        <el-form-item label="姓名">
          <el-input v-model.trim="searchParams.fullName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model.trim="searchParams.mobile" placeholder="请输入手机号" />
        </el-form-item>
      </template>
    </BaseTable>

    <el-dialog :title="formDialog.title" v-model="formDialog.visible" :close-on-click-modal="false">
      <el-form ref="formRef" size="small" label-width="120px" :model="formDialog.formData" :rules="rules">
        <el-form-item label="用户名" prop="username" v-if="formDialog.isAdd">
          <el-input v-model.trim="formDialog.formData.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model.trim="formDialog.formData.fullName" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model.trim="formDialog.formData.mobile" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="formDialog.loading" @click="submitFn">确定</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
  queryTenantUserPage, createTenantUser, updateTenantUserDetail,
  removeTenantUser, fetchTenantUserById
} from '@/api/tenant'
import { isMobile, isUsername } from '@/utils/validate'
import type { FormInstance, FormRules } from 'element-plus'

const formRef = ref<FormInstance>()

const defaultSearch = { current: 1, size: 10, total: 0 }

const searchParams = reactive({
  ...defaultSearch,
  fullName: '',
  mobile: ''
})

const tableHeader = [
  { label: '姓名', prop: 'fullName', align: 'center' as const, minWidth: 120 },
  { label: '用户名', prop: 'username', align: 'center' as const, minWidth: 120 },
  { label: '手机号', prop: 'mobile', align: 'center' as const, minWidth: 120 }
]

const tableData = ref<any[]>([])

const tableOperate = [
  { label: '编辑', type: 'primary', icon: 'el-icon-edit', func: (row: any) => editFn(row) },
  { label: '删除', type: 'danger', icon: 'el-icon-delete', func: (row: any) => delFn(row) }
]

const formDialog = reactive({
  title: '',
  visible: false,
  loading: false,
  isAdd: false,
  formData: {} as any
})

const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { validator: (_r: any, v: string, cb: any) => isUsername(v) ? cb() : cb(new Error('用户名格式不正确')), trigger: 'blur' }
  ],
  fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { validator: (_r: any, v: string, cb: any) => isMobile(v) ? cb() : cb(new Error('请输入正确手机号')), trigger: 'blur' }
  ]
}

function searchFn(isReset = false) {
  if (isReset) Object.assign(searchParams, defaultSearch)
  queryTenantUserPage(searchParams).then(
    (res: any) => {
      tableData.value = res.data.records
      searchParams.total = res.data.total
    },
    (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  )
}

function resetFn() {
  Object.assign(searchParams, defaultSearch, { fullName: '', mobile: '' })
  searchFn()
}

function addFn() {
  formDialog.title = '新增'
  formDialog.visible = true
  formDialog.isAdd = true
  formDialog.formData = {}
}

function editFn(row: any) {
  formDialog.title = '编辑'
  formDialog.isAdd = false
  fetchTenantUserById({ id: row.id }).then(
    (res: any) => {
      formDialog.formData = { ...res.data }
      formDialog.visible = true
    },
    (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  )
}

function cancelFn() {
  formDialog.visible = false
  formDialog.formData = {}
  formRef.value?.resetFields()
}

function submitFn() {
  if (!formRef.value) return
  formDialog.loading = true
  formRef.value.validate((valid: boolean) => {
    if (!valid) { formDialog.loading = false; return }
    const api = formDialog.formData.id ? updateTenantUserDetail : createTenantUser
    api(formDialog.formData).then(
      () => {
        ElMessage.success(formDialog.formData.id ? '修改成功' : '新增成功')
        formDialog.visible = false
        formDialog.loading = false
        searchFn(true)
      },
      (error: any) => {
        ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
        formDialog.loading = false
      }
    )
  })
}

function delFn(row: any) {
  ElMessageBox.confirm('此操作将删除该记录, 是否继续?', '提示', { type: 'warning' }).then(() => {
    removeTenantUser({ ids: [row.id] }).then(
      () => { ElMessage.success('删除成功'); searchFn(true) },
      (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    )
  })
}

searchFn()
</script>
