<!--
     机构配额详情
    @Author:laiyh
    @Date:  2020-08-03
-->
<template>
    <div class="authen-main main-content">
        <!--操作内容导航end-->
        <dg-row :gutter="10">
            <!--角色列表-->
            <dg-col :span="12">
                <dg-card shadow="never" header="角色列表">
                    <el-form ref="roleForm" :model="roleForm" label-suffix=":" inline>
                        <el-form-item label="角色名称" prop="name.value">
                            <el-input
                                v-model="roleForm.name.value"
                                clearable
                                style="width: 140px;"
                                placeholder="请输入角色名称"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="角色层级">
                            <dg-select
                                v-model="roleForm.roleLevel.value"
                                filterable
                                clearable
                                style="width: 140px;"
                                code="DM_ROLE_LEVEL"
                                placeholder="请选择角色层级"
                            ></dg-select>
                        </el-form-item>
                        <el-form-item>
                            <dg-button type="primary" icon="el-icon-search" @click="handleSearch">查询</dg-button>
                        </el-form-item>
                    </el-form>
                    <Table
                        ref="myRoleTable"
                        :url="r_tableurl"
                        :headerData="r_title_data"
                        :condition="roleForm"
                        :lazyLoad="true"
                        @handleRowClick="handleRowClick"
                    ></Table>
                </dg-card>
            </dg-col>
            <!--角色列表end-->
            <!--机构列表-->
            <dg-col :span="12">
                <dg-card shadow="never" header="机构列表信息">
                    <div class="org-operation-buttons">
                        <dg-button type="primary" icon="el-icon-bottom" @click="handleQuatoDistation"
                            >配额下发</dg-button
                        >
                        <dg-button type="primary" icon="el-icon-document-checked" @click="handleSave">保存</dg-button>
                    </div>
                    <div class="org-pe-tips">
                        <div class="quotaOrgTreeDiv yfpTitle"></div>
                        <span class="fpTitle">已分配名额</span>
                        <span class="fhTitle">+</span>
                        <div class="quotaOrgTreeDiv yxfTitle"></div>
                        <span class="fpTitle">已下发名额</span>
                        <span class="fhTitle">+</span>
                        <div class="quotaOrgTreeDiv kxTitle"></div>
                        <span class="fpTitle">空闲名额</span>
                        <span class="fhTitle">=</span>
                        <span class="fpTitle">总配额</span>
                    </div>
                    <div style="text-align: right;padding-right:10px;padding-top:10px;">
                        <dg-button type="primary" icon="el-icon-top" @click="handleRecovery">收回配额</dg-button>
                    </div>
                    <dg-table
                        ref="tableTree"
                        :data="tableData1"
                        :pagination="false"
                        style="width: 100%"
                        row-key="id"
                        lazy
                        :load="load"
                        :tree-props="treeProps"
                        class="my-org-table"
                        highlight-current-row
                        @row-click="handleOrgTreeRow"
                    >
                        <dg-table-column prop="name" label="单位名称" width="180"></dg-table-column>
                        <dg-table-column label="配额分配" align="right">
                            <template slot-scope="{ row, $index }">
                                <div class="pe_div">
                                    <div class="yfp_div">
                                        <span class="quotaOrgTreeSpan">{{ row.bjNum }}</span>
                                    </div>
                                    <div class="yxf_div">
                                        <span class="quotaOrgTreeSpan">{{ row.yxfNum }}</span>
                                    </div>
                                    <div class="kx_div">
                                        <span class="quotaOrgTreeSpan">{{ row.dfpNum }}</span>
                                    </div>
                                    <div class="js_div">
                                        <span class="only_number" v-if="$index == 0">{{
                                            row.bjNum + row.yxfNum + row.dfpNum
                                        }}</span>
                                        <el-input-number
                                            controls-position="right"
                                            size="mini"
                                            :min="0"
                                            v-if="$index !== 0"
                                            v-model="row.initNum"
                                            @change="changeInitNum(row)"
                                        ></el-input-number>
                                    </div>
                                </div>
                            </template>
                        </dg-table-column>
                    </dg-table>
                </dg-card>
            </dg-col>
            <!--机构列表end-->
        </dg-row>
    </div>
</template>

<script>
import Table from "@/components/table";
import { mapGetters } from "vuex";
import * as roleManageApi from "@/api/roleinfo-manage";
import * as commonApi from "@/api/common";
import * as empowerApi from "@/api/empower-manage";
import QuatoDis from "./quato-distribution";

export default {
    name: "edit",
    components: {
        Table
    },
    // 接收父页面传过来的属性
    props: {
        row: {
            // id应用id  appOrgId 机构id
            type: Object,
            default: () => {}
        }
    },
    // 页面数据绑定
    data() {
        return {
            // 角色列表
            r_tableurl: roleManageApi.orgQuoRoleTable,
            r_title_data: [
                { label: "角色名称", prop: "name" },
                { label: "角色层级", prop: "roleLevel", code: "DM_ROLE_LEVEL" },
                { label: "警种", prop: "policeCategory", code: "T_MD_POLICE_TYPE" },
                { label: "总配额", prop: "totalQuotas" }
            ],
            roleForm: {
                applicationId: { value: "", op: "=" }, //应用id
                name: { value: "", op: "like" }, //角色名称
                roleLevel: { value: "", op: "=" } //角色等级
            },
            // 机构列表
            treeProps: {
                label: "name",
                hasChildren: "hasChildren",
                children: "children",
                isLeaf(data) {
                    return !data.parent || !data.isParent;
                }
            },
            tableData1: [],
            targetOrgId: [],
            tableDataCopy: [],
            orgQuotaList: [],

            treeFirst: null,

            // 1.手动分配 2.懒加载树  3.树部分节点更新
            NoautoAuth: [],
            //角色、部门、空闲名额
            self_click_map: {
                roleName: "", //角色名称
                roleId: "", //角色id
                orgName: "", // 单位名称
                orgId: "", // 机构id
                freeNumber: "" //空闲配额
            },
            sizeForm: {
                addNum: 0,
                appId: "",
                appOrgId: "",
                initNum: 0,
                initNumOld: 0,
                roleId: "",
                roleName: "",
                roleLevel: "",
                rootId: "",
                targetOrgId: "",
                targetOrgName: "",
                targetOrgLevel: "",
                unitClass: "",
                upOrgId: "",
                freeNum: ""
            }
        };
    },
    // 计算属性
    computed: {
        ...mapGetters(["user"])
    },
    // 方法
    methods: {
        handleSearch() {
            this.$refs.myRoleTable.handleSearchClick();
        },
        handleRowClick(clickItem) {
            this.self_click_map.roleName = clickItem.row.name; // 已选角色
            this.self_click_map.roleId = clickItem.row.id;
            this.self_click_map.orgName = ""; // 已选机构
            this.self_click_map.orgId = "";

            // 机构配额
            this.getOrgQuotas();
            // 清空机构配额数组
            this.orgQuotaList = [];
            // 清空用户手动配额
            this.NoautoAuth = [];

            // 批量配额变量赋值

            this.sizeForm.roleId = clickItem.row.id;
            this.sizeForm.roleName = clickItem.row.name;
            this.sizeForm.roleLevel = clickItem.row.roleLevel;
        },
        handleOrgTreeRow(row, column, event) {
            this.self_click_map.orgName = row.name; //已选机构
            this.self_click_map.orgId = row.id || this.treeFirst;

            // 配额批量下发变量赋值
            // debugger;
            this.sizeForm.targetOrgName = row.name;
            this.sizeForm.targetOrgId = row.id || this.treeFirst;
            this.sizeForm.upOrgId = row.pid;
            this.sizeForm.initNum = row.initNum;
            this.sizeForm.initNumOld = row.initNumOld;

            let flag = this.tableData1.some(item => {
                return item.id == row.id;
            });
            if (this.self_click_map.roleId) {
                if (flag) {
                    this.self_click_map.freeNumber = "无限";

                    this.sizeForm.freeNum = "无限";
                } else {
                    this.self_click_map.freeNumber = row.dfpNum || 0;
                    this.sizeForm.freeNum = row.dfpNum || 0;
                }
            }
        },
        // 懒加载机构列表
        load({ id, isParent, parent }, treeNode, resolve) {
            const that = this;
            let arr = [];
            // debugger;

            commonApi.getTree({ id: id || that.treeFirst }).then(res => {
                // push机构id
                res.forEach(returnHelper => {
                    that.targetOrgId.push(returnHelper.id);
                });
                arr = res.map(item => {
                    item.bjNum = 0;
                    item.yxfNum = 0;
                    item.dfpNum = 0;
                    item.initNum = 0;
                    item.initNumOld = 0;
                    if (item.isParent) {
                        item.hasChildren = true;
                    }
                    return item;
                });
                // TODO 深拷贝 不改变原来数组 数组内基本数据类型 深拷贝。 引用数据类型浅拷贝
                that.tableDataCopy = that.tableDataCopy.concat(arr);

                resolve(arr);

                if (that.self_click_map.roleId !== "") {
                    that.getOrgQuotas();
                }
            });
        },
        // 获取指定机构的配额信息
        getOrgQuotas() {
            const that = this;
            const targetOrgId = that.targetOrgId.join(",") || "";

            // 清空上一次配置信息
            for (let i = 0; i < that.tableDataCopy.length; i++) {
                that.tableDataCopy[i].bjNum = 0;
                that.tableDataCopy[i].yxfNum = 0;
                that.tableDataCopy[i].dfpNum = 0;
                that.tableDataCopy[i].initNum = 0;
                that.tableDataCopy[i].initNumOld = 0;
            }

            empowerApi
                .getOrgQuotaInfos({
                    appId: that.row.id,
                    roleId: that.self_click_map.roleId,
                    targetOrgId: targetOrgId
                })
                .then(res => {
                    for (let i = 0; i < res.length; i++) {
                        if (that.NoautoAuth.indexOf(res[i].targetOrgId) > -1) {
                            continue;
                        } else {
                            for (let j = 0; j < that.tableDataCopy.length; j++) {
                                // debugger;
                                if (res[i].targetOrgId == that.tableDataCopy[j].id) {
                                    that.tableDataCopy[j].bjNum = res[i].bjNum;
                                    that.tableDataCopy[j].yxfNum = res[i].yxfNum;
                                    that.tableDataCopy[j].dfpNum = res[i].dfpNum;
                                    that.tableDataCopy[j].initNum = res[i].bjNum + res[i].yxfNum + res[i].dfpNum;
                                    that.tableDataCopy[j].initNumOld = res[i].bjNum + res[i].yxfNum + res[i].dfpNum;
                                    break;
                                }
                            }
                        }
                    }
                })
                .catch(err => {
                    that.$message.error("机构配额获取失败！");
                });
        },
        changeInitNum(orgrow) {
            const that = this;
            // 记录手动配额
            if (that.NoautoAuth.indexOf(orgrow.id) == -1) {
                that.NoautoAuth.push(orgrow.id);
            }

            let selectObject = {
                appId: that.row.id,
                upOrgId: orgrow.pid, // 上级id
                appOrgId: that.row.appOrgId, // 应用关联的机构id
                roleId: that.self_click_map.roleId, // 角色id
                targetOrgId: orgrow.id, // 目标id
                bjNum: orgrow.bjNum, //已分配/
                yxfNum: orgrow.yxfNum, // 已下发
                dfpNum: orgrow.dfpNum, //带分配
                initNumOld: orgrow.initNumOld, //久值
                initNum: orgrow.initNum, //新值
                name: orgrow.name
            };
            // 如果改变
            if (selectObject.initNumOld !== selectObject.initNum) {
                for (let i = 0; i < that.orgQuotaList.length; i++) {
                    if (that.orgQuotaList[i].targetOrgId === selectObject.targetOrgId) {
                        that.orgQuotaList.splice(i, 1);
                        break;
                    }
                }
                that.orgQuotaList.push(selectObject);
            } else {
                for (let i = 0; i < that.orgQuotaList.length; i++) {
                    if (that.orgQuotaList[i].targetOrgId === selectObject.targetOrgId) {
                        that.orgQuotaList.splice(i, 1);
                        break;
                    }
                }
            }

            // console.log(that.orgQuotaList);
        },
        // 保存
        handleSave() {
            const that = this;
            const { orgQuotaList } = that;
            if (!that.self_click_map.roleId) {
                that.$message.warning("请选择角色信息");
                return;
            }
            that.$confirm("是否提交此配额信息？", "消息提示", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消"
            }).then(_ => {
                empowerApi
                    .saveOrgQuotas(orgQuotaList)
                    .then(res => {
                        that.$message.success("保存成功");
                        that.$refs.myRoleTable.$refs.grid.reload(); //刷新表格

                        that.NoautoAuth = []; // 用户手动操作数组清空

                        that.orgQuotaList = []; // 清空参数

                        that.getOrgQuotas(); //配额树刷新
                    })
                    .catch(err => {
                        that.$message.error(err);
                    });
            });
        },
        // 配额下发
        handleQuatoDistation() {
            const that = this;
            if (!this.self_click_map.roleName) {
                this.$message.warning("请选择角色！")
                return;
            }
            if (!this.self_click_map.orgName) {
                this.$message.warning("请选择下发机构！")
                return;
            }
            const layer = this.$dgLayer({
                title: "配额下发",
                area: ["990px", "750px"],
                shade: [0.4, "#fff"],
                content: QuatoDis,
                props: {
                    sizeForm: {
                        ...this.sizeForm,
                        appId: this.row.id,
                        appOrgId: this.row.appOrgId,
                        rootId: this.sizeForm.targetOrgId // 自身的id
                    }
                },
                on: {
                    success(bool = false) {
                        layer.close(layer.dialogIndex);
                        if (bool) {
                            that.$refs.myRoleTable.$refs.grid.reload(); //刷新表格
                            that.NoautoAuth = [];
                            that.getOrgQuotas(); //配额树刷新

                            // 清空选择情况
                            that.self_click_map.orgId = "";
                            that.self_click_map.orgName = "";
                            that.self_click_map.freeNumber = "";
                        }
                    }
                }
            });
        },
        // 配额回收
        handleRecovery() {
            const that = this;
            if (!this.self_click_map.roleId) {
                this.$message.warning("请选择角色！")
                return;
            }
            if (!this.self_click_map.orgId) {
                 this.$message.warning("请选择回收机构！")
                return;
            }
            that.$confirm("确定回收配额？", "提示", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消"
            }).then(() => {
                empowerApi
                    .authCancelChild({
                        appId: that.row.id,
                        roleId: that.self_click_map.roleId,
                        targetOrgId: that.self_click_map.orgId
                    })
                    .then(res => {
                        that.$message.success("回收成功！");
                        that.$refs.myRoleTable.$refs.grid.reload(); //刷新表格
                        that.NoautoAuth = [];
                        that.getOrgQuotas(); //配额树刷新
                    })
                    .catch(err => {
                        that.$message.error(err);
                    });
            });
        }
    },
    // 创建组件时调用
    created() {
        // console.log(this.user);
        const that = this;
        const { row } = this;
        const { roleForm } = this;
        if (row.id) {
            this.$set(roleForm.applicationId, "value", row.id);
        }

        this.$nextTick(() => {
            this.handleSearch();
        });

        // 顶级单位名称
        this.treeFirst = row.appOrgId; // 预存

        // 查询机构树
        commonApi
            .getBaseTree({ id: row.appOrgId })
            .then(res => {
                res.bjNum = 0;
                res.yxfNum = 0;
                res.dfpNum = 0;
                res.initNum = 0;
                res.initNumOld = 0;
                if (res.parent == true || res.isParent == true) {
                    res.hasChildren = true;
                }
                res.id = res.id ? res.id : this.treeFirst;
                that.tableData1.push(res);
                that.tableDataCopy = that.tableDataCopy.concat(that.tableData1); // 缓存数据
                that.targetOrgId.push(res.id);
            })
            .catch(err => {
                that.tableData1 = [];
            });
    }
};
</script>

<style scoped lang="scss">
.main-content {
    .select-item-tab-text {
        display: flex;
        height: 30px;
        line-height: 30px;
        padding-left: 10px;
        border-bottom: 1px dashed #a9a9a9;
        font-size: 16px;
        margin-bottom: 10px;
        justify-content: space-between;

        .selected {
            font-weight: bold;
            color: red;
        }
    }

    // 机构列表
    .org-operation-buttons {
        /*position: absolute;*/
        /*top: 10px;*/
        /*right: 30px;*/
        text-align: right;
        padding-right: 10px;
    }

    .org-pe-tips {
        height: 20px;
        border: 1px dashed darkgoldenrod;
        padding: 10px 10px;
        margin: 5px 10px 5px 5px;
    }

    .quotaOrgTreeDiv {
        width: 18px;
        height: 18px;
        float: left;
    }

    .yfpTitle {
        background-color: #949393;
        border: 1px solid #949393;
        margin-left: 10px;
    }

    .fpTitle {
        float: left;
        margin-left: 5px;
    }

    .fhTitle {
        float: left;
        margin-left: 5px;
        font-size: 18px;
        color: deeppink;
        font-weight: bold;
        margin-top: -4px;
    }

    .yxfTitle {
        background-color: darkcyan;
        border: 1px solid darkcyan;
        margin-left: 10px;
    }

    .kxTitle {
        background-color: #2991d9;
        border: 1px solid #2991d9;
        margin-left: 10px;
    }

    .my-org-table {
        .pe_div {
            display: flex;
            justify-content: flex-end;
            align-items: flex-start;
            .yfp_div {
                background-color: #949393;
                width: 60px;
                /*height: 24px;*/
                /*line-height: 24px;*/
                color: #ffffff;
                text-align: center;
                border: 1px solid rgba(140, 139, 139, 0.93);
                /*float: right;*/
                margin-right: 5px;
                span {
                    height: 28px;
                    line-height: 28px !important;
                    /*margin-right: 2px;*/
                }
            }
            .yxf_div {
                background-color: darkcyan;
                width: 60px;
                /*height: 24px;*/
                /*line-height: 24px;*/
                color: #ffffff;
                text-align: center;
                border: 1px solid darkcyan;
                /*float: right;*/
                margin-right: 5px;
                span {
                    height: 28px;
                    line-height: 28px !important;
                    /*margin-right: 2px;*/
                }
            }
            .kx_div {
                background-color: #2991d9;
                width: 60px;
                /*height: 24px;*/
                /*line-height: 24px;*/
                color: #ffffff;
                text-align: center;
                border: 1px solid #2991d9;
                /*float: right;*/
                margin-right: 5px;
                span {
                    height: 28px;
                    line-height: 28px !important;
                    /*margin-right: 2px;*/
                }
            }
            .js_div {
                /*float: right;*/
                .el-input-number--mini {
                    line-height: 28px !important;
                    min-width: 80px;
                    width: 80px;
                    .el-input-number__decrease,
                    .el-input-number__increase {
                        width: 12px;
                        line-height: 28px;
                        height: 28px;
                    }
                }
            }
            .only_number {
                font-weight: bold;
                color: #ff8c00;
                font-size: 17px;
                display: inline-block;
                width: 80px;
                text-align: center;
            }
            .quotaOrgTreeSpan {
                color: white;
                text-align: center;
                width: 100%;
                display: inline-block;
                font-size: 3px;
                height: 22px;
                line-height: 22px !important;
            }
        }
    }
}
</style>
