<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.name" 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="name">
          <el-input v-model.trim="formDialog.formData.name" />
        </el-form-item>
        <el-form-item label="租户编码" prop="code">
          <el-input v-model.trim="formDialog.formData.code" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model.trim="formDialog.formData.contactName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model.trim="formDialog.formData.contactPhone" />
        </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 { queryTenantPage, createTenant, updateTenant, removeTenant, fetchTenantById } from '@/api/tenant'
import type { FormInstance, FormRules } from 'element-plus'

const formRef = ref<FormInstance>()

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

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

const tableHeader = [
  { label: '租户名称', prop: 'name', align: 'center' as const, minWidth: 150 },
  { label: '租户编码', prop: 'code', align: 'center' as const, minWidth: 120 },
  { label: '联系人', prop: 'contactName', align: 'center' as const, minWidth: 120 },
  { label: '联系电话', prop: 'contactPhone', align: 'center' as const, minWidth: 120 },
  { label: '创建时间', prop: 'createTime', align: 'center' as const, minWidth: 160 }
]

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,
  formData: {} as any
})

const rules: FormRules = {
  name: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入租户编码', trigger: 'blur' }]
}

function searchFn(isReset = false) {
  if (isReset) Object.assign(searchParams, defaultSearch)
  queryTenantPage(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, { name: '' })
  searchFn()
}

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

function editFn(row: any) {
  formDialog.title = '编辑'
  fetchTenantById({ 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 ? updateTenant : createTenant
    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(() => {
    removeTenant({ ids: [row.id] }).then(
      () => { ElMessage.success('删除成功'); searchFn(true) },
      (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    )
  })
}

searchFn()
</script>
