<template>
  <div class="user-group">
    <Search />
    <div class="user-list">
      <BasicTable
        :columns="userGroupCol"
        :data-source="userListData"
        :row-key="(row) => row.id"
        :action-column="actionColumn"
        :pagination="{
          total: total,
          pageSize: pagesize,
          currentPage: page,
          hideOnSinglePage: !userListData,
        }"
        :tableSetting="{
          size: false,
          redo: false,
          fullscreen: false,
          striped: false,
          setting: false,
        }"
        :striped="true"
        ref="tableRef"
        @page-num-change="handlePageNumChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #tableTitle>
          <el-button type="primary" @click="handleCreateGroup"  v-permission="{ action: [PERM_NOTICE.PERSONNEL_ADD] }">
            <img src="./img/create.png" style="margin-right: 8px" />新建人员分组
          </el-button>
        </template>
        <template #empty>
          <div class="empty-content flex flex-col items-center">
            <span class="empty-text">暂无数据</span>
          </div>
        </template>
      </BasicTable>
      <el-dialog
        v-model="errorVisible"
        title="无法删除"
        width="420"
        class="errorDialog"
        align-center
        :show-close="false"
        :close-on-click-modal="false"
      >
        <div class="title">该分组在“推送对象”中已被引用，如需删除，请先解除引用关系。</div>
        <div class="list">
          <div
            v-for="(item, index) in visibleRefGroup"
            :key="index"
            style="display: flex; align-items: center"
          >
            <span class="dot"></span>{{ getLabel(item.messageType) }}
          </div>
        </div>
        <div v-if="refGroup && refGroup.length > 3" @click="showAll = !showAll" class="more-button">
          {{ showAll ? '收起' : '更多' }}
        </div>
        <el-button type="primary" @click="errorVisible = false"> 已知晓 </el-button>
      </el-dialog>
      <el-drawer
        v-model="drawer"
        :title="drawerTitle"
        size="450"
        :close-on-click-modal="false"
        :destroy-on-close="true"
      >
        <GroupBoard @close="drawer = false" :drawer-title="drawerTitle" :form-data="formData!" />
      </el-drawer>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import Search from './components/Search.vue';
  import GroupBoard from './components/GroupBoard.vue';
  import { h, ref, reactive, onMounted, computed } from 'vue';
  import { BasicTable, TableActionIcons, BasicColumn } from '@/components/Table';
  import { userGroupCol } from './overviewColumns';
  import userGroupList from './store/index';
  import { storeToRefs } from 'pinia';
  const userGroup = userGroupList();
  const { userListData, total, page, pagesize } = storeToRefs(userGroup);
  const { getUserGroup } = userGroup;
  import { verifyUserGroup, deleteUserGroup, getUserGroupDetail } from '@/api/message/person-group';
  import { FormData } from './type';
  import viewIcon from '@/assets/images/reportmessage/view.png';
  import editIcon from '@/assets/images/reportmessage/edit.png';
  import deleteIcon from '@/assets/images/reportmessage/delete.png';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { messageTypeName } from '@/views/message/constant';
  import { PERM_NOTICE } from '@/types/permission/constants';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  const drawer = ref(false);
  const drawerTitle = ref<string>('新建人员分组');
  const handleCreateGroup = () => {
    drawer.value = true;
    drawerTitle.value = '新建人员分组';
  };
  const getLabel = (messageType) => {
    const messageTypeLabel = messageTypeName.find((item) => item.value === messageType)?.label;
    return `${messageTypeLabel}`;
  };
  const errorVisible = ref<boolean>(false);
  const showAll = ref<boolean>(false);
  const refGroup = ref<Array<{ type: number; statisticType: number; messageType: number }>>();
 
  const actionColumn: BasicColumn = reactive({
    width: 224,
    title: '操作',
    prop: 'action',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableActionIcons as any, {
        space: 20,
        color: '#629bf9',
        iconStyle: 'img',
        size: 16,
        actionIcons: [
          {
            label: '查看',
            icon: viewIcon,
            onClick: handleView.bind(null, record.row),
          },
          {
            label: '编辑',
            icon: editIcon,
            onClick: handleEdit.bind(null, record.row),
            ifShow: userStore.checkPermission(PERM_NOTICE.PERSONNEL_ADD)

          },
          {
            label: '删除',
            icon: deleteIcon,
            onClick: handleDelete.bind(null, record.row),
            ifShow: userStore.checkPermission(PERM_NOTICE.PERSONNEL_DELETE)
          },
        ],
      });
    },
  });
  const handlePageNumChange = (pageNum) => {
    page.value = pageNum;
    getUserGroup();
  };
  const handlePageSizeChange = (size) => {
    pagesize.value = size;
    page.value = 1;
    getUserGroup();
  };
  const formData = ref<FormData>();
  const handleView = (record: Recordable) => {
    drawer.value = true;
    drawerTitle.value = '查看人员分组';
    getUserGroupDetail(record.id).then((res) => {
      formData.value = res;
    });
  };
  const handleEdit = (record: Recordable) => {
    drawer.value = true;
    drawerTitle.value = '编辑人员分组';
    getUserGroupDetail(record.id).then((res) => {
      formData.value = res;
    });
  };
  const handleDelete = (record: Recordable) => {
    ElMessageBox.confirm('删除之后，该分组将无法恢复', '请确认是否删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        verifyUserGroup(record.id).then((res) => {
          const uniqueRes = Array.from(
            new Map(res.map((item) => [item.messageType, item])).values(),
          ) as any;
          refGroup.value = uniqueRes;
          if (refGroup.value?.length! > 0) {
            errorVisible.value = true;
          } else {
            deleteUserGroup(record.id).then(() => {
              ElMessage.success('删除成功');
              getUserGroup();
            });
          }
        });
      })
      .catch(() => {});
  };
  const visibleRefGroup = computed(() => {
    return showAll.value ? refGroup.value : refGroup.value!.slice(0, 3);
  });
  onMounted(() => {
    getUserGroup();
  });

</script>

<style lang="scss" scoped>
  .user-group {
    position: relative;
    height: calc(100vh - 64px - 18px);
    background-color: rgba(255, 255, 255, 1);
    padding: 21px;
    .user-list {
      margin-top: 24px;
    }
    ::v-deep .el-pagination {
      position: absolute;
      bottom: 35px;
      right: 67px;
    }
    .errorDialog {
      .el-button {
        position: absolute;
        bottom: 5px;
        right: 24px;
      }
      .title {
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.88);
        line-height: 22px;
        margin-bottom: 8px;
      }
      .list {
        display: flex;
        flex-direction: column;
        gap: 4px;
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.88);
        line-height: 22px;
        max-height: 300px;
        overflow-y: auto;
        margin-bottom: 15px;
        .dot {
          display: inline-block;
          width: 8px;
          height: 8px;
          background-color: #ff4d4f;
          border-radius: 50%;
          margin-right: 8px;
        }
      }
      .more-button {
        font-weight: 400;
        font-size: 14px;
        color: #1890ff;
        line-height: 20px;
        text-decoration: underline;
        cursor: pointer;
      }
    }
    ::v-deep .el-drawer__header {
      margin: 0;
      border-bottom: 1px solid rgba(0, 0, 0, 0.06);
      span {
        margin-bottom: 20px;
        font-weight: 500;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.88);
        line-height: 24px;
      }
      button {
        margin-bottom: 20px;
        color: #000000;
      }
    }
  }
</style>
