<template>
    <div>
        <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"
                        />
                        <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
                        v-if="memberTableData.length"
                        :data="memberTableData"
                        class="w-full mb-[20px]"
                        fix-header
                        header-bg
                        max-height="500px"
                    >
                        <d-column field="userName" header="成员名" />
                        <d-column field="role" header="角色">
                            <template #default="{ row }">
                                {{ memberRoleMap[row.role] ?? '' }}
                            </template>
                        </d-column>
                        <d-column field="email" header="邮箱" />
                        <d-column field="joinDate" header="加入时间" />
                        <d-column header="操作">
                            <template #default="{row}">
                                <d-button
                                    variant="text"
                                    color="primary"
                                    @click="openDeleteModal(row)"
                                >删除</d-button>
                            </template>
                        </d-column>
                    </d-table>
                    <NoData v-else />
                <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"
                />
            </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"
                />
            </d-form-item>
        </d-form>

        <div class="flex justify-center">
            <d-button
                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]"
                @click="inviteMemberConfirmBtnClick"
            >确定</d-button>
            <d-button @click="closeInviteMemberModal">取消</d-button>
        </div>
    </d-modal>


    <d-modal
      v-model="deleteMemberModalCtrl"
      title="删除成员"
      class="w-[600px]"
    >
        <div>
            即将删除成员‘{{ deleteRow.userName }}’，请确认是否继续？
        </div>
        <div class="flex justify-center">
            <d-button
                variant="solid"
                class="mr-[8px]"
                @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 NoData from "@/components/NoData/NoData.vue";
import {
  createOrganizationApi, deleteOrganizationMemberApi,
  getOrganizationInfoApi, getOrganizationMemberListApi, inviteOrganizationMemberApi,
  updateOrganizationInfoApi
} from "@/api/organizationManage/organizationManageApi";
import {
    type OrganizationInfoType,
    type OrganizationMemberItemType,
} from "@/api/organizationManage/organizationManageType";
import table from "@/components/AIRepair/Table.vue";

const searchOrganizationLoading = ref(false);
const hasOrganization = ref(false);
const organizationInfo = shallowRef<OrganizationInfoType>({
    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('');
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: 'creator' },
    { name: '成员', value: 'member' },
];
const memberRoleMap = {
    creator: '创建者',
    member: '成员',
};

const mockTableData = [
    { userName: '张三', role: 'member', email: '111@gmail.com', joinDate: '2090-02-30', id: '1' },
    { userName: '李四', role: 'creator', email: '111@gmail.com', joinDate: '2090-02-30', id: '2' },
    { userName: '王五', role: 'member', email: '111@gmail.com', joinDate: '2090-02-30', id: '3' },
    { userName: '赵六', role: 'member', email: '111@gmail.com', joinDate: '2090-02-30', id: '4' },
    { userName: '秦七', role: 'member', email: '111@gmail.com', joinDate: '2090-02-30', id: '5' },
];

// -------------------- 获取组织信息 --------------------
async function getOrganizationInfo() {
    const params = {
        organizationName: createFormData.organizationName,
        organizationProfile: createFormData.organizationProfile,
    };
    searchOrganizationLoading.value = true;
    try {
       const res = await getOrganizationInfoApi(params);
    } catch (e) {

    }
    searchOrganizationLoading.value = false;
    getMemberList();
    // TODO 待接口定义好后删除下面两行固定赋值语句
    hasOrganization.value = true;
    organizationInfo.value = { organizationName: createFormData.organizationName, organizationProfile: createFormData.organizationProfile };
}

// -------------------- 获取成员信息 --------------------
async function getOrganizationMember(organizationId: string) {
    const params = {};
}

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

async function createOrganization() {
    const params = {
        organizationName: createFormData.organizationName,
        organizationProfile: createFormData.organizationProfile,
    };
    createOrganizationLoading.value = true;
    try {
        const res = await createOrganizationApi(params);
    } catch (e) {

    }
    closeOrganizationModal();
    // TODO 待接口定义好后删除下面调用逻辑
    getOrganizationInfo();
    createOrganizationLoading.value = false;
}

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

function closeOrganizationModal() {
    createOrganizationModalCtrl.value = false;
}

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

async function editOrganizationConfirm() {
    editLoading.value = true;
    const params = {
        organizationName: createFormData.organizationName,
        organizationProfile: createFormData.organizationProfile,
    };
    try {
        const res = await updateOrganizationInfoApi(params);
    } catch (e) {

    }
    editLoading.value = false;
    isEdit.value = false;
    // TODO 待接口定义好后删除下面两行固定赋值语句
    hasOrganization.value = true;
    organizationInfo.value = { organizationName: createFormData.organizationName, organizationProfile: createFormData.organizationProfile };
}

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

// -------------------- 邀请、查询成员 --------------------
async function getMemberList() {
    const params = {
        organizationName: createFormData.organizationName,
        pageIndex: pager.pageIndex,
        pageSize: pager.pageSize,
        searchParam: memberListSearchParam.value,
    };
    memberListSearchLoading.value = true;
    try {
        const res = await getOrganizationMemberListApi(params);
    } catch (e) {

    }
    memberTableData.value = mockTableData;
    pager.total = 6;
    memberListSearchLoading.value = false;
}

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

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

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

async function inviteMember() {
    const params = {
        userName: inviteMemberFormData.userName,
        role: inviteMemberFormData.role,
    };
    inviteMemberLoading.value = true;
    try {
        const res = await inviteOrganizationMemberApi(params);
    } catch (e) {

    }
    inviteMemberLoading.value = false;
    closeInviteMemberModal();
    // TODO 待接口定义好后删除下面调用逻辑
    mockTableData.unshift({
        userName: inviteMemberFormData.userName,
        role: inviteMemberFormData.role,
        joinDate: new Date().toDateString(),
        id: String(pager.total++),
        email: `${inviteMemberFormData.userName}@gmail.com`,
    });
    memberTableData.value = [...mockTableData];
}

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

async function deleteMember() {
    const params = {
        id: deleteRow.value.id,
    };
    deleteMemberLoading.value = true;
    try {
        const res = await deleteOrganizationMemberApi(params);
    } catch (e) {

    }
    deleteMemberLoading.value = false;
    closeDeleteMemberModal();
    // TODO 待接口定义好后删除下面调用逻辑
    const index = mockTableData.findIndex(item => item.id === deleteRow.value.id);
    mockTableData.splice(index, 1);
    memberTableData.value = [...mockTableData];
    pager.total--;
}

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

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