<template>
  <div class="table-container">
    <el-card>
      <template #header>
        <div class="header">
          <el-form :inline="true" :model="searchFormState">
            <el-form-item label="登录账号">
              <el-input
                v-model="searchFormState.LoginName"
                clearable
                class="filter-item"
                style="width: 150px"
                placeholder="请输入登录账号"
              />
            </el-form-item>
            <el-form-item label="真实姓名">
              <el-input
                v-model="searchFormState.UserName"
                clearable
                class="filter-item"
                style="width: 150px"
                placeholder="请输入真实姓名"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="searchFormState.Status"
                style="width: 100px"
                class="filter-item"
                placeholder="请选择"
              >
                <el-option
                  v-for="(key, value) in statusMap"
                  :key="key"
                  :label="key"
                  :value="value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button type="primary" @click="handleReset">重置</el-button>
              <el-button
                type="primary"
                v-permission="['UserAdd']"
                @click="handleAdd(-1, 1)"
                >新增</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </template>
      <div>
        <el-table
          :data="dataList"
          border
          style="width: 100%"
          v-loading="isLoading"
        >
          <el-table-column
            label="登录账号"
            prop="LoginName"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="真实姓名" prop="UserName"></el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <span :style="{ color: statusToColor(scope.row.Status) }">{{
                statusMap[scope.row.Status]
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="150"
            show-overflow-tooltip
            label="角色"
            prop="roles"
          ></el-table-column>
          <el-table-column
            width="120"
            label="手机号"
            prop="PhoneNo"
          ></el-table-column>
          <el-table-column label="创建时间" prop="CreateTime"></el-table-column>
          <el-table-column label="修改时间" prop="UpdateTime"></el-table-column>
          <el-table-column
            width="300"
            fixed="right"
            label="操作"
            prop="describe"
          >
            <!-- admin无法操作！！！！！ -->
            <template #default="scope">
              <el-button
                v-show="scope.row.LoginName !== 'admin'"
                v-permission="['UserEdit']"
                type="primary"
                size="mini"
                @click="handleAdd(scope.row.Id, scope.row.Status)"
              >
                编辑
              </el-button>
              <el-button
                v-show="scope.row.LoginName !== 'admin'"
                v-permission="['UserDisable']"
                :type="scope.row.Status == 1 ? 'warning' : 'success'"
                size="mini"
                @click="handleDisable(scope.row)"
              >
                {{ scope.row.Status == 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button
                v-show="scope.row.LoginName !== 'admin'"
                v-permission="['UserDelete']"
                type="danger"
                size="mini"
                @click="handleDel(scope.row)"
              >
                删除
              </el-button>
              <el-button
                v-show="scope.row.LoginName !== 'admin'"
                v-permission="['UserPassReset']"
                size="mini"
                @click="handleResetPass(scope.row)"
              >
                重设密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParam.PageNum"
          :page-size="queryParam.PageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total,sizes,pager,prev,next,jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import { onMounted, toRefs } from 'vue'
import { getUserList, disableUser, deleteUser, resetPwd } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import useLoadTableData from '@/hooks/useLoadTableData'
import { colorMapEnum, statusMapEnum } from '@/utils/enum'
export default {
  setup() {
    const statusMap = statusMapEnum
    //表格通用条件只是查询参数不一样，其他分页，loading等都一样
    const formData = {
      LoginName: '',
      RealName: '',
      Status: null
    }

    //获取接口数据
    const fetchData = async (params) => {
      console.log('params', params)
      const data = await getUserList(params)
      return data
    }

    //处理数据-拼接角色
    const handleData = (data) => {
      data.forEach((d) => {
        if (d.RoleList.length > 0) {
          d.roles = ''
          d.RoleList.forEach((item) => {
            d.roles += item.Name + '、'
          })
          d.roles = d.roles.substring(0, d.roles.lastIndexOf('、'))
        }
      })
    }

    const {
      loadData,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleReset,
      state
    } = useLoadTableData(formData, fetchData, handleData)

    onMounted(() => {
      //获取表格数据
      loadData(fetchData, handleData)
    })

    const router = useRouter()
    //新增
    const handleAdd = (Id) => {
      const argu = { Id }
      router.push({
        name: 'user_edit',
        params: argu
      })
    }
    //启禁用
    const handleDisable = async (rowData) => {
      let handledStatus = 0
      if (rowData.Status === 0) {
        handledStatus = 1
      }
      if (rowData.Status === 1) {
        handledStatus = 0
      }
      await disableUser({ Id: rowData.Id, Status: handledStatus })
      loadData(fetchData, handleData)
      ElMessage.success('操作成功')
    }

    //删除
    const handleDel = async (rowData) => {
      ElMessageBox.confirm(`是否删除用户${rowData.UserName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //点击确定的操作(调用接口)
        await deleteUser({ Id: rowData.Id })
        loadData(fetchData, handleData)
        ElMessage.success('操作成功')
      })
    }

    //重置密码
    const handleResetPass = async (rowData) => {
      await resetPwd({ Id: rowData.Id })
      loadData(fetchData, handleData)
      ElMessage.success('操作成功')
    }

    //根据状态显示颜色
    //根据状态显示颜色
    const statusToColor = (status) => {
      /*
      0: '禁止'
      0: '正常'
      */
      let color = '#333'
      switch (status) {
        case 0:
          color = colorMapEnum.red
          break
        case 1:
          color = colorMapEnum.blue
          break
      }
      return color
    }

    //通用hook处理-重置，搜索，页面切换，数据获取
    return {
      handleAdd,
      statusMap,
      ...toRefs(state),
      handleReset,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleResetPass,
      handleDel,
      handleDisable,
      statusToColor
    }
  }
}
</script>

<style lang="scss" scoped>
.table-container {
  .pagination {
    margin-top: 20px;
    text-align: center;
  }
  :deep(.el-form-item) {
    margin-bottom: 10px;
  }
}
</style>
