<template>
  <div class="main-content">
    <BaseTable
      ref="userTableRef"
      :tableHeader="tableHeader"
      :tableData="tableData"
      :tableOperate="tableOperate"
      :searchParams="searchParams"
      @searchFn="searchFn"
      @resetFn="resetFn"
      @addFn="addFn"
      @batchDelFn="batchDelFn"
    >
      <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 width="900px" :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="formDialog.formRules">
        <el-row>
          <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-item label="电子邮箱" prop="email">
            <el-input v-model.trim="formDialog.formData.email" />
          </el-form-item>
          <el-form-item label="角色" prop="roleIds" v-if="formDialog.isAdd">
            <el-select v-model="formDialog.formData.roleIds" multiple style="width: 100%">
              <el-option v-for="item in roles" :key="item.id" :label="item.roleCnName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formDialog.formData.sex">
              <el-radio-button v-for="item in dictSex" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="formDialog.loading" @click="submitFn">确定</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </template>
    </el-dialog>

    <el-dialog width="600px" :title="accountDialog.title" v-model="accountDialog.visible" :close-on-click-modal="false">
      <el-form ref="accountFormRef" size="small" label-width="120px" :model="accountDialog.formData">
        <el-form-item label="用户名">{{ accountDialog.formData.username }}</el-form-item>
        <el-form-item label="手机号">{{ accountDialog.formData.mobile }}</el-form-item>
        <el-form-item label="锁定账号">
          <el-switch
            v-model="accountDialog.formData.locked"
            active-color="#13ce66"
            active-value="1"
            inactive-value="0"
            @change="changeLockedFn"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="accountDialog.formData.roleIds" multiple @change="changeRole">
            <el-option v-for="item in roles" :key="item.id" :label="item.roleCnName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="修改密码">
          <el-col :span="12">
            <el-input v-model.trim="accountDialog.formData.password" type="password" />
          </el-col>
          <el-col :span="11" style="margin-left: 10px">
            <el-button type="primary" size="small" @click="resetPwdFn">修改密码</el-button>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="accountDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { formatDict } from '@/utils/global'
import { isMobile, isUsername } from '@/utils/validate'
import { queryRoleList } from '@/api/role'
import {
  addRole, changeLock, createUser, delRole,
  fetchUserById, queryUserAccount, queryUserPage,
  removeUser, resetPwd, updateUserDetail
} from '@/api/user'
import { useAppStore } from '@/stores/app'
import type { FormInstance, FormRules } from 'element-plus'

const appStore = useAppStore()
const formRef = ref<FormInstance>()
const accountFormRef = ref<FormInstance>()

const dictSex = computed(() => appStore.dict?.dictSex || [])

let userId = ''
let roleIds: string[] = []

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

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

const tableHeader = [
  { label: '姓名', align: 'center' as const, minWidth: 120, prop: 'fullName' },
  { label: '用户名', align: 'center' as const, minWidth: 120, prop: 'username' },
  {
    label: '性别', width: 80, align: 'center' as const, type: 'render',
    render: (_h: any, params: any) => formatDict(dictSex.value, params.row.sex)
  },
  { label: '手机号', prop: 'mobile', align: 'center' as const, minWidth: 120 },
  { label: '可视数据范围', prop: 'scopes', align: 'left' as const, minWidth: 200 },
  { label: '拥有角色', prop: 'roles', align: 'left' as const, minWidth: 200 }
]

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

const tableOperate = [
  { icon: 'el-icon-s-check', type: 'info', label: '账号相关', func: (row: any) => accountFn(row) },
  { 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,
  formRules: {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { validator: (_r: any, v: string, cb: any) => isUsername(v) ? cb() : cb(new Error('用户名英文字母开头, 6~20位')), trigger: 'blur' }
    ],
    fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    mobile: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { len: 11, message: '长度11个字符', trigger: 'blur' },
      { validator: (_r: any, v: string, cb: any) => isMobile(v) ? cb() : cb(new Error('请输入正确手机号')), trigger: 'blur' }
    ],
    email: [{ type: 'email', message: '请输入正确邮箱', trigger: 'blur' }],
    roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }]
  } as FormRules
})

const accountDialog = reactive({
  title: '账号相关',
  visible: false,
  formData: {} as any
})

function searchFn(isReset = false) {
  if (isReset) Object.assign(searchParams, defaultSearch)
  queryUserPage(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.loading = false
  formDialog.isAdd = true
  formDialog.formData = { sex: '3' }
}

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

function batchDelFn(rows: any[]) {
  if (!rows || rows.length === 0) { ElMessage.warning('请选择要删除的记录'); return }
  ElMessageBox.confirm('此操作将删除该记录, 是否继续?', '提示', { type: 'warning' }).then(() => {
    const ids = rows.map((row) => row.id)
    removeUser({ ids }).then(
      (res: any) => { ElMessage.success(res.msg); searchFn(true) },
      (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    )
  })
}

function accountFn(row: any) {
  userId = row.id
  queryUserAccount({ id: row.id }).then(
    (res: any) => {
      accountDialog.formData = { ...res.data }
      roleIds = res.data.roleIds || []
      accountDialog.visible = true
    },
    (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  )
}

function changeLockedFn(val: string) {
  changeLock({ id: accountDialog.formData.id, locked: val }).then(
    (res: any) => ElMessage.success(res.msg),
    (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  )
}

function resetPwdFn() {
  ElMessageBox.confirm('此操作将修改密码, 是否继续?', '提示', { type: 'warning' }).then(() => {
    resetPwd({ id: accountDialog.formData.id, password: accountDialog.formData.password }).then(
      (res: any) => ElMessage.success(res.msg),
      (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    )
  })
}

function changeRole(val: string[]) {
  const params: any = { id: userId }
  if (val.length > roleIds.length) {
    params.roleIds = val.filter((o) => !roleIds.includes(o))
    addRole(params).then((res: any) => ElMessage.success(res.msg))
  } else {
    params.roleIds = roleIds.filter((o) => !val.includes(o))
    delRole(params).then((res: any) => ElMessage.success(res.data?.msg || res.msg))
  }
  roleIds = val
}

function fetchRoleList() {
  queryRoleList().then(
    (res: any) => { roles.value = res.data },
    (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  )
}

fetchRoleList()
searchFn()
</script>

<style scoped lang="less"></style>
