<template>
  <div class="table-box">
    <ProTable ref="proTable" :config="config" :api="getleaderGroupPage" :paramCallback="paramCallback">
      <template #left_buttons>
        <el-button
          v-permission="'risk_member_add'"
          type="primary"
          :icon="Plus"
          @click="accountFormModalRef?.openModal()"
          >新增</el-button
        >
        <el-button v-permission="'risk_member_del'" 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 { getleaderGroupPage, saveLeaderGroup, batchDeleteByIds } from '@/api/user';
  import { useDict } from '@/hooks/useDict';
  import { onMounted } from 'vue';
  import { getTenantPage } from '@/api/tenant';
  import { getRolePage } from '@/api/role';
  const { Status } = useDict("Status");

  const proTable = ref();
  const accountFormModalRef = ref();
  const Rolelist = ref([]);
  const Tenantlist = ref([]);
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    obj['staffRole'] = 'risk_control_commissioner'
    return obj;
  };
  const config = reactive({
    columns: [
      { type: 'checkbox', width: 60, fixed: 'left' },
      { field: 'leader.username', width: 110, title: '领导用户名称', search: { el: 'input', labelWidth: 85 } },
      { field: 'staff.username', width: 110, title: '员工用户名称', search: { el: 'input', labelWidth: 85 } },
      {
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>{Array.from(new Set(row.staff.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.staff.roleNames)).join(',')}</>
            );
          },
        },
        field: 'role',
        enum: Rolelist,
        search: { el: 'select', props: { filterable: true }, key: 'roleCode', labelWidth: 85 },
        fieldNames: { label: 'roleName', value: 'roleCode' },
        title: '员工角色'
      },
      {
        field: 'staff.phone',
        title: '员工手机号',
        width: 160,
        search: { el: 'input', props: { clearable: true }, labelWidth: 85 },
      },
      {
        field: 'staff.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: 'staff.createTime',
        title: '员工创建时间',
        width: 170,
      },
      {
        field: 'staff.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 batchDeleteByIds(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 saveLeaderGroup({
      ...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>
