<template>
    <div>
        <ht-table
            @load="loadData"
            :data="rows"
            :pageResult="pageResult"
            :selection="false"
            quick-search-props="defName,ownerName"
            :show-export="false"
            :showCustomColumn="false"
            ref="htTable"
            :header-cell-class-name="headerCellClassName"
            @selection-change="handleSelectionChange"
        >
            <template v-slot:toolbar >
                    <el-button
                        size="small"
                        @click="divertClick"
                        icon="icon-zhuanyi"
                        type="primary"
                        :disabled="isDisabled"
                        >转移</el-button
                    >
                    <el-button
                        size="small"
                        @click="copyClick"
                        icon="icon-copy"
                        :disabled="isDisabled"
                        >复制</el-button
                    >
                    <ht-delete-button
                        :url="delDefUser"
                        :htTable="$refs.htTable"
                        @after-delete="afterDelDefUser"
                        pk="defUserId"
                        :disabled="isDisabled"
                    >删除</ht-delete-button>
            </template>
            <template>
                <ht-table-column prop="rightType" label="授权类型" width="100">
                    <template v-slot="{row}">
                        <el-tag v-if="row.rightType == 'org'">组织</el-tag>
                        <el-tag v-if="row.rightType == 'role'">角色</el-tag>
                        <el-tag v-if="row.rightType == 'pos'">岗位</el-tag>
                        <el-tag v-if="row.rightType == 'user'">用户</el-tag>
                    </template>
                </ht-table-column>
                <ht-table-column prop="ownerName" label="授权名称" width="200" :show-overflow-tooltip="true"/>
                <ht-table-column prop="authDesc" label="所属授权" :show-overflow-tooltip="true"/>
                <ht-table-column prop="multiPle" label="类型" width="100" :render-header="renderHeaderMethod" :filters="[{text: '流程定义', value: '1'}, {text: '流程分类', value: '2'}]">
                    <template v-slot="{row}">
                        <el-tag v-if="row.multiPle == '1'">流程定义</el-tag>
                        <el-tag type="success" v-if="row.multiPle == '2'">流程分类</el-tag>
                    </template>
                </ht-table-column>
                <ht-table-column prop="defName" label="流程名称/分类名称" :show-overflow-tooltip="true"/>
                <ht-table-column prop="defKey" label="流程Key/分类ID" width="180" :show-overflow-tooltip="true"/>
                <ht-table-column prop="start" label="启动" width="60">
                    <template v-slot="{row}">
                        <el-tag v-if="row.start == 1">是</el-tag>
                        <el-tag type="warning" v-if="row.start != 1">否</el-tag>
                    </template>
                </ht-table-column>
                <ht-table-column prop="management" label="定义" width="250">
                    <template v-slot="{row}">
                        <span>{{getAuthDesc(row.content,'management')}}</span>
                    </template>
                </ht-table-column>
                <ht-table-column prop="task" label="任务" width="100">
                    <template v-slot="{row}">
                        <el-tag v-if="row.task == 1">是</el-tag>
                        <el-tag type="warning" v-if="row.start != 1">否</el-tag>
                    </template>
                </ht-table-column>
                <ht-table-column prop="instance" label="实例" width="80">
                    <template v-slot="{row}">
                        <span>{{getAuthDesc(row.content,'instance')}}</span>
                    </template>
                </ht-table-column>
            </template>
        </ht-table>
        <!--用户选择对话框  -->
        <ht-user-dialog ref="eipUserDialog" @on-confirm="eipUserDialogOk" append-to-body />
        <!-- 组织选择对话框  -->
        <ht-org-post-dialog ref="eipOrgDialog" @on-confirm="eipOrgDialogOk" append-to-body />
        <!-- 岗位选择对话框  -->
        <ht-post-dialog ref="eipPostDialog" @on-confirm="eipPostDialogOk" append-to-body />
        <!-- 角色选择对话框  -->
        <ht-role-dialog ref="eipRoleDialog" @on-confirm="eipRoleDialogOk" append-to-body />
  </div>
</template>

<script>
import req from "@/request.js";
const eipUserDialog = () => import("@/components/dialog/EipUserDialog.vue");
const eipOrgDialog = () => import("@/components/dialog/EipOrgDialog.vue");
const eipPostDialog = () => import("@/components/dialog/EipPostDialog.vue");
const eipRoleDialog = () => import("@/components/dialog/EipRoleDialog.vue");
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'
export default {
    components: {eipUserDialog,eipOrgDialog,eipPostDialog,eipRoleDialog},
    name: "def-authorize-page-dialog",
    props:["data"],
    computed: {
        delDefUser: function() {
            return window.context.bpmModel + "/flow/bpmDefUser/v1/delDefUser";
        }
    },
    mixins: [tableHeaderFilter],
    data() {
        return {
            type:"",//1、转移，2、复制
            selectDefUserIds:[],//选择要转移、复制的 authorizeId（流程授权ID）、ownerId/ownerName（用户、组织、岗位、角色Id/名称）
            pageResult: {
                page: 1,
                pageSize: 20,
                total: 0
            },
            rows: [],
            pageUrl:`${window.context.bpmModel}/flow/defAuthorize/v1/getAuthDetailPage`,
            defDescMap: {m_edit:'设计',m_del:'删除',m_start:'启动',m_set:'设置',m_clean:'清除数据'},
            instanceDescMap: {i_del:'删除',i_org:'本部门'},
            isDisabled:true,
      selectedList:[]
        };
    },
    watch: {
        data: {
            handler(newValue, oldValue) {
                this.$nextTick(()=>{
                    this.$refs.htTable.load();
                });
            },
            deep: true,
            immediate:true
        },
        selectedList:{
      handler(val){
        this.isDisabled = val.length < 1 ? true : false
      },
      deep:true
    }
    },
    methods: {
        handleSelectionChange(selection){
      this.selectedList = selection
    },
         //转移
        divertClick(){
            this.type="";
            this.selectDefUserIds = [];
            let selectSelection = this.$refs.htTable.$refs.htTable.selection;
            if(selectSelection && selectSelection.length==0) {
                this.$message.error("请选择要转移的数据");
                return;
            }
            for(let k = 0;k<selectSelection.length;k++){
                this.selectDefUserIds.push(selectSelection[k].defUserId);
            }  
            this.type="1";
            if(this.data.type=='user'){
                this.$refs["eipUserDialog"].showDialog();
            }
            if(this.data.type=='org'){
                this.$refs["eipOrgDialog"].showDialog();
            }
            if(this.data.type=='post'){
                this.$refs["eipPostDialog"].showDialog();
            }
            if(this.data.type=='role'){
                this.$refs["eipRoleDialog"].showDialog();
            }
        },
        //复制
        copyClick(){
            this.type="";
            this.selectDefUserIds = [];
            let selectSelection = this.$refs.htTable.$refs.htTable.selection;
            if(selectSelection && selectSelection.length==0) {
                this.$message.error("请选择要复制的数据");
                return;
            }
            for(let k = 0;k<selectSelection.length;k++){
                this.selectDefUserIds.push(selectSelection[k].defUserId);
            }   
            this.type="2";
            if(this.data.type=='user'){
                this.$refs["eipUserDialog"].showDialog();
            }
            if(this.data.type=='org'){
                this.$refs["eipOrgDialog"].showDialog();
            }
            if(this.data.type=='post'){
                this.$refs["eipPostDialog"].showDialog();
            }
            if(this.data.type=='role'){
                this.$refs["eipRoleDialog"].showDialog();
            }
        },
        operatingDefUser(map){
            req.post(window.context.bpmModel + "/flow/bpmDefUser/v1/operatingDefUser",map).then(res => {
                if(res.data.state){
                    this.$message.success(res.data.message);
                    this.$nextTick(()=>{
                        this.$refs.htTable.load();
                    });
                }
            });
        },
        //选择用户确认事件
        eipUserDialogOk(data) {
            if (data && data.length>0) {
                let userArray= [];
                for(let k = 0;k<data.length;k++){
                    if(data[k].account!=this.data.typeValue.account){
                        userArray.push({userId:data[k].id,userName:data[k].fullname});
                    }
                }
                let map = {
                    paType:this.data.type,
                    userArray: userArray,
                    defUserIds: this.selectDefUserIds,
                    type: this.type
                };
                this.operatingDefUser(map);
            }
        },
        //选择所属组织确认事件
        eipOrgDialogOk(data) {
            if (data && data.length>0) {
                let orgArray= [];
                for(let k = 0;k<data.length;k++){
                    if(data[k].id!=this.data.typeValue.id){
                        orgArray.push({orgId:data[k].id,orgName:data[k].name});
                    }
                }
                let map = {
                    paType:this.data.type,
                    orgArray: orgArray,
                    defUserIds: this.selectDefUserIds,
                    type: this.type
                };
                this.operatingDefUser(map);
            }
        },
        //选择所属岗位确认事件
        eipPostDialogOk(data) {
            if (data && data.length>0) {
                let postArray= [];
                for(let k = 0;k<data.length;k++){
                    if(data[k].id!=this.data.typeValue.id){
                        postArray.push({postId:data[k].id,postName:data[k].name});
                    }
                }
                let map = {
                    paType:this.data.type,
                    postArray: postArray,
                    defUserIds: this.selectDefUserIds,
                    type: this.type
                };
                this.operatingDefUser(map);
            }
        },
        //选择所属角色确认事件
        eipRoleDialogOk(data) {
            if (data && data.length>0) {
                let roleArray= [];
                for(let k = 0;k<data.length;k++){
                    if(data[k].id!=this.data.typeValue.id){
                        roleArray.push({roleId:data[k].id,roleName:data[k].name});
                    }
                }
                let map = {
                    paType:this.data.type,
                    roleArray: roleArray,
                    defUserIds: this.selectDefUserIds,
                    type: this.type
                };
                this.operatingDefUser(map);
            }
        },
        loadData(param, cb) {
            param.querys || (param.querys = []);
            if(this.data.type=='post'){
                param.querys.push({
                    group: "main",
                    property: "rightType",
                    value: "pos",
                    operation: "EQUAL",
                    relation: "AND"
                });
            }else{
                param.querys.push({
                    group: "main",
                    property: "rightType",
                    value: this.data.type,
                    operation: "EQUAL",
                    relation: "AND"
                });
            }
            param.querys.push({
                group: "main",
                property: "ownerId",
                value: this.data.typeValue.id,
                operation: "EQUAL",
                relation: "AND"
            });
            req.post(this.pageUrl,param).then(response => {
                this.rows = response.data.rows;
                this.pageResult = {
                    page: response.data.page,
                    pageSize: response.data.pageSize,
                    total: response.data.total
                };
            }).finally(() => cb());
        },
        //获取实例、定义授权内容
        getAuthDesc(jsonStr,type){
            if(jsonStr){
                let _this = this;
                let jsonObj = JSON.parse(jsonStr);
                let descArray = [];
                for (let key in jsonObj) {
                    if (jsonObj.hasOwnProperty(key)) {
                        if(jsonObj[key]==true){
                            if(type!='instance'){
                                if(_this.defDescMap[key]){
                                    descArray.push(_this.defDescMap[key]);
                                }
                            }else{
                                if(_this.instanceDescMap[key]){
                                    descArray.push(_this.instanceDescMap[key]);
                                }
                            }
                        }
                    }
                }
                if(descArray.length>0){
                    return descArray.join("、");
                }
            }
            return '无配置';
        },
        afterDelDefUser(){
            this.$refs.htTable.load();
        },
    }
};
</script>

<style lang="scss" scoped>
::v-deep{
  .cell>.el-table__column-filter-trigger{
    display: none;
  }
}
div[aria-invalid="true"] >>> .el-input__inner,
div[aria-invalid="true"] >>> .el-input__inner:focus {
  border-color: #f56c6c;
}
</style>