<template>
  <div v-loading="searchOrganizationLoading" class="mt-3">
    <div v-if="hasOrganization">
      <d-card class="mb-[16px] bg-white" shadow="never">
        <div class="text-[14px] w-full flex items-center justify-between">
          <div class="font-bold mb-[16px]">基础信息</div>
          <div>
            <d-icon v-if="!isEdit" class="font-normal" name="edit" operable @click="editIconClick">
              <template #suffix>
                <span>编辑</span>
              </template>
            </d-icon>
          </div>
        </div>
        <d-form ref="baseInfoFormRef" :data="createFormData" message-type="none">
          <d-form-item field="organizationName" label="组织名称">
            <d-input v-if="isEdit" v-model="createFormData.organizationName" />
            <div v-else>{{ organizationInfo.organizationName }}</div>
          </d-form-item>
          <d-form-item field="organizationProfile" label="组织简介">
            <d-textarea v-if="isEdit" v-model="createFormData.organizationProfile" show-count maxlength="200" :rows="5"  />
            <div v-else>{{ organizationInfo.organizationProfile }}</div>
          </d-form-item>
        </d-form>
        <div v-if="isEdit">
          <d-button variant="solid" class="mr-[8px]" @click="editOrganizationConfirm">完成</d-button>
          <d-button @click="editOrganizationCancel">取消</d-button>
        </div>
      </d-card>

      <d-card class="mb-[16px] bg-white" shadow="never">
        <div class="font-bold text-[14px] mb-[12px]">成员管理</div>
        <div class="flex mb-[12px]">
          <d-button icon="add" variant="solid" class="mr-[8px]" @click="openInviteMemberModal">邀请成员</d-button>
          <d-search icon-position="left" class="w-[296px]" placeholder="请输入搜索内容" />
        </div>
        <d-table
          :data="memberTableData"
          :show-loading="memberListSearchLoading"
          class="w-full mb-[20px] organ-table"
          :fix-header="memberTableData.length > 0"
          header-bg
          max-height="500px"
        >
          <d-column field="username" header="成员名" />
          <d-column field="roleCode" header="角色">
            <template #default="{ row }">
              {{ memberRoleMap[row.roleCode] ?? '' }}
            </template>
          </d-column>
          <d-column field="email" header="邮箱" />
          <d-column field="createTime" header="加入时间" />
          <d-column header="操作">
            <template #default="{ row }">
              <d-button size="sm" variant="text" color="primary" class="p-0 justify-start" @click="openDeleteModal(row)">删除</d-button>
            </template>
          </d-column>
          <template #empty>
            <NoData />
          </template>
        </d-table>
        <d-pagination
          class="flex justify-end"
          :total="pager.total"
          v-model:pageSize="pager.pageSize"
          v-model:pageIndex="pager.pageIndex"
          :can-view-total="true"
          :can-change-page-size="true"
          :max-items="5"
          @page-index-change="pagerIndexChange"
          @page-size-change="pagerSizeChange"
        />
      </d-card>
    </div>

    <div v-else>
      <NoData :small="false">
        <div class="font-bold mb-[20px]">很抱歉，当前无任何组织，赶快去</div>
        <d-button size="lg" variant="solid" @click="openCreateOrganizationModal">新建组织</d-button>
      </NoData>
    </div>
  </div>

  <d-modal v-model="createOrganizationModalCtrl" title="新建组织" class="w-[600px]">
    <d-form ref="createFormRef" layout="vertical" :data="createFormData" message-type="none">
      <d-form-item field="organizationName" label="组织名称" required>
        <d-input v-model="createFormData.organizationName" />
      </d-form-item>
      <d-form-item field="organizationProfile" label="组织简介" required>
        <d-textarea v-model="createFormData.organizationProfile" show-count maxlength="200" :rows="6" />
      </d-form-item>
    </d-form>

    <div class="flex justify-center">
      <d-button :loading="createOrganizationLoading" variant="solid" class="mr-[8px]" @click="confirmCreateOrganizationBtnClick">确定</d-button>
      <d-button @click="closeOrganizationModal">取消</d-button>
    </div>
  </d-modal>

  <d-modal v-model="inviteMemberModalCtrl" title="邀请成员" class="w-[600px]">
    <d-form ref="inviteMemberFormRef" layout="vertical" :data="inviteMemberFormData" message-type="none">
      <d-form-item field="userName" label="成员" required>
        <d-input v-model="inviteMemberFormData.userName" placeholder="请输入" />
      </d-form-item>
      <d-form-item field="role" label="角色" required>
        <d-select v-model="inviteMemberFormData.role">
          <d-option v-for="item of inviteMemberSelectOptions" :key="item.value" :value="item.value" :name="item.name" />
        </d-select>
      </d-form-item>
    </d-form>

    <div class="flex justify-center">
      <d-button variant="solid" class="mr-[8px]" :loading="inviteMemberLoading" @click="inviteMemberConfirmBtnClick">确定</d-button>
      <d-button @click="closeInviteMemberModal">取消</d-button>
    </div>
  </d-modal>

  <d-modal v-model="deleteMemberModalCtrl" title="删除成员" class="w-[600px]">
    <div class="mb-[20px]">即将删除成员‘{{ deleteRow.username }}’，请确认是否继续？</div>
    <div class="flex justify-center">
      <d-button variant="solid" class="mr-[8px]" :loading="deleteMemberLoading" @click="deleteMember">确定</d-button>
      <d-button @click="closeDeleteMemberModal">取消</d-button>
    </div>
  </d-modal>
</template>

<script setup lang="ts">
import { reactive, ref, shallowRef } from 'vue';
import { Message } from 'vue-devui';
import NoData from '@/components/NoData/NoData.vue';
import {
  createOrganizationApi,
  deleteOrganizationMemberApi,
  getOrganizationMemberListApi,
  inviteOrganizationMemberApi,
  updateOrganizationInfoApi
} from '@/api/organizationManage/organizationManageApi';
import {
  type OrganizationInfoType,
  type OrganizationMemberItemType,
  OrganizationMemberRoleEnum,
  type UserInfoType,
} from '@/api/organizationManage/organizationManageType';
import {getUserInfo} from "@/api/user";

const userInfo = shallowRef<UserInfoType>({
  username: '',
  mobile: null,
  email: '',
  avatar: '',
  noticeUnreadNum: 0,
  inviteNum: 0,
  groupId: null,
  groupName: null,
  groupDesc: null,
});
const searchOrganizationLoading = ref(false);
const hasOrganization = ref(false);
const organizationInfo = shallowRef<OrganizationInfoType>({
  groupId: 0,
  organizationName: '',
  organizationProfile: ''
});

const createOrganizationModalCtrl = ref(false);
const createFormData = reactive({
  organizationName: '',
  organizationProfile: '' // 组织简介
});
const createFormRef = ref();
const createOrganizationLoading = ref(false);

const isEdit = ref(false);
const editLoading = ref(false);

const memberListSearchLoading = ref(false);
const memberListSearchParam = ref('');
let originMemberList: OrganizationMemberItemType[] = [];
let filterMemberList: OrganizationMemberItemType[] = [];
const memberTableData = shallowRef<OrganizationMemberItemType[]>([]);
const pager = reactive({
  pageSize: 10,
  pageIndex: 1,
  total: 0
});

const deleteRow = shallowRef<OrganizationMemberItemType>(null);
const deleteMemberModalCtrl = ref(false);
const deleteMemberLoading = ref(false);

const inviteMemberFormRef = ref();
const inviteMemberModalCtrl = ref(false);
const inviteMemberLoading = ref(false);
const inviteMemberFormData = reactive({
  userName: '',
  role: ''
});
const inviteMemberSelectOptions = [
  { name: '创建者', value: OrganizationMemberRoleEnum.OWNER },
  { name: '成员', value: OrganizationMemberRoleEnum.MEMBER }
];
const memberRoleMap = {
  [OrganizationMemberRoleEnum.OWNER]: '创建者',
  [OrganizationMemberRoleEnum.MEMBER]: '成员'
};

init();
function init() {
  queryUserInfo();
}

// -------------------- 获取组织信息 --------------------
async function queryUserInfo() {
  searchOrganizationLoading.value = true;
  try {
    const res = await getUserInfo();
    if (res.data?.data?.code === 200) {
      userInfo.value = res.data?.data.data;
    }
    if (userInfo.value.groupId) {
      hasOrganization.value = true;
      organizationInfo.value = {
        groupId: userInfo.value.groupId,
        organizationName: userInfo.value.groupName as string,
        organizationProfile: userInfo.value.groupDesc as string,
      };
      getMemberList();
    }
  } catch (e) {
    Message.error('查询用户信息失败');
  }
  searchOrganizationLoading.value = false;
}

// -------------------- 创建组织 --------------------
function confirmCreateOrganizationBtnClick() {
  createFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      createOrganization();
    }
  });
}

async function createOrganization() {
  const params = {
    groupName: createFormData.organizationName,
    groupDesc: createFormData.organizationProfile
  };
  createOrganizationLoading.value = true;
  try {
    const res = await createOrganizationApi(params);
    if (res.data?.code !== 200) {
      Message.error(res.data?.msg || '创建失败');
    } else {
      closeOrganizationModal();
      queryUserInfo();
    }
  } catch (e) {
    Message.error('接口错误，创建失败');
  }
  createOrganizationLoading.value = false;
}

function openCreateOrganizationModal() {
  createOrganizationModalCtrl.value = true;
}

function closeOrganizationModal() {
  createFormData.organizationName = '';
  createFormData.organizationProfile = '';
  createOrganizationModalCtrl.value = false;
}

// -------------------- 编辑组织信息 --------------------
function editIconClick() {
  createFormData.organizationName = organizationInfo.value.organizationName;
  createFormData.organizationProfile = organizationInfo.value.organizationProfile;
  isEdit.value = true;
}

async function editOrganizationConfirm() {
  if (!createFormData.organizationName || !createFormData.organizationProfile) {
    Message.warning('组织名称和组织简介不能为空');
    return;
  }
  editLoading.value = true;
  const params = {
    id: organizationInfo.value.groupId,
    name: createFormData.organizationName,
    desc: createFormData.organizationProfile
  };
  try {
    const res = await updateOrganizationInfoApi(params);
    if (res.data?.code === 200) {
      organizationInfo.value = {
        groupId: organizationInfo.value.groupId,
        ...createFormData,
      };
      createFormData.organizationName = '';
      createFormData.organizationProfile = '';
    } else {
      Message.error(res.data?.msg || '更新失败');
    }
  } catch (e) {
    Message.error('接口错误，更新失败');
  }
  editLoading.value = false;
  isEdit.value = false;
}

function editOrganizationCancel() {
  isEdit.value = false;
  createFormData.organizationName = organizationInfo.value.organizationName;
  createFormData.organizationProfile = organizationInfo.value.organizationProfile;
}

// -------------------- 邀请、查询成员 --------------------
async function getMemberList() {
  memberListSearchLoading.value = true;
  originMemberList = [];
  pager.total = 0;
  try {
    const res = await getOrganizationMemberListApi({ groupId: organizationInfo.value.groupId });
    if (res.data?.code === 200) {
      originMemberList = res.data?.data;
      pager.total = originMemberList.length;
      updateFilterTableList();
    } else {
      Message.warning(res.data?.msg || '查询失败');
    }
  } catch (e) {
    Message.error('接口错误，查询失败');
  }
  memberListSearchLoading.value = false;
}

function updateFilterTableList() {
  const queryStr = memberListSearchParam.value;
  filterMemberList = queryStr ? originMemberList.filter(item => item.username.includes(queryStr)) : originMemberList;
  updateCurrentPageTableList();
}

function updateCurrentPageTableList() {
  const endIndex = pager.pageIndex * pager.pageSize;
  memberTableData.value = filterMemberList.slice(endIndex - pager.pageSize, endIndex);
}

function pagerIndexChange() {
  updateCurrentPageTableList();
}

function pagerSizeChange() {
  pager.pageIndex = 1;
  updateCurrentPageTableList();
}

function openInviteMemberModal() {
  inviteMemberModalCtrl.value = true;
}

function openDeleteModal(row: any) {
  deleteRow.value = row;
  deleteMemberModalCtrl.value = true;
}

function inviteMemberConfirmBtnClick() {
  inviteMemberFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      inviteMember();
    }
  });
}

async function inviteMember() {
  const params = {
    groupId: organizationInfo.value.groupId,
    username: inviteMemberFormData.userName,
    roleCode: inviteMemberFormData.role
  };
  inviteMemberLoading.value = true;
  try {
    const res = await inviteOrganizationMemberApi(params);
    if (res.data?.data) {
      Message.success('邀请成功');
      getMemberList();
    } else {
      Message.warning(res.data?.msg || '邀请失败');
    }
  } catch (e) {
    Message.warning('接口错误，邀请失败');
  }
  inviteMemberLoading.value = false;
  closeInviteMemberModal();
}

function closeInviteMemberModal() {
  inviteMemberModalCtrl.value = false;
}

async function deleteMember() {
  const params = {
    groupId: organizationInfo.value.groupId,
    username: deleteRow.value.username
  };
  deleteMemberLoading.value = true;
  try {
    const res = await deleteOrganizationMemberApi(params);
    if (res.data?.data) {
      Message.success('删除成功');
      getMemberList();
    } else {
      Message.error(res.data?.msg || '删除失败');
    }
  } catch (e) {
    Message.warning('接口错误，删除失败');
  }
  deleteMemberLoading.value = false;
  closeDeleteMemberModal();
}

function closeDeleteMemberModal() {
  deleteMemberModalCtrl.value = false;
}
</script>

<style scoped lang="scss">
.organ-table :deep(.devui-table__row td) {
  padding: 10px 16px;
}
</style>
