<template>
    <el-dialog v-model="show" title="邀请成员" style="width:744px;" @close="closed" class="bold-head q-pa-none">
        <div class="row InviteMember" style="min-height: 440px;">
            <div class="q-pa-md full-height" style="width:164px; border-right: 1px solid #f1f2f4;">
                <el-menu class="no-border md-menu" :default-active="currentMenu">
                    <el-menu-item index="1" @click="currentMenu = '1'">邀请成员</el-menu-item>
                    <el-menu-item index="2" @click="currentMenu = '2'">批量导入成员</el-menu-item>
                </el-menu>
            </div>
            <div class="col" style="padding: 24px;" v-if="currentMenu == '1'">
                <div class="text-dark">发送链接邀请好友加入企业，一起创作吧~</div>
                <div class="q-mt-xl">
                    <el-popover trigger="click" ref="popoverRef" width="532px"
                        popper-style="border-radius:10px; padding: 5px;">
                        <template #reference>
                            <div class="row items-center borders-light group-share-buttom rounded" style="padding:3px">
                                <div class="col row items-center q-pl-lg cusor-pointer">
                                    <span>加入团队/企业后身份为</span>
                                    <span class="q-mx-md">{{ inviteIsAdmin == '0' ? '成员' : '管理员' }}</span>
                                    <IconDown size="16px"></IconDown>
                                </div>
                                <el-button type="primary" class="rounded" @click="(event) => copyInviteUrlHandler(event)"
                                    :loading="copyLoading">复制链接</el-button>
                            </div>
                        </template>
                        <el-menu class="no-border md-menu" :default-active="inviteIsAdmin">
                            <el-menu-item index="0" @click="setIsAdminHandler(0)">邀请成员</el-menu-item>
                            <el-menu-item index="1" @click="setIsAdminHandler(1)">邀请管理员</el-menu-item>
                        </el-menu>
                    </el-popover>
                </div>
                <div class="q-mt-md text-small text-info">链接有效期14天</div>
            </div>
            <div class="col column" style="padding: 24px;" v-else>
                <div class="row items-center">
                    <div class="num-serial text-small q-mr-md">1</div>
                    <div class="col text-dark" style="font-size: 16px">下载模板</div>
                </div>
                <div class="row items-center">
                    <div style="border-left: 1px dashed #000; margin-left: 8px;margin-right: 9px; height:98px;"></div>
                    <div class="col q-ml-md">
                        <el-alert type="info" :closable="false">
                            <template #title>
                                <div class="row items-center">
                                    <div class="col">请按参考模板填写内容；字段不符合规则，则不予以导入</div>
                                    <div class="text-primary row items-center cusor-pointer q-ml-md" @click="goDownload">
                                        <IconToBottom size="16" class="q-mr-sm"></IconToBottom>
                                        <span>下载导入模板</span>
                                    </div>
                                </div>
                            </template>
                        </el-alert>
                    </div>
                </div>
                <div class="row items-center">
                    <div class="num-serial text-small q-mr-md">2</div>
                    <div class="col text-dark" style="font-size: 16px">上传文件</div>
                </div>
                <div class="q-mt-lg">
                    <el-upload class=" text-primary" drag  accept=".xls,.xlsx"
                    :action="getUploadActionUrl()" 
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :limit="1"
                    ref="upload"  
                    :on-exceed="handleExceed"  
                    >
                    <template #trigger>
                        <IconUpload size="54" class=""></IconUpload>
                        <div class="el-upload__text">
                            <div style="font-size: 16px;" class="q-my-lg">成员名单仅支持 .xls .xlsx</div>
                            <div class="text-center">
                                <el-button class="ppt-button" type="primary" size="target">导入成员名单</el-button>
                            </div>
                        </div>
                    </template>
                    <template #tip>
                        <div></div>
                    </template>
                    </el-upload>
                </div>
                <template v-if="dialogVisible">
                    <div class="text-primary" style="font-weight: bold;">提示</div>
                    <div class="q-mt-xs  row flex-between items-center" style="position: relative;">
                        <div>
                            <el-alert show-icon title="人员总数" type="info" :closable="false">
                                <i class="el-icon-coin"></i>
                                <span>{{UploadResults.totalNum>0?UploadResults.totalNum:0}}</span>
                            </el-alert>
                        </div>
                        <div class="q-px-md">
                            <el-alert show-icon title="成功人数" type="success" :closable="false">
                                <i class="el-icon-coin"></i>
                                <span>{{UploadResults.successNum>=0?UploadResults.successNum:0}}</span>
                            </el-alert>
                        </div>
                        <div>
                            <el-alert show-icon title="失败人数" type="warning" :closable="false">
                                <i class="el-icon-coin"></i>
                                <span class="row">
                                    <span>{{UploadResults.failNum>=0?UploadResults.failNum:0}}</span>
                                    <span v-if="UploadResults.DownloadUrl" class="col text-primary row items-center cusor-pointer q-ml-md"
                                    @click="goDownload(1)">
                                        <IconToBottom size="16" class="q-mr-sm"></IconToBottom>
                                        <span>下载</span>
                                    </span>
                                </span>
                            </el-alert>
                        </div>
                        <span class="close-btn cursor-pointer column items-center flex-center"><IconClose :size="10" @click="dialogVisible = false,closeUploadRes()"></IconClose></span>
                        <!-- <el-button @click="dialogVisible = false,closeUploadRes()">关闭</el-button> -->
                        <!-- <el-button type="primary" @click="dialogVisible = false">
                            确定
                        </el-button> -->
                    </div>
                </template>
                
            </div>
        </div>
    </el-dialog>
    <!-- <el-dialog v-model="dialogVisible" title="导入成员名单提示" width="500" @close="closeUploadRes">
        <div class="row flex-between">
            <div>
                <el-alert show-icon title="人员总数" type="info" :closable="false">
                    <i class="el-icon-coin"></i>
                    <span>{{UploadResults.totalNum>0?UploadResults.totalNum:0}}</span>
                </el-alert>
            </div>
            <div class="q-px-md">
                <el-alert show-icon title="成功人数" type="success" :closable="false">
                    <i class="el-icon-coin"></i>
                    <span>{{UploadResults.successNum>=0?UploadResults.successNum:0}}</span>
                </el-alert>
            </div>
            <div>
                <el-alert show-icon title="失败人数" type="warning" :closable="false">
                    <i class="el-icon-coin"></i>
                    <span class="row">
                        <span>{{UploadResults.failNum>=0?UploadResults.failNum:0}}</span>
                        <span v-if="UploadResults.DownloadUrl" class="col text-primary row items-center cusor-pointer q-ml-md"
                        @click="goDownload(1)">
                            <IconToBottom size="16" class="q-mr-sm"></IconToBottom>
                            <span>下载</span>
                        </span>
                    </span>
                </el-alert>
            </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="dialogVisible = false">
              确定
            </el-button>
          </div>
        </template>
    </el-dialog> -->
      
</template>

<script lang="ts" setup>
import { ApiResult } from "@/configs/axios"
import UserServices from "@/services/UserService"
import { useUserStore } from "@/store"
import { copyText } from "@/utils/clipboard"
import { dateFormat } from "@/utils/common"
import { ElMessage } from "element-plus"
import { storeToRefs } from "pinia"
import { ref, unref } from "vue"
import { domainManager } from '@/utils/domainManager'
import type { ElAlert,UploadUserFile,UploadInstance, UploadProps, UploadRawFile } from 'element-plus';

const props = defineProps({
    showType: {
        type: Number,
        default: 1
    },
})

const emit = defineEmits<{
    (event: 'close'): void,
    (event: 'imported'): void
}>()

const show = ref(true)
const currentMenu = ref(props.showType.toString())
const inviteIsAdmin = ref('0')
const popoverRef = ref()
const copyLoading = ref(false)
const useUser = useUserStore()
const { userInfo } = storeToRefs(useUser)
const dialogVisible = ref(false)
const UploadResults = ref({} as any)
const fileList = ref<UploadUserFile[]>([])
const loading = ref(false)

const closeUploadRes = () => {
    UploadResults.value = {}
    fileList.value = []
}
const closed = () => {
    emit('close')
}
const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  upload.value!.handleStart(file)
  upload.value.submit()
}

const goDownload = (type:any) =>{
    if(type==1) window.location.href = UploadResults.value.DownloadUrl
    else window.location.href ='https://imgfile.oytour.com/static/pptist/pptusertemplate.xlsx'
}
//导入文件地址
const getUploadActionUrl=()=>{
    loading.value = true
  let uid=userInfo.value.id;
   const url=domainManager().domainUrl.replace("common","file")+`?cmd=dmc_post_LocalFileUpload&Type=19&fileType=1&PPTEmployeeId=${encodeURIComponent(uid)}`
   return url;
}

const handleAvatarSuccess= (res:any)=>{
    console.log("handleAvatarSuccess_res",res);
    if(res.data){
        UploadResults.value = res.data
        if(res.data.successNum>0) emit('imported')
        if(res.data.failUrl) UploadResults.value.DownloadUrl = domainManager().DownloadUrl.replace("common","file")+`${res.data.failUrl}`
    }
}

const beforeAvatarUpload=  (res:any)=>{
    closeUploadRes()
    dialogVisible.value = true
    console.log("beforeAvatarUpload_res",res);
    // fileList.value.unshift({
    //     name: res.name+new Date().getTime(),
    //     url: ''
    // })
    
}

const copyInviteUrlHandler = async (e: MouseEvent) => {
    e.stopPropagation()
    if (copyLoading.value) return

    copyLoading.value = true
    const ia = inviteIsAdmin.value == '0' ? 0 : 1
    const response = await UserServices.SetTenantInviteCodeAsync(ia)
    if (response.data.resultCode == ApiResult.SUCCESS) {
        let currentDate = new Date();
        currentDate.setDate(currentDate.getDate() + 14);
        const url = `${window.location.origin}/j/${response.data.data}  \n我正在使用Travel Design,点击链接立即加入我的团队。\n邀请人：${userInfo.value.nickname}\n团队/企业名称：${userInfo.value.company}\n有效期至：${dateFormat(currentDate, "YYYYMMDD")}`
        copyText(url)
        ElMessage.success({ message: '复制成功' })
    } else {
        ElMessage.error({ message: '当前无法生成邀请链接' })
    }

    copyLoading.value = false
    return false
}
const setIsAdminHandler = (isa: number) => {
    inviteIsAdmin.value = isa.toString()
    popoverRef.value?.hide?.()
}

</script>

<style scoped>
.InviteMember::v-deep(.el-upload-dragger) {
    padding: 15px 0;
}
.InviteMember .content-item{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    font-size: 0.73vw;
    margin-bottom: 0.7vw;
    color: #000000;
}
.InviteMember .close-btn{
    position: absolute;
    top: 20px;
    right: -25px;
    width: 18px;
    height:18px;
    border:1px solid #AFAFAF;
    text-align: center;
    color:#AFAFAF;
    border-radius: 50%;
}
.bold-head .el-dialog__header {
    font-weight: 800 !important;
}

.bold-head .el-dialog__body {
    border-top: 1px solid #F1f2f4;
}

.q-pa-none .el-dialog__body {
    padding: 0 !important;
}

.group-share-buttom:hover {
    border-color: var(--el-color-primary);
}

.num-serial {
    width: 18px;
    height: 18px;
    color: #000;
    border: 1px solid #000;
    border-radius: 18px;
    line-height: 16px;
    text-align: center;
    background: #FFF;
}
</style>