<template>
  <div class="table-box">
    <ProTable ref="proTable" :config="config" :api="getUserPage">
      <template #left_buttons>
        <el-button
          v-permission="'AccountAdd'"
          type="primary"
          :icon="Plus"
          @click="accountFormModalRef?.openModal()"
          >新增</el-button
        >
        <el-button v-permission="'AccountDelete'" type="danger" :icon="Delete" @click="handleDelete"
          >删除</el-button
        >
      </template>
    </ProTable>

    <AccountFormModal ref="accountFormModalRef" @success="query" />
  </div>
</template>

<script setup lang="jsx" name="accountManage">
  import ProTable from '@/components/ProTable/index.vue';
  import AccountFormModal from './components/AccountFormModal.vue';
  import { Delete, Edit, Plus } from '@element-plus/icons-vue';
  import { reactive, ref } from 'vue';
  import { ElButton, ElMessageBox, ElMessage, ElTag } from 'element-plus';
  import { getUserPage, setStatus, deleteUsers, restPassword } from '@/api/user';
  import { useDict } from '@/hooks/useDict';
  import { onMounted } from 'vue';
  import { getTenantPage } from '@/api/tenant';
import { getdepartmentTree } from '@/api/departmentManage';
  import { getRolePage } from '@/api/role';
  const { Status } = useDict("Status");

  const proTable = ref();
  const accountFormModalRef = ref();
  const Rolelist = ref([]);
  const departlist = ref([]);
  const Tenantlist = ref([]);
  const config = reactive({
    columns: [
      { type: 'checkbox', width: 60, fixed: 'left' },
      { field: 'username', width: 110, title: '用户名称', search: { el: 'input', labelWidth: 85 } },
      {
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>{row?.tenant?.name}</>
            );
          },
        },
        field: 'tenantNames',
        enum: Tenantlist,
        width: 120, 
        search: { el: 'select', props: { filterable: true }, key: 'tenant', labelWidth: 85 },
        fieldNames: { label: 'name', value: 'id' },
        title: '调解中心'
      },
      {
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>{Array.from(new Set(row.roleNames)).join(',')}</>
            );
          },
        },
        width: 120, 
        field: 'role',
        enum: Rolelist,
        search: { el: 'select', props: { filterable: true }, key: 'roleCode', labelWidth: 85 },
        fieldNames: { label: 'roleName', value: 'roleCode' },
        title: '角色'
      },
      
      {
        field: 'departmentName',
        title: '部门',
        width: 160,
        enum: departlist,
        fieldNames: { label: 'name', value: 'id' },
        search: { el: 'tree-select', props: { filterable: true, checkStrictly: true}, labelWidth: 85, key: 'departmentId' },
      },
      {
        field: 'phone',
        title: '手机号',
        width: 160,
        search: { el: 'input', props: { clearable: true }, labelWidth: 85 },
      },
      {
        field: 'status',
        title: '状态',
        width: 100,
        enum: Status,
        search: { el: 'select', props: { clearable: true }, labelWidth: 85 },
        slots: {
          default: ({ row }) => {
            return (
              <ElTag type={row.status == 'enable' ? 'primary' : 'danger'}>
                {row.status == 'enable' ? '启用' : '禁用'}
              </ElTag>
            );
          },
        },
      },
      {
        field: 'createTime',
        title: '创建时间',
        width: 170,
      },
      {
        field: 'updateTime',
        title: '更新时间',
        width: 170,
      },
      {
        field: 'action',
        title: '操作',
        width: 260,
        fixed: 'right',
        slots: {
          default: ({ row }) => {
            return (
              <>
                <ElButton link type="primary" icon={Edit} onClick={() => editAccount(row)}>
                  编辑
                </ElButton>
                <ElButton link type="primary" icon={Edit} onClick={() => handleDisable(row)}>
                  {row.status == 'enable' ? '禁用' : '启用'}
                </ElButton>
                <ElButton link type="primary" onClick={() => handleRefresh(row)}>
                  重置密码
                </ElButton>
              </>
            );
          },
        },
      },
    ],
  });
  const handleRefresh = async (row) => {
    await ElMessageBox.confirm(
      `是否确认重置该用户的密码？`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 修改的状态
    await restPassword({
      id: row.id
    });
    ElMessage({
      type: 'success',
      message: `重置成功！`,
      plain: true,
    });
  }
  const handleDelete = async () => {
    const list = proTable.value.element.getCheckboxRecords();
    if (list.length) {
      await ElMessageBox.confirm('是否确认删除选中账户?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });

      const ids = list.map((v) => v.id).join(',');
      await deleteUsers(ids);

      ElMessage({
        type: 'success',
        message: '删除成功！',
        plain: true,
      });
      query();
    }
  };
  const editAccount = (row) => accountFormModalRef.value.openModal(JSON.parse(JSON.stringify(row)));
  const handleDisable = async (row) => {
    await ElMessageBox.confirm(
      `是否确认${row.status == 'enable' ? '禁用' : '启用'}该用户？`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 修改的状态
    const status = row.status === 'enable' ? 'disable' : 'enable';
    await setStatus({
      id: row.id,
      status,
    });

    row.status = status;
    ElMessage({
      type: 'success',
      message: `${status == 'enable' ? '启用' : '禁用'}成功！`,
      plain: true,
    });
  };

  const query = () => proTable.value?.search();

  onMounted(() => {
    query();
    getRolePage({ current: 1, size: 9999999 }).then(res => {
      if (res.success) {
        Rolelist.value = res.result.content
      }
    })
    getTenantPage({ current: 1, size: 9999999, status: 'enable' }).then(res => {
      if (res.success) {
        Tenantlist.value = res.result.content
        console.log('Tenantlist.value', Tenantlist.value)
      }
    })
    getdepartmentTree().then(res => {
      if (res.success) {
        departlist.value = res.result
      }
    })
  });
</script>
<style lang="scss" scoped></style>
