<template>
  <div class="full-height full-width column" ref="memberListRef">
    <div class="row items-center">
        <div class="text-dark text-weight-bolder col">成员管理</div>
       
        <el-popover  v-if="used[0]<used[1]" :width="100" popper-style="border-radius:10px; padding: 5px;" >
            <template #reference>
                <el-button class="ppt-button text-normal" type="primary">邀请成员</el-button>
            </template>
            <el-menu class="no-border md-menu"> <!-- style="font-family: 'Microsoft JhengHei ui';" -->
                <el-menu-item @click="inviteHandler(1)">邀请成员</el-menu-item>
                <el-menu-item @click="inviteHandler(2)">批量导入成员</el-menu-item>
            </el-menu>
        </el-popover>
        <template v-else>
            <div class="text-small text-negative q-mr-md">* 当前已无可用账号</div>
            <el-button class="ppt-button text-normal" type="primary">购买席位</el-button>
        </template>
    </div>
    <div class="q-mt-lg row flex-between">
        <el-select v-model="parameters.t" placeholder="用户角色" style="width:150px" size="default" @change="changeSearch">
            <el-option :label="x.name" :value="x.id" v-for="x in userGroup" :key="x.id" />
        </el-select>
        <el-input v-model="parameters.k" placeholder="请输入用户名称/账号"  @change="changeSearch" size="default" style="width:200px">
            <template #suffix>
                <IconSearch class="cusor-pointer"></IconSearch>
            </template>
        </el-input>
    </div>
    <div class="col q-mt-md">
        <el-table class="dark-table" v-load-more="tableScrollHandler" :data="data" style="width: 100%" height="100%" v-loading="loading">
            <el-table-column width="248">
                <template #header>
                    <span style="padding-left: 42px;">企业成员 ({{ used[0] }}/{{ used[1] }})</span>
                </template>
                <template #default="scope">
                    <div class="row items-center">
                        <el-avatar shape="square" :src="scope.row.photo.includes('http://')||scope.row.photo.includes('https://')?scope.row.photo:USER_DEFAULT_HEADER" :size="32"></el-avatar>
                        <div class="col row items-center user-nickname" v-if="editorTarget!=scope.row.id||editorIndex!=0">
                            <span class="q-ml-md">
                                {{ scope.row.name }} {{ scope.row.ism?'(我自己)':'' }}
                            </span>
                            <IconPencli size="14" style="color:#000;" class="q-ml-md cusor-pointer editor-pencli" @click="setNickNameHandler(scope.row,0)"></IconPencli>
                        </div>
                        <div class="col row items-center" v-else>
                            <el-input v-model="nickNameModel" placeholder="请输入用户昵称" size="small" class="col q-ml-md" />
                            <el-button link size="small" class="q-ml-sm" type="primary" @click="setMemberNickName(scope.row,0)">确认</el-button>
                            <el-button link size="small" style="margin-left: 5px;" @click="setNickNameHandler">取消</el-button>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="" label="账号" width="200">
                <template #default="scope">
                    <div class="col row items-center user-nickname" v-if="editorTarget!=scope.row.id||editorIndex!=1">
                        <span class="q-ml-md">
                            {{ scope.row.account }}
                        </span>
                        <!-- <IconPencli size="14" style="color:#000;" class="q-ml-md cusor-pointer editor-pencli" @click="setNickNameHandler(scope.row,1)"></IconPencli> -->
                    </div>
                    <div class="col row items-center" v-else>
                        <el-input v-model="nickNameModel" placeholder="请输入账号" size="small" class="col q-ml-md" />
                        <el-button link size="small" class="q-ml-sm" type="primary" @click="setMemberNickName(scope.row,1)">确认</el-button>
                        <el-button link size="small" style="margin-left: 5px;" @click="setNickNameHandler">取消</el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="" label="邮箱" min-width="210">
                <template #default="scope">
                    <div class="col row items-center user-nickname" v-if="editorTarget!=scope.row.id||editorIndex!=2">
                        <span class="q-ml-md">
                            {{ scope.row.mail }}
                        </span>
                        <IconPencli size="14" style="color:#000;" class="q-ml-md cusor-pointer editor-pencli" @click="setNickNameHandler(scope.row,2)"></IconPencli>
                    </div>
                    <div class="col row items-center" v-else>
                        <el-input v-model="nickNameModel" placeholder="请输入邮箱" size="small" class="col q-ml-md" />
                        <el-button link size="small" class="q-ml-sm" type="primary" @click="setMemberNickName(scope.row,2)">确认</el-button>
                        <el-button link size="small" style="margin-left: 5px;" @click="setNickNameHandler">取消</el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="" label="手机号" min-width="160">
                <template #default="scope">
                    <div class="col row items-center user-nickname" v-if="editorTarget!=scope.row.id||editorIndex!=3">
                        <span class="q-ml-md">
                            {{ scope.row.mobile }}
                        </span>
                        <IconPencli size="14" style="color:#000;" class="q-ml-md cusor-pointer editor-pencli" @click="setNickNameHandler(scope.row,3)"></IconPencli>
                    </div>
                    <div class="col row items-center" v-else>
                        <el-input v-model="nickNameModel" placeholder="请输入手机号" size="small" class="col q-ml-md" />
                        <el-button link size="small" class="q-ml-sm" type="primary" @click="setMemberNickName(scope.row,3)">确认</el-button>
                        <el-button link size="small" style="margin-left: 5px;" @click="setNickNameHandler">取消</el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="" label="系统角色" width="180">
                <template #default="scope">
                    <span v-if="scope.row.ic">超级管理员</span>
                    <el-popover :width="150" trigger="click" v-else>
                        <template #reference>
                            <div class="inline-block">
                                <div class="row items-center no-select cusor-pointer">
                                    <span v-if="scope.row.isa">管理员</span>
                                    <span v-else>成员</span>
                                    <IconDown size="18" style="margin-left: 5px;"></IconDown>
                                </div>
                            </div>
                        </template>
                        <el-menu mode="vertical" class="no-border md-menu">
                            <el-menu-item index="1" :disabled="scope.row.isa" @click="setMemberManagerStatus(scope.row,1)">设为管理员</el-menu-item>
                            <el-menu-item index="2"  :disabled="!scope.row.isa" @click="setMemberManagerStatus(scope.row,0)">设为成员</el-menu-item>
                        </el-menu>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="" label="操作" width="150">
                <template #default="scope">
                    <el-button v-if="scope.row.ic && userInfo.ic" link type="primary" class="ppt-button" @click="setSaExchangeHandler">转让</el-button>
                    <el-button v-else-if="!scope.row.ic" link type="primary" class="ppt-button" @click="removeMemeberHandler(scope.row)">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
  </div>

  <!-- 移除成员 -->
  <el-dialog v-model="removeVisible" title="移除成员" style="width:400px;">
      <main>
        <el-alert type="warning" show-icon :closable="false">
            <template #header>
                <span class="text-normal text-dark">你正在移除成员<span class="text-weight-bolder">{{ removeMemberModel.name }}</span>，移除后，该成员将无法访问本团队/企业，其在「我的空间」中的所有内容将被清空，且不可恢复，请谨慎操作</span>
            </template>
        </el-alert>
        <div class="text-dark q-my-md">如确认移除成员并清空内容，请输入「移除并清空」</div>
        <el-input v-model="removeTokenStr" size="large" class="full-width" input-style="font-family:pingfangr" placeholder="请输入：移除并清空" />
      </main>
      <template #footer>
        <el-button @click="removeVisible = false" size="large" class="ppt-button" :disabled="loading">我再想想</el-button>
        <el-button :type="removeTokenStr!='移除并清空'?'info':'primary'" size="large" @click="removeMember" :disabled="removeTokenStr!='移除并清空' || loading" class="ppt-button" :class="[removeTokenStr!='移除并清空'?'text-grey-8':'']">移除并清空</el-button>
      </template>
  </el-dialog>
  <!-- 转让管理员 -->
  <el-dialog v-model="exchangeVisible" title="转让管理员" style="width:400px;">
      <main>
        <el-alert type="warning" show-icon :closable="false">
            <template #header>
                <span class="text-normal text-dark">你正在转让超级管理员，转让后你将失去团队/企业管理的最高权限，请谨慎操作</span>
            </template>
        </el-alert>
        <el-select v-model="exchangeMember" size="large" class="full-width q-mt-md" filterable remote reserve-keyword placeholder="请输入成员姓名查找" :remote-method="querySearchAsync" :loading="exchangeLoading" >
            <el-option v-for="item in exchangeMemberList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </main>
      <template #footer>
        <el-button @click="setSaExchangeHandler(false)" size="large" class="ppt-button" :disabled="loading">我再想想</el-button>
        <el-button :type="exchangeMember==''?'info':'primary'" size="large" @click="exchangeTenantSa" :disabled="exchangeMember=='' || loading" class="ppt-button text-grey-8">确认转让</el-button>
      </template>
  </el-dialog>
  
  <invite-member v-if="showAddMember" :show-type="showAddMemberType" @close="()=>showAddMember=false" @imported="changeSearch"></invite-member>
</template>

<script lang="ts" setup>
import { ApiResult } from "@/configs/axios";
import { USER_DEFAULT_HEADER } from "@/configs/customer";
import OrgService from "@/services/OrgService";
import UserServices from "@/services/UserService";
import { useUserStore } from "@/store";
import { ElLoading, ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { ref } from "vue";
import { useRouter } from "vue-router";
import InviteMember from '@/views/components/Team/InviteMember.vue'

const userGroup = ref<{id:number,name:string}[]>([
    {id:0,name:'全部角色'},
    {id:1,name:'管理员'},
    {id:2,name:'成员'},
])
const userStore = useUserStore()
const {userInfo} = storeToRefs(userStore)
const data = ref<any[]>([])
const loading = ref(false)
const pageCount = ref(0)
const used = ref<number[]>([0,0])
const memberListRef = ref()
const editorTarget = ref('')
const editorIndex = ref(0)
const nickNameModel = ref(''||  Number)
const removeVisible = ref(false)
const removeTokenStr = ref('')
const removeMemberModel = ref<any>()
const exchangeVisible = ref(false)
const exchangeMember = ref('')
const exchangeLoading = ref(false)
const exchangeMemberList = ref<any[]>([])
const router = useRouter()
const showAddMember=ref(false)
const showAddMemberType=ref(1)

const parameters = ref<any>({
    t:0,
    k:'',
    pageIndex:1,
    pageSize:20
})
const mailRegex = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/

const setNickNameHandler = (target:any,type:number) =>{
    editorIndex.value = type
    if(target){
        editorTarget.value = target.id
        if(type==0) nickNameModel.value = target.name
        if(type==1) nickNameModel.value = target.account
        if(type==2) nickNameModel.value = target.mail
        if(type==3) nickNameModel.value = target.mobile
    }else{
        editorTarget.value = ''
        nickNameModel.value = ''
        editorIndex.value = 0
    }
}
const setSaExchangeHandler = (status:boolean)=>{
    if(status){
        exchangeMember.value = ''
        exchangeVisible.value = true
        exchangeMemberList.value = []
    }else{
        exchangeVisible.value = false
    }
}
const getMembers = async ()=>{
    if(loading.value) return
    loading.value=true

    const response = await OrgService.GetMembersAsync(parameters.value)

    if(response.data.resultCode == ApiResult.SUCCESS && response.data.data.pageData){
        data.value = data.value.concat(response.data.data.pageData)
        pageCount.value = response.data.data.pageCount
    }
    loading.value=false
}
const inviteHandler = (t:2|1)=>{
    showAddMemberType.value=t
    showAddMember.value=true
}
const removeMemeberHandler = (target:any)=>{
    removeMemberModel.value=target
    removeVisible.value=true
    removeTokenStr.value=''
}
const getMemberUsedStatus = async ()=>{

    const response = await OrgService.GetMembersUsedStatusAsync()
    if(response.data.resultCode == ApiResult.SUCCESS){
        used.value = response.data.data
    }

}
const changeSearch = ()=>{
    data.value = []
    pageCount.value = 0
    parameters.value.pageIndex=1
    getMembers()
}
const setMemberManagerStatus = async (target:any,value:0|1)=>{
    memberListRef.value.click()
    if(loading.value) return
    loading.value=true

    const response = await UserServices.SetMemberInfoAsync('',target.id,value)
    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'更新成功'})
        target.isa =value==1
        if(userInfo.value.id==target.id && value!=1){
            userInfo.value.ia = false
            router.push({path:'/space'})
        }
    }else{
        ElMessage.error({message:'更新失败'})
    }

    loading.value=false
}
const setMemberNickName = async (target:any,type:any)=>{
    if(loading.value || nickNameModel.value=='' || !nickNameModel.value) return
    if(type==2&&!mailRegex.test(nickNameModel.value)) return ElMessage.error({message:'请输入正确的邮箱'})
    loading.value=true
    
    let response
    if(type==0) response = await UserServices.SetMemberInfoAsync(nickNameModel.value,target.id,-1)
    if(type==1) response = await UserServices.SetMembers(target.id,1,nickNameModel.value,target.mail,target.mobile)
    if(type==2) response = await UserServices.SetMembers(target.id,2,target.account,nickNameModel.value,target.mobile)
    if(type==3) response = await UserServices.SetMembers(target.id,3,target.account,target.mail,nickNameModel.value)
    if(response){
        if(response.data.resultCode == ApiResult.SUCCESS){
            ElMessage.success({message:'更新成功'})
            if(type==0) target.name =nickNameModel.value
            if(type==1) target.account =nickNameModel.value
            if(type==2) target.mail =nickNameModel.value
            if(type==3) target.mobile =nickNameModel.value
            
            if(userInfo.value.id==target.id&&type==0){
                userInfo.value.nickname = nickNameModel.value
            }
            setNickNameHandler(null)
        }else{
            ElMessage.error({message:'更新失败'})
        }
    }

    loading.value=false
}
const tableScrollHandler = ()=>{
    if(pageCount.value>parameters.value.pageIndex){
        parameters.value.pageIndex++
        getMembers()
    }
}
const removeMember = async ()=>{
    removeVisible.value = false
    const loadingInstanct = ElLoading.service({text:'正在删除用户数据'})

    const response = await UserServices.RemoveMemberAsync(removeMemberModel.value.id)

    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'用户已被移除团队/企业'})
    }else{
        ElMessage.error({message:'移除失败'})
    }
    loadingInstanct.close()

    changeSearch()
    getMemberUsedStatus()
}
const querySearchAsync = async (queryString: string, cb: (arg: any) => void) => {
    const query = {
        t:0,
        k:queryString,
        pageIndex:1,
        pageSize:2000
    }
    const response = await OrgService.GetMembersAsync(query)

    if(response.data.resultCode == ApiResult.SUCCESS && response.data.data.pageData){
        exchangeMemberList.value = response.data.data.pageData
    }
}
const exchangeTenantSa =async () => {
    if(exchangeMember.value=='') return
    setSaExchangeHandler(false)

    const loadingInstanct = ElLoading.service({text:'正在转移超级管理员权限'})
    const response = await UserServices.SetTenantSAAsync(exchangeMember.value)

    if(response.data.resultCode == ApiResult.SUCCESS){
        ElMessage.success({message:'权限转移成功'})
        const isa = response.data.data
        userStore.setOldSaPermission(isa)
        loadingInstanct.close()
        if(!isa) router.push({path:'/space'})
        else changeSearch()
    }else{
        ElMessage.error({message:'移除失败'})
        loadingInstanct.close()
    }
    

}

getMembers()
getMemberUsedStatus()
</script>

<style>
.dark-table{
    font-size: 14px;
    color:#000;
}
.el-table.dark-table th.el-table__cell{
    background: #f1f2f4;
    border-color: #e8eaec;
    color:#000;
}
.user-nickname .editor-pencli{
    visibility: hidden;
}
.user-nickname:hover .editor-pencli{
    visibility:visible;
}
</style>