<template>
    <el-dialog v-model="show" v-loading="loading" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false" style="max-width:550px;">
        <template #header>
            <div class="text-title" ref="headDom">分享设置</div>
        </template>
        <div>
            <div class="row items-center">
                <el-select v-model="currentType" placeholder="分享类型" style="width: 100px;">
                    <el-option :label="x.label" :value="x.value" v-for="x in shareTypeItems" />
                </el-select>
                <div class="col q-mx-md">
                    <el-select v-model="selectedCompnays"  collapse-tags multiple placeholder="请选择公司" class="full-width" v-if="currentType==1">
                        <el-option :label="x.BName" :value="x.Id" v-for="x in allBranchs" />
                    </el-select>
                    <el-select v-model="selectedPeoples" filterable collapse-tags multiple placeholder="请选择员工" class="full-width" v-if="currentType==4">
                        <el-option :label="x.name" :value="x.empId" v-for="x in allPeoples" />
                    </el-select>
                    <el-tree-select
                        placeholder="请选择部门"
                        v-model="selectedDepartment"
                        :data="allOrgs"
                        :render-after-expand="false"
                        show-checkbox
                        multiple
                        :props="defaultProps"
                        node-key="DepartmentId"
                        check-strictly
                        class="full-width"
                        collapse-tags
                        v-if="currentType==2"
                    />
                </div>
                <el-select v-model="selectedPermission" style="width: 150px;" collapse-tags multiple placeholder="请选择权限">
                    <el-option :label="x.label" :value="x.value" v-for="x in permissions" />
                </el-select>
                <el-button class="q-ml-md" @click="saveShareHandler">添加</el-button>
            </div>
            <el-scrollbar height="300px" class="q-mt-lg">
                <div class="row items-center q-mb-md" v-for="x in shareList">
                    <el-avatar icon="OfficeBuilding" size="36" shape="square" class="bg-primary" v-if="x.ShareType==0"></el-avatar>
                    <el-avatar icon="HomeFilled" size="36" shape="square" class="bg-secony" v-else-if="x.ShareType==1"></el-avatar>
                    <el-avatar icon="Menu" size="36" shape="square" class="bg-waring" v-else-if="x.ShareType==2"></el-avatar>
                    <el-avatar icon="UserFilled" size="36" shape="square" v-else-if="x.ShareType==4"></el-avatar>
                    <div class="q-mx-md col">
                        <div class="text-subtitle2">
                            <span v-if="x.ShareType==0">所有人</span>
                            <span v-else>
                                {{ x.ShareTargetName.split(':')[1].split(',')[0] }}
                                <span class="q-mr-md" v-if="x.ShareTargetIds.split(',').length>0">等</span>
                                <el-popover :width="300" trigger="click">
                                    <template #reference>
                                        <el-tag size="small" v-if="x.ShareTargetIds.split(',').length>0" effect="light" class="cusor-pointer">
                                            {{ x.ShareTargetIds.split(',').length }}个{{ x.ShareType==1?'公司':(x.ShareType==2?'部门':'人员') }}
                                        </el-tag>
                                    </template>
                                    <div class="row wrap">
                                        <el-tag v-for="(item,i) in x.ShareTargetName.split(':')[1].split(',')" :key="i" type="success" class="q-mr-md q-mb-md" effect="plain">
                                            {{ item }}
                                        </el-tag>
                                    </div>
                                </el-popover>
                            </span>
                        </div>
                        <div class="text-small text-info">
                            <span v-if="x.ShareType==0">所有在职员工均适用于此规则</span>
                            <span v-else>{{ x.ShareTargetName.split(':')[0] }}权限</span>
                        </div>
                    </div>
                    <el-popover :width="275" >
                        <template #reference>
                            <div class="cusor-pointer" style="margin-top: 8px;">
                                <el-icon size="16" class="q-ml-md" title="可以复制" v-if="x.EditTypeList.indexOf(1)!=-1"><CopyDocument /></el-icon>
                                <el-icon size="16" color="#f89c53" class="q-ml-md" title="可以修改" v-if="x.EditTypeList.indexOf(2)!=-1"><EditPen /></el-icon>
                                <el-icon size="16" color="#0b40fe" class="q-ml-md" title="可以下载" v-if="x.EditTypeList.indexOf(3)!=-1"><Download /></el-icon>
                            </div>
                        </template>
                        <el-checkbox-group v-model="x.copyEditor">
                            <el-checkbox v-for="city in permissions" :key="city.value" :label="city.value">{{ city.label }}</el-checkbox>
                        </el-checkbox-group>
                        <div class="text-right q-mt-md">
                            <el-button size="mini" type="primary" @click="updateShareRuleAsync(x)">确认修改</el-button>
                        </div>
                    </el-popover>
                    <el-divider direction="vertical" class="q-mx-md" />
                    <el-tooltip effect="dark" content="删除规则">
                        <el-button link @click="removeShareRuleAsync(x.ShareId)"><el-icon size="16" color="#FF4B86"><Delete /></el-icon></el-button>
                    </el-tooltip>
                </div>
                <el-empty :image-size="100" v-if="!shareList || shareList.length==0" description="未设置分享信息" />
            </el-scrollbar>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="()=>closedhandler()">关闭</el-button>
                <!-- <el-button type="primary" @click="()=>closedhandler()"> 保存分享配置 </el-button> -->
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ApiResult } from '@/configs/axios';
import OrgService from '@/services/OrgService';
import { ref } from 'vue';
import { View,Download,EditPen,Delete,CopyDocument } from '@element-plus/icons-vue';
import { ElDialog, ElMessage, ElMessageBox } from 'element-plus';
import ConfigService from '@/services/ConfigService';
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";

const { userInfo } = storeToRefs(useUserStore());

const props = defineProps({
    id:{
        type:Number,
        required:true
    },
    fileType:{
        type:Number,
        required:true
    },
})
const emit = defineEmits<{
  (event: 'close'): void
}>()

const defaultProps = {
  children: 'ChildList',
  label: 'DepartmentName'
}
const show=ref(true)
const headDom = ref()
const shareTypeItems = ref<{label:string,value:number}[]>([])
const permissions = ref<{label:string,value:number}[]>([])
const loading = ref(true)
const selectedDepartment = ref<any[]>([])
const selectedCompnays=ref<number[]>([])
const selectedPeoples=ref<number[]>([])
const selectedPermission = ref<number[]>([])
const allBranchs = ref<any[]>([])
const allOrgs = ref<any[]>([])
const allPeoples = ref<any[]>([])
const shareList = ref<any[]>([])
shareTypeItems.value.push({label:'所有人',value:0})
if(userInfo.value.isp) {
    shareTypeItems.value.push({label:'公司',value:1})
    shareTypeItems.value.push({label:'部门',value:2})
}
shareTypeItems.value.push({label:'员工',value:4})
permissions.value.push({label:'复制',value:1})
permissions.value.push({label:'编辑',value:2})
permissions.value.push({label:'导出',value:3})
const currentType = ref<number>(0)

const closedhandler=()=>{
    emit('close')
}
const getDepartments = async ()=>{
    OrgService.GetTreeDepartmentsAsync().then((res)=>{
        if(res.data.resultCode == ApiResult.SUCCESS && res.data.data.length>0){
            allOrgs.value=res.data.data
            allOrgs.value.forEach(x=>{
                x.disabled=true
            })
        }
        loading.value=false
    }).catch(()=>{
        loading.value=false
    })
}
const getAllBranch = async ()=>{
    OrgService.GetAllBranchsAsync().then((res)=>{
        if(res.data.resultCode == ApiResult.SUCCESS && res.data.data.length>0){
            allBranchs.value=res.data.data
        }
        loading.value=false
    }).catch(()=>{
        loading.value=false
    })
}
const getAllPeople = async ()=>{
    OrgService.GetAllEmployerAsync().then((res)=>{
        if(res.data.resultCode == ApiResult.SUCCESS && res.data.data.length>0){
            allPeoples.value=res.data.data
        }
        loading.value=false
    }).catch(()=>{
        loading.value=false
    })
}
const getShareAsync = () => {
    ConfigService.GetShareAsync(props.id).then((res)=>{
        if(res.data.resultCode == ApiResult.SUCCESS && res.data.data.length>0){
            shareList.value=res.data.data
            shareList.value.forEach((x)=>{
                x.copyEditor = JSON.parse(JSON.stringify(x.EditTypeList))
            })
        }
        loading.value=false
    }).catch(()=>{
        loading.value=false
    })
}
const removeShareRuleAsync=(id:number)=>{
    ElMessageBox.confirm('你确定要删除这条分享规则吗？','删除提醒',{
      confirmButtonText: '确定删除',
      cancelButtonText: '取消'
    })
    .then(() => {
        loading.value=true
        ConfigService.RemoveShareAsync(id).then((res)=>{
            if(res.data.resultCode == ApiResult.SUCCESS){
                ElMessage.success({
                    message:'操作成功'
                })
                getShareAsync()
            }else{
                ElMessage.error({
                    message:'操作执行失败，请刷新页面重试'
                })
            }
            loading.value=false
        }).catch(()=>{
            ElMessage.error({
                message:'操作执行失败，请刷新页面重试'
            })
            loading.value=false
        })
    })
    .catch(() => { })
}
const updateShareRuleAsync=async (x:any)=>{
    if(loading.value) return
    loading.value=true
    let errmsg=''
    if(!x.copyEditor || x.copyEditor.length==0) errmsg='请选择权限'
    if(errmsg==''){
        try {
            let response = await ConfigService.UpdateShareAsync({
                ShareId:x.ShareId,
                ShareTargetIds:x.ShareTargetIds,
                EditType:x.copyEditor.join(',')
            })

            if(response.data.resultCode==ApiResult.SUCCESS){
                ElMessage.success({
                    message:'设置成功'
                })
                headDom.value.click()
                getShareAsync()
            } else errmsg='修改权限失败，请刷新重试'
        } catch (error) {
            errmsg = '修改权限失败，请刷新重试'
        }
    }
    if(errmsg!='') {
        ElMessage.error({
            message:errmsg
        })
    }
    loading.value=false
}
const saveShareHandler = async ()=>{
    if(loading.value) return
    loading.value=true
    let errmsg=''
    if(currentType.value==1 && selectedCompnays.value.length==0)errmsg='请选择公司'
    else if(currentType.value==2 && selectedDepartment.value.length==0)errmsg='请选择部门'
    else if(currentType.value==4 && selectedPeoples.value.length==0)errmsg='请选择人员'
    else if(selectedPermission.value.length==0)errmsg='请进行权限设定'
    if(errmsg==''){
        let ids:string = '0'
        if(currentType.value==1) ids = selectedCompnays.value.join(',')
        else if(currentType.value==2) ids = selectedDepartment.value.join(',')
        else if(currentType.value==4) ids = selectedPeoples.value.join(',')
        try {
            let response = await ConfigService.SetShareAsync({
                ShareFileId: props.id,
                FileType:props.fileType,
                ShareList: [{
                    ShareType: currentType.value,
                    ShareTargetIds: ids,
                    EditType: selectedPermission.value.join(',')
                }]
            })

            if(response.data.resultCode==ApiResult.SUCCESS){
                ElMessage.success({
                    message:'分享成功'
                })
                getShareAsync()
            } else errmsg='保存分享配置失败，请重试'
        } catch (error) {
            errmsg = '保存分享配置失败，请重试'
        } 
    } 
    if(errmsg!='') {
        ElMessage.error({
            message:errmsg
        })
    }
    loading.value=false
}
getDepartments()
getAllBranch()
getAllPeople()
getShareAsync()
</script>
<style>
.share-item{}
</style>