<template>
    <div class="role_manage_page list_page">
        <div class="list_page_content">
            <div class="list_top_content">
                <div class="list_top_search_content">
                    <div class="search_content_left">
                        <filterComponent :title="'Role Name or Id'"><a-input v-model:value="name" size="large" placeholder="Please input Role Name or Id"  @keydown.enter="searchList()"/></filterComponent>
                    </div>
                </div>
                <div class="list_top_button_content">
                    <a-button class="primary_button btn-margin-r-20" type="primary" size="large" @click="searchList()">Seach</a-button>
                    <a-button class="default_button" size="large" @click="resetList()">Reset</a-button>
                    <a-button class="primary_button btn-margin-t-35" type="primary" size="large" @click="addRole()">+Add Role</a-button>
                </div>
            </div>
            <div class="list_table_content">
                <a-table :columns="columns" :data-source="collectionList"  @change="changePage" :loading="tableLoading"
                    :pagination="{
                    showSizeChanger:true,
                    current: currentPage,
                    pageSize:pageSize,
                    total: total,
                    showQuickJumper:true,
                    bordered:false,
                    pageSizeOptions:['10','20','50'],
                }">
                    <template v-slot:bodyCell="{column,record, index}" >
                        <template v-if="column.dataIndex === 'operation'">
                            <div class="operate_list">
                                <div class="operate_item" @click="editRole(record)">Edit</div>
                                <div class="operate_item" @click="deleteRole(record,index)">Delete</div>
                            </div>
                        </template>
                        
                    </template>
                </a-table>
            </div>
        </div>

        <a-modal class="edit_modal_component" 
            v-model:visible="editRoleModal" 
            :footer="null" 
            :title="editRoleTitle"
            width="680px"
            :maskClosable="false"
            :centered="true"
            @cancel="closeRole"
        >
            <a-form ref="formRef" :model="formState" :rules="rules" :layout="'vertical'" >
                <a-form-item label="Role Name" name="name">
                    <a-input v-model:value="formState.name" size="large" placeholder="Please input role name"/>
                </a-form-item>
                <div>
                    <div class="form_item_title required">Role Permission</div>
                    <a-checkbox class="form_check_all" size="large" v-model:checked="permissionCheckAll" @change="perCheckAll">All</a-checkbox>
                    <table class="permission_table">
                        <tr v-for="(role) in rolePermission" :key="role.code">
                            <td class="first_td">
                                <div class="table_td_block"><a-checkbox size="large" v-model:checked="role.select" @change="checkLevelFirst(role)">{{role.resource}}</a-checkbox></div>
                            </td>
                            <td class="second_td">
                                <div class="table_td_block" v-for="(menu) in role.level2ResourceList" :key="menu.code"><a-checkbox size="large" v-model:checked="menu.select" @change="checkLevelSec(role,menu)">{{menu.resource}}</a-checkbox></div>
                            </td>
                            <td class="third_td">
                                <div class="table_td_block" v-for="(menu) in role.level2ResourceList" :key="menu.code">
                                    <div class="table_td_permission">
                                        <div v-for="(per) in menu.operationList" :key="per.code"><a-checkbox :disabled="!menu.select"  size="large" v-model:checked="per.select">{{per.resource}}</a-checkbox></div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
                
            </a-form>
            <div class="modal_button_list">
                 <a-button class="default_button btn-margin-r-20" size="large" @click="closeRole()">Cancel</a-button>
                 <a-button class="primary_button" type="primary" size="large" @click="confirmSubmit()">Submit</a-button>
            </div>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { defineComponent,ref,reactive,toRefs,UnwrapRef,onMounted,createVNode } from "vue";
import filterComponent from '@/component/filterComponent.vue'
import { message,Modal } from "ant-design-vue";
import { Https } from "@/tool/https";
import { WarningOutlined } from '@ant-design/icons-vue';

export default defineComponent({
    name:'roleManage',
    components:{filterComponent},
    setup(){
        let filter =  reactive({
            name:'',
        })
        let tableLoading = ref(false)
        let columns = reactive([
            { title: 'Role Name', align:'center', ellipsis: true,  dataIndex: 'name', key: 'name', width:250 },
            { title: 'Role Permission', align:'center', ellipsis: true,  dataIndex: 'permission', key: 'permission'},
            {
                title: 'Operations',
                key: 'operation',
                align:'center', 
                fixed: 'right',
                width: 250, 
                dataIndex:'operation',
              
            },
        ])
        let collectionList = ref([])
        let currentPage = ref(1)
        let pageSize = ref(10)
        let total = ref(1)
        let editRoleModal = ref(false)
        let editRoleTitle = ref('Add Role')
        let permissionCheckAll=ref(false)
        let rolePermission:any = ref([])
        let backupRolePermission:any = ref([])
        let formRef = ref();
        let formState = ref({
            id: '',
            name: '',
        });
        let rules = {
            name: [
                { required: true, message: 'Please input role name', trigger: 'blur' },
            ],
            roleType: [
                { required: true, message: '', trigger: 'blur' },
            ],
        }

        let changePage = (e:any) =>{
            currentPage.value = e.current
            pageSize.value = e.pageSize
            getRoleList()
        }

        let closeRole = () =>{
            formState.value = {
                id: '',
                name: '',
            }
            permissionCheckAll.value = false
            rolePermission.value = JSON.parse(JSON.stringify(backupRolePermission.value))
            editRoleModal.value = false
        }

        let addRole = () =>{
            editRoleTitle.value = 'Add Role'
            editRoleModal.value = true
        }

        let editRole = (data:any,) =>{
            editRoleModal.value = true
            editRoleTitle.value = 'Eidt Role'
            formState.value = {
                id: data.id,
                name: data.name,
            }
            rolePermission.value = changeSelectBoolean(data.rolePermission.level1ResourceList)
            permissionCheckAll.value = data.rolePermission.allSelect
        }

        let getRoleList = () =>{
            let data = {
                name : filter.name,
                page:currentPage.value,
                size:pageSize.value
            }
            tableLoading.value = true
            Https.axiosPost(Https.httpUrls.roleQueryRolePage, data).then(
                (rv: any) => {
                    if (rv) {
                        tableLoading.value = false
                        collectionList.value = rv.content.map((v:any) =>{
                            let data = {
                                ...v,
                                permission:v.rolePermission.level1ResourceList.filter((v:any)=>v.select).map((per:any) => per.resource).join('、')
                            }
                            return data
                        })
                        total.value = rv.total
                    }
                }
            );
        }

        let getMenuListPer = () =>{
            Https.axiosGet(Https.httpUrls.roleQueryPermissionList).then(
                (rv: any) => {
                    if (rv) {
                        rolePermission.value =  changeSelectBoolean(rv)
                        backupRolePermission.value = changeSelectBoolean(rv)
						console.log(rolePermission.value);
						
                    }
                }
            );
        }

        let changeSelectBoolean = (data:any) =>{
            let newData = JSON.parse(JSON.stringify(data))
            for(let first of newData){
                first.select = changeBooleanNumber(first.select)
                for(let sec of first.level2ResourceList){
                    sec.select = changeBooleanNumber(sec.select)
                    for(let third of sec.operationList){
                        third.select = changeBooleanNumber(third.select)
                    }
                }
            }
            return newData
        }

        //判断是布尔值则转为数字，数字则转布尔值
        let changeBooleanNumber = (data:any) => {
            let newData = data
            if(newData.constructor === Boolean){
                newData = newData ? 1 :0
            }else{
                newData = newData ? true :false
            }
            return newData
        }

        let searchList = () =>{
            currentPage.value = 1
            getRoleList()
        }

        let resetList = () =>{
            currentPage.value = 1
            filter.name = ''
            getRoleList()
        }


        let deleteRole = (data:any,index:any) =>{
            let confirmDelete = (data:any,index:any) =>{
                let newData = {
                    id:data.id
                }
                Https.axiosPost(Https.httpUrls.roleDelete, newData).then(
                    (rv: any) => {
                        if (rv) {
                            message.success('Delete success')
                            collectionList.value.splice(index,1)
                        }
                    }
                );
            }
            Modal.confirm({
                    title: "Are you sure delete the role?",
                    icon: createVNode(WarningOutlined),
                    class:'confirm_style',
                    okText: 'Ok',
                    cancelText: 'Cancel',
                    // centered:true,
                    onOk() {
                       confirmDelete(data,index)
                    }
                });
        }

        let perCheckAll = () =>{
            for(let first of rolePermission.value){
                first.select = permissionCheckAll.value
                for(let sec of first.level2ResourceList){
                    sec.select = permissionCheckAll.value
                    for(let third of sec.operationList){
                        third.select = permissionCheckAll.value
                    }
                }
            }
        }

        let checkLevelFirst = (firstDdata:any) =>{
            for(let sec of firstDdata.level2ResourceList){
                sec.select = firstDdata.select
                for(let third of sec.operationList){
                    third.select = firstDdata.select
                }
            }
            checkIsAllPer()
        }

        let checkLevelSec = (firstData:any, secondData:any) =>{
            for(let third of secondData.operationList){
                third.select = secondData.select
            }
            let status = false
            for(let item of firstData.level2ResourceList){
                if(item.select){
                    status = true
                    break
                }
            }
            firstData.select = status
            checkIsAllPer()
        }

        //判断是否已经全部勾选
        let checkIsAllPer = () =>{
            let status = true
            for(let first of rolePermission.value){
                if(!first.select){
                    status = false
                    break
                }
                for(let sec of first.level2ResourceList){
                    if(!sec.select){
                        status = false
                        break
                    }
                }
                if(!status){break}
            }
            permissionCheckAll.value = status
        }

        let confirmSubmit = () =>{
            let data = {
                ...formState.value,
                rolePermission:{
                    allSelect:permissionCheckAll.value ? 1 : 0,
                    level1ResourceList:changeSelectBoolean(rolePermission.value)
                },
                timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
            }
            formRef.value.validate().then(()=>{
                let status = false
                for(let first of rolePermission.value){
                    if(first.select){
                        status = true
                        break
                    }
                    for(let sec of first.level2ResourceList){
                        if(sec.select){
                            status = true
                            break
                        }
                    }
                    if(status){break}
                }
                if(!status){
                     message.error('Please check role permission')
                     return
                }
                submit()
            })
            let submit = () => {
                Https.axiosPost(Https.httpUrls.roleSaveOrEdit, data).then(
                    (rv: any) => {
                        if (rv) {
                            let tip = !formState.value.id ? 'Role added successfully' :'Edit role successfully'
                            message.success(tip)
                            resetList()
                            closeRole()
                        }
                    }
                );
            }
                
        }

        onMounted(() => {
           getRoleList()
           getMenuListPer()
        })
        
  
        return {
            ...toRefs(filter),
            tableLoading,
            columns,
            collectionList,
            currentPage,
            pageSize,
            total,
            permissionCheckAll,
            rolePermission,
            editRoleModal,
            editRoleTitle,
            formRef,
            formState,
            rules,
            changePage,
            closeRole,
            addRole,
            editRole,
            searchList,
            resetList,
            deleteRole,
            perCheckAll,
            checkLevelFirst,
            checkLevelSec,
            confirmSubmit,
        }
        
    },
   
});
</script>
<style lang="less" scoped>
.role_manage_page{
    padding-left: 28px;

    .role_pic{
        width: 50px;
    }

   .operate_list{
       display: flex;
       justify-content: space-between;
       padding: 0 50px;

       .operate_item{
            font-size: 14px;
            font-family: Roboto;
            font-weight: 400;
            color: #343579;
            cursor: pointer;
       }
   }
}

.form_check_all{
    margin: 10px 0;
}

.permission_table{
    width: 100%;
    margin-top: 10px;
    border-left:1px solid #DFDFDF;
    border-top:1px solid #DFDFDF;

    td{
        border-bottom: 1px solid #DFDFDF;
        border-right:  1px solid #DFDFDF;

        .table_td_block{
            padding: 16px 0 16px 20px;
            border-bottom: 1px solid #DFDFDF;

            &:last-child{
                border-bottom: none;
            }
        }

        .table_td_permission{
            display: flex;
            min-height: 23px;
        }
    }

    .first_td{
        width: 120px;
    }

    .second_td{
        width: 150px;
    }
}


</style>