<template>
  <div style="height: 100%;" class="department-authorization">
    <CSTable ref="csTable" v-if="loadTree" style="height: 100%;" :tableData="tableData" :tableConfig="tableConfig"></CSTable>
    <el-drawer
        size="900px"
        :title="$t(dataAuthorizationDialogTitle)"
        :visible.sync="dataAuthorizationFlag"
        custom-class="custom-class"
        :modal="false"
        :before-close="closeDataAuthorizationDialog">
        <DataAuthorizationDialog :authority-data-category-list="authorityDataCategoryList" :org-id="orgId" authority-type="2" v-if="dataAuthorizationFlag" />
        <div class="dialog-footer">
            <el-button @click="closeDataAuthorizationDialog">{{
                $t("cs.common.button.cancel")
            }}</el-button>
            <el-button type="primary" @click="submitDataAuthorizationDialog">{{
                $t("cs.common.button.ok")
            }}</el-button>
        </div>
    </el-drawer>
    <el-drawer
        size="640px"
        :title="$t(menuAuthorizationDialogTitle)"
        :visible.sync="menuAuthorizationFlag"
        :modal="false"
        custom-class="custom-class"
        :before-close="closeMenuAuthorizationDialog">
        <MenuAuthorizationDialog :menu-id-list="menuIdList" :org-id="orgId" authority-type="2" v-if="menuAuthorizationFlag" />
        <div class="dialog-footer">
            <el-button @click="closeMenuAuthorizationDialog">{{
                $t("cs.common.button.cancel")
            }}</el-button>
            <el-button type="primary" @click="submitMenuAuthorizationDialog">{{
                $t("cs.common.button.ok")
            }}</el-button>
        </div>
    </el-drawer>
  </div>
</template>
<script scoped>
import  CoreAPI from "../../../Common/JS/CoreAPI";
import DataAuthorizationDialog from "../../../BusinessCommon/Components/DataAuthorizationDialog.vue";
import MenuAuthorizationDialog from "../../../BusinessCommon/Components/MenuAuthorizationDialog.vue";
import CSTable from "../../../BusinessCommon/Components/CSTable.vue";
export default {
    name: "UserAuthorizationTable",
    components: { DataAuthorizationDialog, MenuAuthorizationDialog, CSTable },
    props: {
        
    },
    data() {
        return {
            activeName: 'second',
            loadTree: false,
            dataAuthorizationFlag: false,
            menuAuthorizationFlag: false,
            dataAuthorizationDialogTitle: "cs.authorityManage.authorization.dataAuthorization",
            menuAuthorizationDialogTitle: "cs.authorityManage.authorization.menuAuthorization",
            authorityDataCategoryList: [],
            menuIdList: [],
            tableData: [],
            
            tableConfig: {
                operationArea: {
                    buttonList: [
                        {
                            prop: "cs.authorityManage.authorization.batchMenuAuthorization", // 按钮名称
                            disabled: true, // 是否禁用
                            clickFunc: this.showBatchMenuAuthorizationDialog // 点击事件
                        }
                    ]
                },
                queryConditionArea: {
                    queryList: [
                        {
                            type: "select",
                            selectOptions: [
                                {
                                    // 字段名下拉框类型 选项 如果type是select类型  必传
                                    label: "cs.authorityManage.authorization.organizationName",
                                    value: "orgName",
                                    searchValueType: "input" // 当前选项对应的查询值类型 暂只支持 input date select
                                },
                                {
                                    // 字段名下拉框类型 选项 如果type是select类型  必传
                                    label: "cs.authorityManage.authorization.abbreviation",
                                    value: "shortName",
                                    searchValueType: "input" // 当前选项对应的查询值类型 暂只支持 input date select
                                }
                            ],
                            filtersValue: "",
                            queryConditionAreaSelectValue: ""
                        }
                    ],
                    searchFunc: this.listSearch // 查询按钮调用方法
                },
                // 列配置
                tableContentArea: {
                    sortChange: this.sortChange,
                    columns: [
                        // 文本形式
                        {
                            label: "cs.authorityManage.authorization.organizationName",
                            prop: "orgName",
                            showOverflowTooltip: true,
                            isChineseSort: true,
                            sortable: 'custom'

                        },
                        {
                            label: "cs.authorityManage.authorization.abbreviation",
                            prop: "shortName",
                            showOverflowTooltip: true,
                            isChineseSort: true,
                            sortable: 'custom'
                        },
                        {
                            label: "cs.authorityManage.authorization.menuAuthorization",
                            type: "link",
                            iconName: "el-icon-key",
                            width: 180,
                            minWidth: 180,
                            align: "left",
                            linkList: [
                                {
                                    linkName: "cs.authorityManage.authorization.unauthorized,cs.authorityManage.authorization.authorized", // 链接名称  对应数据的属性名称
                                    color: "#303133,#1890ff",
                                    prop: "isMenuAuthority",
                                    clickFunc: this.showMenuAuthorizationDialog
                                }
                            ],
                            underline: false
                        }
                    ],
                    needTip: true,
                    needSelection: true, // 选填  是否需要显示列表多选
                    handleSelectionChange: this.handleSelectionChange // 当选择项发生变化时会触发该事件 返回参数: 选中的行
                },
                // 无限滚动加载      ps:无限滚动加载和分页区域  选其一就行
                infiniteScrollLoadData: this.infiniteScrollLoadData, // 选填 无限滚动 加载数据方法
                infiniteScrollLoadDataDisable: false, // 选填 无限滚动加载是否禁用
                // 整行焦点离开
                leaveCurrentRowFunc: this.codeTableBlur,
                isNeewCancelStopPropagation: true
            },
            infiniteScrollLoadDataIndex: 0,
            infiniteScrollLoadDataAntiShake: true,
            multipleSelection: [],
            sortModelList: []
        };
    },
    methods: {
        handleClick(tab, event) {
            console.log(tab, event);
        },
        showDialog() {
            console.log("1")
        },
        getTableData() {
            let _this = this;
           
            CoreAPI.getSystemApiData(postData).then((result) => {
                console.log(JSON.parse(result).obj)
                let res = JSON.parse(result).obj
                let code = JSON.parse(result).code
                if(code == '429') return _this.$alert(_this.$t("cs.common.errorCode.429"), _this.$t("cs.common.text.tips"), {
                    confirmButtonText: _this.$t("cs.common.button.ok"),
                    type: 'warning',
                    callback: action => {}
                });
                res.forEach(element => {
                    element.cus
                });
            }).catch((err) => {
                console.log(err)
            });
        },
        infiniteScrollLoadData() {
            let _this = this;
            if (_this.infiniteScrollLoadDataAntiShake) {
                _this.infiniteScrollLoadDataAntiShake = false;
                _this.getAuthorizeRoleList(true);
            }
        },
        getAuthorizeRoleList(isInfinite) {
            let _this = this;
            let postData = {
                "systemId":  CloudServiceCommon.Props.systemId,
                "code": 'authority_org_list',
                "param": {
                    "paging": {
                        "page_index": _this.infiniteScrollLoadDataIndex,
                        "page_size": 30
                    },
                    "sortModelList": _this.sortModelList,
                    // "sortModelList": [
                    //     {
                    //         "fieldName": "userName",
                    //         "sortType": 0,
                    //         "chineseSort": true
                    //     },
                    //     {
                    //         "fieldName": "loginName",
                    //         "sortType": 0,
                    //         "chineseSort": true
                    //     }
                    // ],
                    "query": null
                    // "query": {
                    //     "query_name": "userName",
                    //     "query_value": "",
                    //     "operation_type": "LIKE"
                    // }
                }
            }
            if(_this.searchValue) {
                postData.param.query = _this.searchValue
            }
            CoreAPI.getSystemApiData(postData).then((result) => {
                    console.log(JSON.parse(result).obj)
                    let res = JSON.parse(result).obj
                    let code = JSON.parse(result).code
                    if(code == '429') return _this.$alert(_this.$t("cs.common.errorCode.429"), _this.$t("cs.common.text.tips"), {
                        confirmButtonText: _this.$t("cs.common.button.ok"),
                        type: 'warning',
                        callback: action => {}
                    });
                    _this.infiniteScrollLoadDataAntiShake = true;
                    if (res.length < 30) {
                        _this.tableConfig.infiniteScrollLoadDataDisable = true;
                    }
                    if (res.length < 1 && _this.infiniteScrollLoadDataIndex == 0) {
                        return (_this.tableData = []);
                    }
                    _this.infiniteScrollLoadDataIndex++;
                    for (let i = 0; i < res.length; i++) {
                        res[i].customRowConfigData = {};
                        if (isInfinite) {
                        _this.tableData.push(res[i]);
                        }
                    }
                    if (!isInfinite) {
                        _this.tableData = res;
                    }
                    CloudServiceCommon.Methods.selectTableCheckBoxService({
                        // 选中的数据
                        oldSelectList: _this.multipleSelection,
                        // 最新的tableData
                        newData: _this.tableData,
                        // 行数据唯一id的属性名称
                        targetId: 'orgId',
                        // 列表配置
                        tableConfig: _this.tableConfig
                    })
                },
                function (error) {
                    _this.infiniteScrollLoadDataAntiShake = true;
                    _this.$message.error(error.msg);
                }
            );
        },
        //首选项多选列表 this.tableData
        handleSelectionChange(val) {
            let _this = this;
            if (val.length == 0) {
                this.tableConfig.operationArea.buttonList[0].disabled = true;
                this.tableConfig.operationArea.buttonList[1] ? this.tableConfig.operationArea.buttonList[1].disabled = true : ''

            } else {
                this.tableConfig.operationArea.buttonList[0].disabled = false;
                this.tableConfig.operationArea.buttonList[1] ? this.tableConfig.operationArea.buttonList[1].disabled = false : ''

            }
            CloudServiceCommon.Methods.findSelectTableNotChooseList({
                // 选中的数据
                oldSelectList: val,
                // tableData 最新的数据
                newData: _this.tableData,
                // 行数据唯一id的属性名称
                targetId: 'orgId',
                // 列表配置
                tableConfig: _this.tableConfig,
                allSelectList: _this.multipleSelection
            })
            if(_this.tableConfig.tableContentArea.isChooseAllSelect && !_this.searchValue) {
                CoreAPI.getSystemApiData({
                    "systemId":  CloudServiceCommon.Props.systemId,
                    "code": 'get_all_organization_ids',
                    "param": {}
                }).then(function(res){
                    let resault = JSON.parse(res).obj
                    let code = JSON.parse(res).code
                    if(code == '429') return _this.$alert(_this.$t("cs.common.errorCode.429"), _this.$t("cs.common.text.tips"), {
                        confirmButtonText: _this.$t("cs.common.button.ok"),
                        type: 'warning',
                        callback: action => {}
                    });
                    _this.allIdList = resault
                    let notChooseNum = _this.tableConfig.tableContentArea.selectionNotChooseList.length
                    _this.tableConfig.tableContentArea.allDataNum = resault.length - notChooseNum
                    _this.$refs.csTable.refreshTableTip()
                })
            }else if(_this.tableConfig.tableContentArea.isChooseAllSelect && _this.searchValue){
                let postData = {
                    "systemId":  CloudServiceCommon.Props.systemId,
                    "code": 'authority_org_list',
                    "param": {
                        "query": _this.searchValue
                    }
                }
                CoreAPI.getSystemApiData(postData).then((result) => {
                    let res = JSON.parse(result).obj
                    let code = JSON.parse(result).code
                    if(code == '429') return _this.$alert(_this.$t("cs.common.errorCode.429"), _this.$t("cs.common.text.tips"), {
                        confirmButtonText: _this.$t("cs.common.button.ok"),
                        type: 'warning',
                        callback: action => {}
                    });
                    _this.allIdList = []
                    if(res && res.length) {
                        res.forEach(function(target) {
                            _this.allIdList.push(target.userId)
                        })
                    }
                    let notChooseNum = _this.tableConfig.tableContentArea.selectionNotChooseList.length
                    _this.tableConfig.tableContentArea.allDataNum = res.length - notChooseNum
                    _this.$refs.csTable.refreshTableTip()
                })
            }else{
                _this.tableConfig.tableContentArea.allDataNum = val.length == 0 ? val.length : _this.multipleSelection.length
                _this.$refs.csTable.refreshTableTip()
            }
        },
        sortChange(val) {
            let _this = this;
            _this.sortModelList = val;
            _this.sortModelListHasChange = true;
            if (_this.sortModelList.length < 1) {
                _this.sortModelList = []
                _this.sortModelListHasChange = false;
            }
            _this.infiniteScrollLoadDataIndex = 0
            _this.tableConfig.infiniteScrollLoadDataDisable = false;
            _this.infiniteScrollLoadDataAntiShake = false;
            _this.getAuthorizeRoleList(false)
        },
        //查询
        listSearch(searchValue) {
            // _this.getExcelTemplates(res,true)
            let _this = this;
            if (searchValue.filterGroupModel[0].filterFields.length) {
                searchValue.filterGroupModel[0].filterFields.forEach(item => {
                    _this.searchValue = {
                        "query_name": item.fieldName,
                        "query_value": item.fieldValue,
                        "operation_type": "LIKE"
                    }
                        
                })
            // 查询返回的过滤模型如果为空则初始化过滤模型字段
            } else if (!searchValue.filterGroupModel[0].filterFields.length && _this.searchValue){
                // _this.filterModel.filterGroupModel[0].filterFields = [_this.filterModel.filterGroupModel[0].filterFields[0]]
                _this.searchValue = null
            }
            _this.infiniteScrollLoadDataIndex = 0;
            _this.tableConfig.infiniteScrollLoadDataDisable = false;
            _this.infiniteScrollLoadDataAntiShake = false;
            _this.multipleSelection = []
            _this.getAuthorizeRoleList(false)
            this.tableConfig.tableContentArea.isChooseAllSelect = false;
            this.tableConfig.tableContentArea.selectionNotChooseList = [];
            this.multipleSelection = [];
        },
        showMenuAuthorizationDialog(row) {
            let _this = this;
            console.log(row)
            _this.isBatch = 1;
            _this.orgIdList = [row.orgId]
            _this.orgId = row.orgId
            _this.menuIdList = [];
            _this.menuAuthorizationFlag = true;
        },
        showBatchMenuAuthorizationDialog() {
            let _this = this;
            _this.isBatch = 0;
            _this.menuIdList = [];
            _this.orgId = '0';
            _this.orgIdList = []
            if(_this.tableConfig.tableContentArea.isChooseAllSelect) {
                let nowAllIds = JSON.parse(JSON.stringify(_this.allIdList))
                if(_this.tableConfig.tableContentArea.selectionNotChooseList && _this.tableConfig.tableContentArea.selectionNotChooseList.length) {
                    _this.tableConfig.tableContentArea.selectionNotChooseList.forEach(function(item) {
                        nowAllIds.indexOf(item) != '-1' ? nowAllIds.splice(nowAllIds.indexOf(item), 1) : ''
                    })
                }
                _this.orgIdList = nowAllIds
            }else{
                _this.multipleSelection.forEach(function(item) {
                    _this.orgIdList.push(item.orgId)
                })
            }
            _this.menuAuthorizationFlag = true;
        },
        dataAuthorizationFunc(row) {
            let _this = this;
            console.log(row)
            _this.isBatch = 1;
            _this.orgIdList = [row.orgId]
            _this.orgId = row.orgId
            _this.authorityDataCategoryList = [];
            _this.dataAuthorizationFlag = true;
        },
        showBatchDataAuthorizationDialog(row) {
            let _this = this;
            _this.isBatch = 0;
            _this.authorityDataCategoryList = [];
            _this.orgId = '0';
            _this.orgIdList = []
            _this.multipleSelection.forEach(function(item) {
                _this.orgIdList.push(item.orgId)
            })
            _this.dataAuthorizationFlag = true;
        },
        closeDataAuthorizationDialog(){
            let _this = this;
            _this.dataAuthorizationFlag = false;  
        },
        closeMenuAuthorizationDialog(){
            let _this = this;
            _this.menuAuthorizationFlag = false;  
        },
        submitDataAuthorizationDialog(){
            let _this = this;
            // 判断数据授权返回的数据是不是空权限
            _this.authorityDataCategoryList.forEach(function(target) {
                if(target.dataAuthorityItemList && target.dataAuthorityItemList.length) {
                    let hasAuthorize = false;
                    target.dataAuthorityItemList.forEach(function(item){
                        if(item.funcCodeList.length) {
                            hasAuthorize = true
                        }
                    })
                    !hasAuthorize ? target.dataAuthorityItemList = [] : ''
                }
            })
            let postData = {
                "systemId": CloudServiceCommon.Props.systemId,
                "authorityType": 2,
                "isBatch": _this.isBatch,
                "authorityDataCategoryList": _this.authorityDataCategoryList,
                "roleIdList": [],
                "userIdList": [],
                "orgIdList": _this.orgIdList,
                "userIdRecord": CloudServiceCommon.User.userId,
                "orgIdRecord": CloudServiceCommon.User.organizationId
            }
            CoreAPI.saveDataAuthority(postData).then(function(res) {
                _this.infiniteScrollLoadDataIndex = 0;
                _this.tableConfig.infiniteScrollLoadDataDisable = false;
                _this.infiniteScrollLoadDataAntiShake = false;
                _this.getAuthorizeRoleList(false);
                _this.dataAuthorizationFlag = false;  
            })
        },
        submitMenuAuthorizationDialog(){
            let _this = this;
            let postData = {
                "systemId": CloudServiceCommon.Props.systemId,
                "authorityType": 2,
                "isBatch": _this.isBatch,
                "authItemIdList": _this.menuIdList,
                "roleIdList": [],
                "userIdList": [],
                "orgIdList": _this.orgIdList,
                "userIdRecord": CloudServiceCommon.User.userId,
                "orgIdRecord": CloudServiceCommon.User.organizationId
            }
            CoreAPI.saveAuthority(postData).then(function(res) {
                // if(_this.menuIdList.length > 0) {
                    // !_this.isBatch ? console.log('批量') : console.log(‘单个’)
                    _this.infiniteScrollLoadDataIndex = 0;
                    _this.tableConfig.infiniteScrollLoadDataDisable = false;
                    _this.infiniteScrollLoadDataAntiShake = false;
                    _this.getAuthorizeRoleList(false);
                // }
                _this.menuAuthorizationFlag = false;  
            })
        },
        getAuthorityDataCategoryBySystemId: function() {
            let _this = this;
            CoreAPI.getAuthorityDataCategoryBySystemId(CloudServiceCommon.Props.systemId).then(function (res) {
                if(res && res.length) {
                    _this.tableConfig.tableContentArea.columns.push(
                        {
                            label: "cs.authorityManage.authorization.dataAuthorization",
                            type: "link",
                            iconName: "el-icon-key",
                            width: 180,
                            minWidth: 180,
                            align: "left",
                            linkList: [
                                {
                                    linkName: "cs.authorityManage.authorization.unauthorized,cs.authorityManage.authorization.authorized", // 链接名称  对应数据的属性名称
                                    color: "#303133,#1890ff",
                                    prop: "isDataAuthority",
                                    clickFunc: _this.dataAuthorizationFunc
                                }
                            ],
                            underline: false
                        }
                    )
                    _this.tableConfig.operationArea.buttonList.push({
                        prop: "cs.authorityManage.authorization.batchDataAuthorization", // 按钮名称
                        disabled: true, // 是否禁用
                        clickFunc: _this.showBatchDataAuthorizationDialog // 点击事件
                    })
                }
                _this.loadTree = true;
            }).catch(err => {
                _this.loadTree = true;
                if (err.code) {
                    this.$message.error(
                        this.$t(`cs.common.errorCode.${err.code}`).indexOf(err.code) == -1 ? this.$t(`cs.common.errorCode.${err.code}`) : err.msg
                    );
                }
                CloudServiceCommon.Log.debug(err);
            });
        }
    },
    created(){
        let _this = this;
        _this.getAuthorityDataCategoryBySystemId();
    }       
};
</script>
<style lang="less" scoped>
.department-authorization {
  /deep/.custom-class { 
    .el-drawer__body {
      padding: 0 25px;
    }
    .dialog-footer {
      margin-bottom: -32px;
      padding: 20px 32px;
      width: 100%;
      box-sizing: border-box;
      padding: 10px 20px 20px;
      text-align: right;
      padding-right: 0;
    }
  }
  /deep/.el-drawer__header {
    padding: 20px 24px 0;
    height: 64px;
    margin-bottom: 12px;
    padding-top: 0;
  }
  /deep/.el-drawer__header>:first-child {
    color: #303133;
    font-size: 18px;
  }
  /deep/.el-tree--highlight-current div.el-tree-node.is-current>.el-tree-node__content {
    color: #606266;
  }
}
</style>
