<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="企业名称" prop="enterpriseId" v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-select v-model="queryParams.enterpriseId" filterable clearable placeholder="请输入企业名称进行查找" class="!w-240px">
          <el-option
            v-for="item in enterpriseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name" v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-input v-model="queryParams.name" clearable placeholder="请输入姓名" class="!w-240px" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone" v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-input v-model="queryParams.phone" clearable class="!w-240px" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-input v-model="queryParams.email" clearable class="!w-240px" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="最后登录IP" prop="loginIp" v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-input v-model="queryParams.loginIp" clearable class="!w-240px" placeholder="请输入最后登录IP" />
      </el-form-item>
      <el-form-item label="帐号状态" prop="status" clearable v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择帐号状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime" v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="登录时间" prop="loginDate" v-hasPermi="['menduner:system:enterprise-user-bind:query']">
        <el-date-picker
          v-model="queryParams.loginDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['menduner:system:enterprise-user-bind:query']" @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button v-hasPermi="['menduner:system:enterprise-user-bind:query']" @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['menduner:system:enterprise-user-bind:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true">
      <el-table-column label="企业名称" align="center" prop="enterpriseName" fixed="left">
        <template #default="scope">{{ formatName(scope.row.enterpriseName) }}</template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="用户头像" align="center" prop="avatar">
        <template #default="scope">
          <el-image v-if="scope.row.avatar" style="width: 60px; height: 60px" :src="scope.row.avatar" fit="contain" />
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="帐号状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MENDUNER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="用户类型" align="center" prop="userType">
        <template #default="scope">
          {{ scope.row.userType === '1' ? '管理员': '普通用户' }}
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" align="center" prop="loginIp" />
      <el-table-column label="最后登录时间" align="center" prop="loginDate" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" fixed="right" min-width="260">
        <template #default="scope">
          <el-button link type="primary" @click="openDetail(scope.row.id, scope.row.enterpriseId, scope.row.userId)">详情</el-button>
          <!-- <el-button link type="primary" @click="openEditEmail(scope.row.id)">修改登录邮箱</el-button> -->
          <el-button link type="primary" @click="openEdit(scope.row.id)">编辑</el-button>
          <el-button link type="primary" @click="openEditPassword(scope.row.id)">修改登录密码</el-button>
          <el-button v-if="scope.row.status === '0'" link type="danger" @click="handleActions(scope.row.id, 'disabled')">禁用</el-button>
          <el-button v-if="scope.row.status === '1'" link type="success" @click="handleActions(scope.row.id, 'enable')">启用</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 修改用户登录邮箱 -->
  <!-- <EditEmail ref="editEmailRef" @success="getList" /> -->

  <!-- 编辑 -->
  <Edit ref="editRef" @success="getList" />

  <!-- 修改用户登录密码 -->
  <EditPassword ref="editPasswordRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { formatName } from '@/utils'
import { EnterpriseUserBindApi, EnterpriseUserBindVO } from '@/api/menduner/system/enterprise/userBind'
// import EditEmail from './EditEmail.vue'
import Edit from './Edit.vue'
import EditPassword from './EditPassword.vue'

/** 门墩儿-企业登录用户 列表 */
defineOptions({ name: 'EnterpriseUserBind' })

const message = useMessage() // 消息弹窗
const enterpriseList = ref([])

const loading = ref(true) // 列表的加载中
const list = ref<EnterpriseUserBindVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: undefined,
  loginIp: undefined,
  name: undefined,
  phone: undefined,
  email: undefined,
  enterpriseId: undefined,
  createTime: '',
  loginDate: ''
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EnterpriseUserBindApi.getEnterpriseUserBindPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 企业列表
const getEnterpriseListData = async () => {
  try {
    const data = await EnterpriseUserBindApi.getEnterpriseList()
    enterpriseList.value = data
  } catch (err) {}
}
getEnterpriseListData()

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 打开企业详情 */
const { push } = useRouter()
const openDetail = (id: string, enterpriseId: string, userId: string) => {
  push({ name: 'EnterpriseUserDetail', query: { id, enterpriseId, userId } })
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/* 修改用户邮箱 */
// const editEmailRef = ref()
// const openEditEmail = (id: number) => {
//   editEmailRef.value.open(id)
// }

/* 编辑 */
const editRef = ref()
const openEdit = (id: number) => {
  editRef.value.open(id)
}

/* 修改用户登录密码 */
const editPasswordRef = ref()
const openEditPassword = (id: number) => {
  editPasswordRef.value.open(id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EnterpriseUserBindApi.exportEnterpriseUserBind(queryParams)
    download.excel(data, '门墩儿-企业登录用户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 禁用、启用账户
const handleActions = async (id: number, type: string) => {
  try {
    await message.confirm(type === 'disabled' ? '确定要禁用该账户吗？' : '确定要启用该账户吗？')
    type === 'disabled' ? await EnterpriseUserBindApi.disabledEnterpriseAccount(id) : await EnterpriseUserBindApi.enableEnterpriseAccount([id])
    message.success('操作成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>