<template>
    <ap-container>
        <ap-aside margin="1111">
            <div class="layout-aside-header">
                <div class="layout-aside-header-title">组织部门</div>
            </div>
            <div>
                <el-input placeholder="关键字过滤" v-model="treeFilterText"></el-input>
            </div>
            <div class="layout-aside-content" v-loading="loadingTreeFlag">
                <el-tree
                    ref="tSysOrgTree"
                    node-key="fdId"
                    :data="treeData"
                    :props="{children: 'children',label: 'fdName'}"
                    :check-on-click-node="true"
                    :highlight-current="true"
                    :expand-on-click-node="false"
                    :check-strictly="false"
                    :filter-node-method="filterTreeNode"
                    @node-click="clickTreeEvent">
                </el-tree>
            </div>
        </ap-aside>
        <ap-container>
            <ap-header margin="1110">
                <el-form ref="tSysOrgSearchForm" :model="tSysOrgSearchForm" :rules="tSysOrgSearchFormRules"
                         :inline="true" class="layout-header-form" @submit.native.prevent="searchEvent">
                    <el-form-item label="搜索:" class="layout-header-form-item" prop="likeStr">
                        <el-input v-model="tSysOrgSearchForm.likeStr" placeholder="名称/全称/编码"></el-input>
                    </el-form-item>
                    <el-form-item label="生效：" class="layout-header-form-item" prop="fdDisabled">
                        <el-select v-model="tSysOrgSearchForm.fdDisabled" style="width: 80px;">
                            <el-option key="2" label="全部" :value="2"></el-option>
                            <el-option key="0" label="有效" :value="0"></el-option>
                            <el-option key="1" label="失效" :value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-button type="primary" @click="searchEvent" native-type="submit">查询</el-button>
                </el-form>
                <el-button type="primary" @click="resetOrgLevelInfoEvent" style="margin-left: 10px">重置层级</el-button>
                <el-button type="primary" @click="multiEditEvent">批量修改属性</el-button>
            </ap-header>
            <ap-main margin="0110">
                <ap-table ref="tSysOrgRef" :options.sync="tSysOrgOpt"></ap-table>
            </ap-main>

            <el-dialog :title="dialogInfo.title" :visible.sync="dialogInfo.isVisible"
                       @close="resetTSysOrgForm" width="1100px">
                <el-form ref="tSysOrgFormRef" :model="tSysOrgForm" :rules="tSysOrgFormRules"
                         v-loading="dialogInfo.formIsLoading"
                         label-width="100px" :inline="true" class="ap-form">
                    <div class="ap-form-row">
                        <el-form-item label='父部门' prop='fdParentId'>
                            <el-select v-model="tSysOrgForm.fdParentId" placeholder="请选择" clearable filterable>
                                <el-option key="item.value" label="无" value=""></el-option>
                                <el-option v-for="item in parentList" :key="item.fdId" :label="item.fdName"
                                           :value="item.fdId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label='部门ID' prop='fdId'>
                            <el-input v-model='tSysOrgForm.fdId' disabled></el-input>
                        </el-form-item>
                        <el-form-item label='部门层级' prop='fdLevel'>
                            <el-input v-model='tSysOrgForm.fdLevel' disabled></el-input>
                        </el-form-item>
                    </div>

                    <div class="ap-form-row">
                        <el-form-item label='部门名称' prop='fdName'>
                            <el-input v-model='tSysOrgForm.fdName'></el-input>
                        </el-form-item>
                        <el-form-item label='简称' prop='fdShortName'>
                            <el-input v-model='tSysOrgForm.fdShortName'></el-input>
                        </el-form-item>
                        <el-form-item label='英文名' prop='fdEnName'>
                            <el-input v-model='tSysOrgForm.fdEnName'></el-input>
                        </el-form-item>
                        <el-form-item label='全称' prop='fdFullName'>
                            <el-input v-model='tSysOrgForm.fdFullName' disabled></el-input>
                        </el-form-item>
                    </div>
                    <div class="ap-form-row">
                        <el-form-item label='公司别' prop='fdCompanyId'>
                            <el-select v-model="tSysOrgForm.fdCompanyId" placeholder="请选择" clearable filterable>
                                <el-option key="item.value" label="无" value=""></el-option>
                                <el-option v-for="item in companyList" :key="item.value" :label="item.key"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label='部门领导id' prop='fdLeaderId'>
                            <el-input v-model='tSysOrgForm.fdLeaderId'></el-input>
                        </el-form-item>
                        <el-form-item label='上级领导' prop='fdHigherLeader'>
                            <el-input v-model='tSysOrgForm.fdHigherLeader'></el-input>
                        </el-form-item>

                    </div>
                    <div class="ap-form-row">
                        <el-form-item label='编码' prop='fdCode'>
                            <el-input v-model='tSysOrgForm.fdCode'></el-input>
                        </el-form-item>
                        <el-form-item label='属性' prop='fdAttr'>
                            <el-select v-model="tSysOrgForm.fdAttr" placeholder="请选择">
                                <el-option v-for="item in attrList" :key="item.value" :label="item.key"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label='类型' prop='fdType'>
                            <el-select v-model="tSysOrgForm.fdType" placeholder="请选择">
                                <el-option v-for="item in typeList" :key="item.value" :label="item.key"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="ap-form-row">
                        <el-form-item label='编码a' prop='fdThirdCodeA'>
                            <el-input v-model='tSysOrgForm.fdThirdCodeA'></el-input>
                        </el-form-item>
                        <el-form-item label='编码b' prop='fdThirdCodeB'>
                            <el-input v-model='tSysOrgForm.fdThirdCodeB'></el-input>
                        </el-form-item>
                        <el-form-item label='编码c' prop='fdThirdCodeC'>
                            <el-input v-model='tSysOrgForm.fdThirdCodeC'></el-input>
                        </el-form-item>
                        <el-form-item label='编码d' prop='fdThirdCodeD'>
                            <el-input v-model='tSysOrgForm.fdThirdCodeD'></el-input>
                        </el-form-item>
                    </div>

                    <div class="ap-form-row">
                        <el-form-item label='标识a' prop='fdFlagA'>
                            <el-select v-model="tSysOrgForm.fdFlagA" placeholder="请选择">
                                <el-option v-for="item in flagAList" :key="item.value" :label="item.key"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label='标识b' prop='fdFlagB'>
                            <el-select v-model="tSysOrgForm.fdFlagB" placeholder="请选择">
                                <el-option v-for="item in flagBList" :key="item.value" :label="item.key"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label='标识c' prop='fdFlagC'>
                            <el-select v-model="tSysOrgForm.fdFlagC" placeholder="请选择">
                                <el-option v-for="item in flagCList" :key="item.value" :label="item.key"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label='标识d' prop='fdFlagD'>
                            <el-select v-model="tSysOrgForm.fdFlagD" placeholder="请选择">
                                <el-option v-for="item in flagDList" :key="item.value" :label="item.key"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>

                    <el-form-item label='排序' prop='fdSort'>
                        <el-input-number v-model="tSysOrgForm.fdSort" :min="1"></el-input-number>
                    </el-form-item>
                    <el-form-item label='备注' prop='fdComment'>
                        <el-input v-model='tSysOrgForm.fdComment'></el-input>
                    </el-form-item>
                    <el-form-item label='是否有效' prop='fdDisabled'>
                        <el-radio-group v-model="tSysOrgForm.fdDisabled">
                            <el-radio :label="0">有效</el-radio>
                            <el-radio :label="1">失效</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>

                <span slot="footer">
                <el-button @click="dialogInfo.isVisible = false">取 消</el-button>
                <el-button v-if="hasEditPermission()" type="primary" @click="saveTSysOrgForm"
                           :loading="dialogInfo.saveBtnIsLoading">确 定</el-button>
                <el-button v-else type="warning" >无编辑同步部门权限</el-button>
            </span>
            </el-dialog>

            <el-dialog title="部门批量编辑" :visible.sync="multiEditVisible" width="1100px">
                <el-form ref="multiEditFormRef" :model="multiEditForm"
                         label-width="100px" >
                    <el-form-item label='已选择部门' style="width: 800px">
                        <span v-for="name in multiSelectName" class="ap-tag" style="margin-right: 5px;">
                            {{name}}
                        </span>
                    </el-form-item>
                    <el-form-item label='属性' prop='fdAttr'>
                        <el-select v-model="multiEditForm.fdAttr" placeholder="请选择">
                            <el-option v-for="item in attrList" :key="item.value" :label="item.key"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>

                <span slot="footer">
                    <el-button @click="multiEditVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveMultiEditForm">确 定</el-button>
                </span>
            </el-dialog>
        </ap-container>
    </ap-container>
</template>

<script>
import {convertToTreeData, getTreeChildrenIdsById} from "ap-util/util/DataUtil";
import {hasPermission} from 'ap-util/util/LoginUserUtil'
export default {
    name: 'SysOrg',
    data() {
        let columns = [
            {
                prop: 'fdName',
                label: '部门名称',
                width: 120,
                type: 'input'
            }, {
                prop: 'fdCompanyId',
                label: '公司别',
                width: 70,
                type: 'select',
                selectOptionsKey: {label: "key", value: "value"},
                selectOptionsRemote: 'companyList',
            }, {
                prop: 'fdLevel',
                label: '层级',
                width: 50,
                align: "center",
                type: 'input',
            }, {
                prop: 'fdFullName',
                label: '全称',
                type: 'input',
                width: 300
            }, {
                prop: 'fdCode',
                label: '编码',
                width: 100,
                type: 'input'
            }, {
                prop: 'fdAttr',
                label: '属性',
                width: 50,
                type: 'select',
                selectOptionsKey: {label: "key", value: "value"},
                selectOptionsRemote: 'attrList'
            }, {
                prop: 'fdType',
                label: '类型',
                width: 50,
                type: 'select',
                selectOptionsKey: {label: "key", value: "value"},
                selectOptionsRemote: 'typeList'
            }, {
                prop: 'fdSourceId',
                label: '来源',
                type: 'input',
                width: 50,
                align: "center",
                html: function (value, row) {
                    if (value == null || value == "") {
                        return '<div class="ap-color-yellow">手动</div>'
                    } else {
                        return '<div class="ap-color-green">同步</div>'
                    }
                }
            }, {
                prop: 'fdSort',
                label: '排序',
                width: 40,
                align: "center",
                type: 'input'
            }, {
                prop: 'fdComment',
                label: '备注',
                type: 'input'
            }, {
                prop: 'fdDisabled',
                label: '是否有效',
                type: 'input',
                align: "center",
                width: 80,
                html: function (value, row) {
                    if (value == 1) {
                        return '<div class="ap-tag-danger">失效</div>'
                    } else if (value == 0) {
                        return '<div class="ap-tag-success">有效</el-tag>';
                    }
                }
            },
        ];
        let toolbarBtn = [
            {type: "add", onClick: this.openAddDialog},
            {type: "edit", onClick: this.openEditDialog},
            "del", "refresh", "save"
        ];
        let tableOpt = {
            title: "组织部门表",
            columns: columns,
            dataUrl: "/apm/sys/org/getTSysOrgGridList",
            deletePk: "fdId", // 默认fdId
            deleteUrl: "/apm/sys/org/deleteTSysOrgGridData",
            toolbarBtn: toolbarBtn,
            initData: false, // 默认false
            pagination: {pageSizes: [100, 1000, 3000], pageSize: 100},
            rowParentKey: "fdParentId",
            defaultExpandAll: true,
            indexWidth: 120,
            indexAlign: "left",
            showIndex: true,
            showSelection: true,
            beforeDelete: () => {
                if (!this.hasEditPermission()) {
                    this.$message.error("删除失败！没有删除同步部门的权限")
                    return false;
                }
                return true;
            },
            params: () => {
                return {
                    hierarchy: this.hierarchy,
                    likeStr: this.tSysOrgSearchForm.likeStr,
                    fdDisabled: this.tSysOrgSearchForm.fdDisabled,
                }
            },
            selectionChangeEvent: (selection) => {
                let lastSelectedRow = {};
                if (selection.length > 0) {
                    lastSelectedRow = selection[selection.length - 1];
                }
                this.lastSelectedRow = lastSelectedRow;
            },
        };

        let tSysOrgForm = {
            fdId: '',
            fdParentId: '',
            fdCompanyId: '',
            fdName: '',
            fdEnName: '',
            fdShortName: '',
            fdFullName: '',
            fdAttr: '',
            fdLevel: '',
            fdType: '',
            fdCode: '',
            fdThirdCodeA: '',
            fdThirdCodeB: '',
            fdThirdCodeC: '',
            fdThirdCodeD: '',
            fdFlagA: '',
            fdFlagB: '',
            fdFlagC: '',
            fdFlagD: '',
            fdLeaderId: '',
            fdHigherLeader: '',
            fdSort: '',
            fdComment: '',
            fdDisabled: '',
            fdDeleted: 0
        };
        let multiEditForm = {
            fdAttr: '',
        };
        return {
            // ----- 左侧树 -----
            loadingTreeFlag: false,
            treeFilterText: '',
            treeData: [],
            hierarchy: "",
            // ----- 右侧表 -----
            parentList: [],
            companyList: [],
            attrList: [],
            typeList: [],
            flagAList: [],
            flagBList: [],
            flagCList: [],
            flagDList: [],
            lastSelectedRow: {},
            tSysOrgOpt: tableOpt,
            tSysOrgForm: tSysOrgForm,
            multiEditForm: multiEditForm,
            tSysOrgFormRules: {
                fdCompanyId: [
                    {required: true, message: '必填', trigger: 'blur'},
                    {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
                ],
                fdName: [
                    {required: true, message: '必填', trigger: 'blur'},
                    {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                ]
            },
            dialogInfo: {
                title: "",
                isAdd: false,
                isVisible: false,
                saveBtnIsLoading: false,
                formIsLoading: false
            },
            tSysOrgSearchForm: {
                likeStr: "",
                fdDisabled: 0
            },
            tSysOrgSearchFormRules: {

                likeStr: [{min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}]
            },
            multiEditVisible: false,
            multiSelectName: "",
        }
    },
    watch: {
        treeFilterText(val) {
            // 过滤值修改，更新tree
            this.$refs.tSysOrgTree.filter(val);
        },
    },
    created() {
        this.loadTreeData();
        this.initEditInfo();
        this.getMultiEditInfo();
    },
    methods: {
        hasEditPermission() {
            return hasPermission("SYS-ORG-SYNC-EDIT");
        },
        // 左侧树：加载数据
        loadTreeData() {
            this.loadingTreeFlag = true;
            // 加载数据
            this.$request({
                url: '/apm/sys/org/getTSysOrgList',
                method: 'post'
            }).then(response => {
                // 数据格式转换：数组 -> tree
                this.treeData = convertToTreeData(response.data, {
                    idKey: "fdId",
                    parentKey: "fdParentId",
                    childrenKey: "children",
                });
            }).finally(() => {
                this.loadingTreeFlag = false;
            })
        },
        // 左侧树：过滤节点
        filterTreeNode(value, data) {
            if (!value) return true;
            return data.fdName.indexOf(value) !== -1;
        },
        // 左侧树：click事件
        clickTreeEvent(data, node, comp) {
            this.hierarchy = data.fdHierarchy;
            this.tSysOrgOpt.title = `${data.fdFullName}`;
            this.$refs.tSysOrgRef.refresh();
        },
        initEditInfo() {
            this.$request({
                url: '/apm/sys/org/getEditInfo',
                method: 'post',
                data: {}
            }).then(response => {
                this.parentList = response.data.parentList;
                this.companyList = response.data.companyList;
                this.attrList = response.data.attrList;
                this.typeList = response.data.typeList;
                this.flagAList = response.data.flagAList;
                this.flagBList = response.data.flagBList;
                this.flagCList = response.data.flagCList;
                this.flagDList = response.data.flagDList;
            }).finally(() => {
                this.dialogInfo.formIsLoading = false;
            })
        },
        getMultiEditInfo() {
            this.$request({
                url: '/apm/sys/org/getMultiEditInfo',
                method: 'post',
                data: {}
            }).then(response => {
                this.attrList = response.data.attrList;
            })
        },
        // 打开添加dialog
        openAddDialog() {
            this.dialogInfo.isAdd = true;
            this.dialogInfo.title = "添加部门";
            this.dialogInfo.isVisible = true;
            // 默认值
            this.tSysOrgForm.fdParentId = this.lastSelectedRow.fdId;
            this.tSysOrgForm.fdCompanyId = this.lastSelectedRow.fdCompanyId;
            this.tSysOrgForm.fdDisabled = 0;
        },
        // 打开编辑dialog
        openEditDialog() {
            let selectedRows = this.$refs.tSysOrgRef.getSelection();
            if (selectedRows.length < 1) {
                this.$message.error("请选择需要编辑的行！");
                return;
            }
            if (selectedRows.length > 1) {
                this.$message.error("只能选择单行数据进行编辑！");
                return;
            }

            this.dialogInfo.isAdd = false;
            this.dialogInfo.title = "编辑部门";
            this.dialogInfo.isVisible = true;
            this.dialogInfo.formIsLoading = true;
            // 获取单条数据
            this.$request({
                url: '/apm/sys/org/getTSysOrgByFdId',
                method: 'post',
                data: {
                    fdId: selectedRows[0].fdId
                }
            }).then(response => {
                this.tSysOrgForm = response.data;
            }).finally(() => {
                this.dialogInfo.formIsLoading = false;
            })
        },
        // 重置表单
        resetTSysOrgForm() {
            this.$refs.tSysOrgFormRef.resetFields();
        },

        // dialog表单保存
        saveTSysOrgForm() {
            // 表单rules认证
            this.$refs.tSysOrgFormRef.validate((valid) => {
                if (!valid) {
                    this.$message.error('数据校验错误！');
                    return false;
                }
                this.dialogInfo.saveBtnIsLoading = true;

                let fnName = this.dialogInfo.isAdd ? "insertTSysOrg" : "updateTSysOrg";
                // 添加数据
                this.$request({
                    url: '/apm/sys/org/' + fnName,
                    method: 'post',
                    data: this.tSysOrgForm
                }).then(response => {
                    this.$message.success(`保存成功！`)
                    this.dialogInfo.isVisible = false;
                    // 刷新表格
                    this.$refs.tSysOrgRef.refresh();
                }).finally(() => {
                    this.dialogInfo.saveBtnIsLoading = false;
                })
            });
        },
        // 查询
        searchEvent() {
            // 表单rules认证
            this.$refs.tSysOrgSearchForm.validate((valid) => {
                if (!valid) {
                    this.$message.error('搜索条件格式不正确！');
                    return false;
                }
                this.$refs.tSysOrgRef.refresh();
            });
        },
        resetOrgLevelInfoEvent() {
            this.$confirm('确认重置【组织表（companyId、fullName、hierarchy、level）和组织层级表】？', '提示', {
                confirmButtonText: '重置',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$request({
                    url: '/apm/sys/org/initOrgLevelInfo',
                    method: 'post',
                }).then(response => {
                    this.$message.success(`组织层级重置完成！`);
                })
            })
        },
        multiEditEvent() {
            let selectedRows = this.$refs.tSysOrgRef.getSelection();
            if (selectedRows.length < 1) {
                this.$message.error("请选择需要编辑的行！");
                return;
            }
            this.multiEditVisible = true;
            let names = [];
            for (let i = 0; i < selectedRows.length; i++) {
                names.push(selectedRows[i].fdName);
            }
            this.multiSelectName = names;
        },
        saveMultiEditForm() {
            let selectedRows = this.$refs.tSysOrgRef.getSelection();
            if (selectedRows.length < 1) {
                this.$message.error("请选择需要编辑的行！");
                return;
            }
            let ids = [];
            for (let i = 0; i < selectedRows.length; i++) {
                ids.push(selectedRows[i].fdId);
            }
            this.$request({
                url: '/apm/sys/org/saveMultiOrgInfo',
                method: 'post',
                data: {
                    ids: JSON.stringify(ids),
                    fdAttr: this.multiEditForm.fdAttr
                }
            }).then(response => {
                this.$message.success(`批量修改完成！`);
                this.multiEditVisible = false;
                this.$refs.tSysOrgRef.refresh();
            })

        }
    }
}
</script>

<style scoped>
</style>