<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, saveUser, deleteUsers } from '@/api/user';
  import { onMounted } from 'vue';
  import { getTenantPage } from '@/api/tenant';
  import { getRolePage } from '@/api/role';

  const proTable = ref();
  const accountFormModalRef = ref();
  const Rolelist = 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 (
              <>{Array.from(new Set(row.tenantNames)).join(',')}</>
            );
          },
        },
        field: 'tenantNames',
        enum: Tenantlist,
        search: { el: 'select', props: { filterable: true }, key: 'tenantId', labelWidth: 85 },
        fieldNames: { label: 'name', value: 'id' },
        title: '调解中心'
      },
      {
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>{Array.from(new Set(row.roleNames)).join(',')}</>
            );
          },
        },
        field: 'role',
        enum: Rolelist,
        search: { el: 'select', props: { filterable: true }, key: 'roleCode', labelWidth: 85 },
        fieldNames: { label: 'roleName', value: 'roleCode' },
        title: '角色'
      },
      {
        field: 'phone',
        title: '手机号',
        width: 160,
        search: { el: 'input', props: { clearable: true }, labelWidth: 85 },
      },
      {
        field: 'status',
        title: '状态',
        width: 100,
        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: 200,
        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>
              </>
            );
          },
        },
      },
    ],
  });

  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 saveUser({
      ...row,
      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)
      }
    })
  });
</script>
<style lang="scss" scoped></style>
