<template>
  <BasicDrawer title="部门角色分配" :width="365" @close="onClose" @register="registerDrawer">
    <Spin :spinning="loading">
      <template v-if="desformList.length > 0">
        <CheckboxGroup v-model:value="designNameValue">
          <Row>
            <Col :span="24" v-for="item of desformList">
              <Checkbox :value="item.id">{{ item.roleName }}</Checkbox>
            </Col>
          </Row>
        </CheckboxGroup>
        <div style="width: 100%; margin-top: 15px">
          <c-button type="primary" :loading="loading" :size="'small'" preIcon="ant-design:save-filled" @click="onSubmit">
            <span>点击保存</span>
          </c-button>
        </div>
      </template>
      <a-empty v-else description="无配置信息" />
    </Spin>
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner, Button as CButton } from '@jdlinker/ui';
  import { queryDepartRoleByUserId, queryDepartRoleUserList, saveDepartRoleUser } from '../depart.user.api';
  import { Spin, CheckboxGroup, Row, Col, Checkbox } from 'ant-design-vue';

  defineEmits(['register']);
  const loading = ref<boolean>(false);
  const userId = ref('');
  const departId = ref('');
  const oldRoleId = ref('');
  const desformList = ref<Array<any>>([]);
  const designNameValue = ref<Array<any>>([]);

  // 注册抽屉组件
  const [registerDrawer, { closeDrawer }] = useDrawerInner((data) => {
    userId.value = unref(data.userId);
    departId.value = unref(data.departId);
    loadData();
  });

  async function loadData() {
    try {
      loading.value = true;
      const params = {
        departId: departId.value,
        userId: userId.value
      };
      // 查询 DepartRole
      const [$desformList, $departRoleList] = await Promise.all([
        queryDepartRoleUserList(params),
        queryDepartRoleByUserId(params)
      ]);
      desformList.value = $desformList;
      designNameValue.value = $departRoleList.map((item) => item.droleId);
      oldRoleId.value = designNameValue.value.join(',');
    } finally {
      loading.value = false;
    }
  }

  async function onSubmit() {
    try {
      loading.value = true;
      await saveDepartRoleUser({
        userId: userId.value,
        newRoleId: designNameValue.value.join(','),
        oldRoleId: oldRoleId.value
      });
      doClose();
    } finally {
      loading.value = false;
    }
  }

  function onClose() {
    doReset();
  }

  function doClose() {
    doReset();
    closeDrawer();
  }

  function doReset() {
    userId.value = '';
    departId.value = '';
    oldRoleId.value = '';
    desformList.value = [];
    designNameValue.value = [];
  }
</script>
