<template>
    <div class="organizManage-main">
        <div class="organizManage-mainLeft">
            <div class="public-function-div">机构树
                <el-button
                    @click="setCheckedNodes"
                    size="small"
                    class="refresh"
                >展开</el-button>
                <el-button
                    @click="setCheckedKeys"
                    size="small"
                    class="refresh2"
                >收起</el-button>
                <el-button
                    @click="handleReset('formItem')"
                    type="primary"
                    size="small"
                    class="refresh3"
                    v-privilege="activeMenu + 'ADD'"
                >新增顶级</el-button>
            </div>
            <el-input
                placeholder="输入关键字进行过滤"
                class="filterTree"
                v-model="filterText"
            >
            </el-input>
            <el-tree
                ref="orgTree"
                :data="orgTree"
                :props="defaultProps"
                node-key="orgId"
                @node-click="nodeClick"
                :expand-on-click-node="true"
                :style="{height: treeHeight + 'px'}"
                :render-content="renderContent"
                :filter-node-method="filterOrgTree"
            >
            </el-tree>
        </div>
        <div class="organizManage-mainRight">
            <div class="public-function-div">编辑区</div>
            <el-form
                ref="formItem"
                :model="formItem"
                :rules="ruleValidate"
                label-width="80px"
                class="FormorganizManage-main"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item
                            label="父机构"
                            prop="pName"
                        >
                            <el-input
                                v-model="formItem.pName"
                                disabled
                                size="small"
                                style="vertical-align:top;"
                            >
                                <!-- <el-button
                                    slot="append"
                                    @click="handleReset('formItem')"
                                >清空</el-button> -->
                            </el-input>
                        </el-form-item>
                        <el-form-item
                            label="机构id"
                            prop="orgId"
                            style="display:none;"
                        >
                            <el-input
                                v-model="formItem.orgId"
                                placeholder="请输入"
                                disabled
                                size="small"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
            <el-form-item label="机构类别"
                          prop="cate">
              <el-select v-model="formItem.cate"
                         style="width: 100%;"
                         size="small"
                         @change="changeval">
                <el-option v-for="item in dataDictionary.state.dict.CATE"
                           :value="item.value"
                           :key="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
                    <el-col :span="12">
                        <el-form-item
                            label="机构编码"
                            prop="orgCode"
                        >
                            <el-input
                                v-model="formItem.orgCode"
                                placeholder="请输入"
                                :disabled="!(operateStatus==='add')"
                                size="small"
                            >
                                <el-button
                                    v-show="operateStatus==='add'"
                                    :slot="operateStatus==='add' ? 'append' : ''"
                                    @click="getOrgCode"
                                    :disabled="textClass !== '' ? true : false"
                                    :loading="getOrgCodeLoding"
                                    :class="textClass"
                                >{{CodeText}}</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
            <el-form-item label="机构级别" prop="rank">
              <el-select v-model="formItem.rank" style="width: 100%;" size="small">
                <el-option v-for="item in formItemRank" :value="item.value" :key="item.value"  :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
                    <el-col :span="12">
                        <el-form-item
                            label="机构名称"
                            prop="orgName"
                        >
                            <el-input
                                v-model="formItem.orgName"
                                placeholder="请输入"
                                size="small"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
            <el-form-item label="二维码"
                          prop="qrCode">
              <el-input v-model="formItem.qrCode"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="机构简称"
                          prop="orgBrief">
              <el-input v-model="formItem.orgBrief"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人"
                          prop="contact">
              <el-input v-model="formItem.contact"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="中文路径"
                          prop="pathName">
              <el-input v-model="formItem.pathName"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="联系电话"
                          prop="tel">
              <el-input v-model="formItem.tel"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="城市" prop="citycode">
              <el-input v-model="formItem.citycode" placeholder="请输入" size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="办公地址"
                          prop="officeAddr">
              <el-input v-model="formItem.officeAddr"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="地区" prop="country">
              <el-input v-model="formItem.country" placeholder="请输入" size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="联系邮箱"
                          prop="email">
              <el-input v-model="formItem.email"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="邮政编码"
                          prop="post">
              <el-input v-model="formItem.post"
                        placeholder="请输入"
                        size="small"></el-input>
            </el-form-item>
          </el-col> -->
                    <!-- <el-col :span="12">
            <el-form-item label="是否虚机构"
                          prop="isVirtual">
              <el-select v-model="formItem.isVirtual"
                         style="width: 100%;"
                         size="small">
                <el-option v-for="item in formItemIsVirtual"
                           :value="item.value"
                           :key="item.value"
                           :label="item.label"></el-option>
              </el-select>
              <el-switch
                    v-model="formItem.isVirtual"
                    active-text="是"
                    inactive-text="否"
                    active-value="1"
                    inactive-value="0">
                </el-switch>
            </el-form-item>
          </el-col> -->
                    <el-col :span="24">
                        <el-form-item
                            label="备注"
                            prop="remark"
                        >
                            <el-input
                                v-model="formItem.remark"
                                placeholder="请输入"
                                type="textarea"
                                :autosize="{minRows: 3,maxRows: 5}"
                                style="width:100%"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item>
                    <el-button
                        size="small"
                        v-show="operateStatus==='edit'"
                        style="float:right;"
                        type="primary"
                        @click="handleSubmit('formItem')"
                        v-privilege="activeMenu + 'EDIT'"
                        :loading="addLoading1"
                    >保存
                    </el-button>
                    <el-button
                        size="small"
                        v-show="operateStatus==='add'"
                        style="float:right;"
                        type="primary"
                        @click="handleSubmit('formItem')"
                        v-privilege="activeMenu + 'ADD'"
                        :loading="addLoading2"
                    >添加
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>

</template>
<script>
import store from '@/store/index.js';
import dataDictionary from '@/store/dataDictionary.js';
import { checkCharLength, checkCharLength2, checkCharNoChinese, checkTel, checkEmail, checkNumber, checkChar } from '@/utils/validator.js';
import { objAssign, dgTree } from '@/utils/util.js';
export default {
    data () {
        return {
            filterText: '',
            store,
            dataDictionary,
            addLoading1: false,
            addLoading2: false,
            operateStatus: 'add',
            treeHeight: 600,
            getOrgCodeLoding: false, // 生成编码加载
            CodeText: '自动生成', // 生成提示
            textClass: '',
            formItem: {
                'orgId': '',
                'pId': '',
                'pName': '',
                'pCode': '',
                'pDeptId': '',
                'pDeptCode': '',
                'cate': '',
                'orgCode': '',
                'rank': '',
                'orgName': '',
                'qrCode': '',
                'orgBrief': '',
                'contact': '',
                'pathName': '',
                'tel': '',
                'citycode': '',
                'officeAddr': '',
                'country': '',
                'email': '',
                'remark': '',
                'post': '',
                'status': '',
                'isVirtual': ''
            },
            ruleValidate: {
                orgCode: [
                    { required: true, message: '机构编码不能为空', trigger: 'change' },
                    { validator: checkCharLength, max: 32, trigger: 'change' },
                    { validator: checkCharNoChinese, trigger: 'change' }
                ],
                orgName: [
                    { required: true, message: '机构名称不能为空', trigger: 'change' },
                    { validator: checkChar, trigger: 'change' },
                    { validator: checkCharLength, max: 64, trigger: 'change' }
                ],
                cate: [
                    { required: true, message: '机构类别不能为空', trigger: 'change' }
                ],
                remark: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' },
                    { validator: checkChar, trigger: 'change' }
                ],
                tel: [
                    { validator: checkNumber, trigger: 'change' },
                    { validator: checkTel, trigger: 'change' },
                    { validator: checkCharLength2, max: 11, trigger: 'change' }
                ],
                email: [
                    { validator: checkEmail, trigger: 'change' },
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                contact: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                orgBrief: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                officeAddr: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                post: [
                    { validator: checkNumber, trigger: 'change' },
                    { validator: checkCharLength2, max: 6, message: '请输入正确的邮政编码', trigger: 'change' }
                ]
            }
        }
    },
    watch: {
        filterText (val) {
            this.$refs.orgTree.filter(val);
        }
    },
    computed: {
        //  菜单树数据
        orgTree () {
            return this.store.state.system.organizManage.tree;
        },
        //  树配置
        defaultProps () {
            return this.store.state.system.organizManage.defaultProps;
        },
        //  展开数组
        expandedKeys: {
            get: function () {
                return this.store.state.system.organizManage.expandedKeys;
            },
            set: function (data) {
                this.store.commit('system/organizManage/expandedKeys', data);
            }
        },
        //  选中节点数据
        orgItem () {
            return this.store.state.system.organizManage.item;
        },
        //  树配置
        formItemCate () {
            return this.store.state.system.organizManage.formItemCate;
        },
        //  是否虚机构
        formItemIsVirtual () {
            return this.store.state.system.organizManage.formItemIsVirtual;
        }
    },
    mounted () {
        this.initData();
        //  设置树区域高度
        this.treeHeight = this.getTreeHeight(this.$refs['orgTree'].$el);
    },
    created () {
        this.activeMenu = window.localStorage.getItem('activeMenu');
    },
    methods: {
        initData () {
            //  查询列表
            this.store.dispatch('system/organizManage/tree').then(res => {
                if (res.code === '0') {
                    this.store.commit('system/organizManage/tree', res.data);
                    this.$nextTick(() => {
                        $('.delMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'DELET') ? 'inline-block' : 'none')
                        $('.addMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'ADD') ? 'inline-block' : 'none')
                    })
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  点击树事件
        nodeClick (item, el) {
            //  放入
            this.store.commit('system/organizManage/item', item);
            //  清空
            this.$refs['formItem'].resetFields();
            //  加入
            this.formItem = objAssign(this.formItem, item);
            this.formItem.pName = el.parent.label;
            //  点击时为编辑状态
            this.operateStatus = 'edit';
            this.$nextTick(() => {
                $('.delMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'DELET') ? 'inline-block' : 'none')
                $('.addMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'ADD') ? 'inline-block' : 'none')
            })
        },
        //  清空 清空为添加，添加直接添加顶级目录
        handleReset (name) {
            this.$refs[name].resetFields();
            this.operateStatus = 'add';
            this.CodeText = '自动生成';
            this.textClass = '';
        },
        //  添加点击
        addTreeNode (node, item) {
            this.operateStatus = 'add';
            this.$refs['formItem'].resetFields();
            //  设置pId为当前ID
            this.formItem.pId = item.orgId;
            this.formItem.pName = item.orgName;
            //  机构类别：1-机构 0-部门
            if (item.cate === '1') {
                this.formItem.pId = item.orgId;
                this.formItem.pCode = item.orgCode;
            } else if (item.cate === '0') {
                this.formItem.pDeptId = item.orgId;
                this.formItem.pDeptCode = item.orgCode;
            }
            //  清空ID
            this.formItem.orgId = '';
        },
        //  计算树区域高度
        getTreeHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        renderContent (h, { node, data, store }) {
            let render = [];
            render = [
                h('span', {
                    class: 'el-icon-delete xl-icon-size delMenuPr',
                    attrs: {
                        title: '删除'
                    },
                    on: {
                        click: (event) => {
                            this.delTreeNode(node, data);
                            event.stopPropagation();
                        }
                    }
                })
            ];
            //  如果是菜单增加 添加按钮
            render = [h('span', {
                class: 'el-icon-plus xl-icon-size addMenuPr',
                attrs: {
                    title: '添加'
                },
                on: {
                    click: (event) => {
                        this.addTreeNode(node, data);
                        event.stopPropagation();
                    }
                }
            })].concat(render);
            return h('span',
                {
                    style: {
                        position: 'relative',
                        width: '100%',
                        fontSize: '12px'
                    },
                    class: 'og-st-ellipsis'
                },
                [
                    h('span', node.label),
                    h('span', {
                        style: {
                            position: 'absolute',
                            right: '0px'
                        }
                    }, render)
                ]);
        },
        // 获取机构编码规则具体规则
        async getbsCode () {
            let that = this;
            let arr = []
            await that.axios.get('pass/v1/syscodepatterns/queryByBuilderType?builderType=' + encodeURIComponent('SYS_ORG.ORG_CODE')).then(function (res) {
                if (res.code === '0') {
                    res.data.forEach(item => {
                        arr.push({
                            id: item.codePatternId,
                            ruleType: item.patternType, // 规则类型
                            attribute: item.valueField, // 取值属性
                            display: item.valueFmt, // 显示格式
                            length: item.valueLen, // 长度
                            initial: item.valueDef, // 初始值
                            max: item.valueMax, // 最大值
                            stepLength: item.valueStep, // 步长
                            recyclable: item.isLoop, // 是否可循环
                            order: item.patternSeq, // 排列顺序
                            state: item.status // 状态
                        });
                    });
                } else {
                    that.$message.error(res.message);
                    return false;
                }
            }).catch(function (err) {
                console.log(err);
            });
            return arr
        },
        // 添加时调用规则生成新的编码规则
        async getOrgCode () {
            let that = this;
            that.getOrgCodeLoding = true;
            that.CodeText = '自动生成中...';
            let arr = await this.getbsCode();
            // 只提交启用的规则
            let codeRuleList = [];
            for (let item of arr) {
                if (item.state === '1') {
                    codeRuleList.push({
                        codePatternId: item.id,
                        patternType: item.ruleType,
                        valueField: item.attribute,
                        valueFmt: item.display,
                        valueLen: item.length,
                        valueDef: item.initial,
                        valueMax: item.max,
                        valueStep: item.stepLength,
                        isLoop: item.recyclable,
                        patternSeq: item.order,
                        status: item.state
                    });
                }
            }
            if (codeRuleList.length > 0) {
                that.axios.post('pass/v1/syscodebuilders/generateOneCode?builderType=' + encodeURIComponent('SYS_ORG.ORG_CODE'), {
                    codeRuleList: codeRuleList
                }, {
                    diy: true,
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8'
                    }
                })
                .then(function (res) {
                    if (res.code === '0') {
                        that.formItem.orgCode = res.data;
                        that.getOrgCodeLoding = false;
                        that.CodeText = '已生成';
                        that.textClass = 'green';
                    } else {
                        that.$message.error(res.message);
                        that.getOrgCodeLoding = false;
                        that.CodeText = '生成失败';
                        that.textClass = 'red';
                    }
                }).catch(function (err) {
                    that.$message.error(err);
                    that.getOrgCodeLoding = false;
                    that.CodeText = '生成失败';
                    that.textClass = 'red';
                });
            } else {
                that.$message.error('请您先在编码管理中对该编码规则进行完善！');
            }
        },
        /**
         * 保存数据
         * */
        async handleSubmit (name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    if (this.operateStatus === 'edit') {
                        if (!this.formItem.orgId) {
                            this.$message.error('请选择数据再来操作');
                            return;
                        }
                        this.$confirm('确定要修改已选择的记录吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            //  修改数据
                            this.addLoading1 = true;
                            this.formItem.cate = 1;
                            //
                            this.store.dispatch('system/organizManage/editOrg', { id: this.orgItem.id, form: this.formItem }).then(res => {
                                //
                                this.addLoading1 = false;
                                //
                                if (res.code === '0') {
                                    this.$message.success('保存成功');
                                    // //  更新菜单项
                                    let tempItem = null;
                                    dgTree(this.orgTree, 'children', item => {
                                        if (item.orgId === this.formItem.orgId) {
                                            tempItem = item;
                                        }
                                    });
                                    tempItem = Object.assign(tempItem, this.formItem);
                                    this.store.commit('system/functionMain/menuTree', this.menuTree);
                                } else {
                                    this.$message.error(res.message);
                                }
                            }).catch(() => {
                                this.addLoading1 = false;
                            });
                        }).catch(() => {
                            this.$message.info('已取消操作');
                        });
                    } else if (this.operateStatus === 'add') {
                        //   添加
                        this.addLoading2 = true;

                        this.formItem.cate = 1;
                        //
                        this.store.dispatch('system/organizManage/addOrg', this.formItem).then(res => {
                            //
                            this.addLoading2 = false;
                            //
                            if (res.code === '0') {
                                this.$message.success('添加成功');
                                //  更新树
                                this.$refs['orgTree'].append(res.data, this.formItem.pId);
                                this.$refs['orgTree'].setCurrentKey(res.data.id);
                                this.$nextTick(() => {
                                    $('.delMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'DELET') ? 'inline-block' : 'none')
                                    $('.addMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'ADD') ? 'inline-block' : 'none')
                                })
                                this.handleReset('formItem');
                            } else {
                                this.$message({ message: res.message, type: 'error' });
                            }
                        }).catch(() => {
                            this.addLoading2 = false;
                        });
                    }
                }
            })
        },
        /**
         * 删除树节点元素
         */
        delTreeNode (node, data) {
            if ((data.children && data.children.length > 0) || (node.childNodes && node.childNodes.length > 0)) {
                this.$message.error('此节点有子节点，不允许删除');
                return false;
            }
            //
            this.$confirm('确定要删除已选择的记录吗？', '提示', {
                customClass: 'org-Manage-changeprimaryforbutton',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.store.dispatch('system/organizManage/delOrg', data.orgCode).then(res => {
                    if (res.code === '0') {
                        this.$message.success('删除成功');
                        //  更新树
                        this.handleReset('formItem')
                        this.$refs['orgTree'].remove(node);
                    } else {
                        this.$message.error(res.message);
                    }
                });
            }).catch(() => {
                this.$message.info('已取消操作');
            });

            this.$nextTick(() => {
                document.getElementsByClassName('org-Manage-changeprimaryforbutton')[0].getElementsByClassName('el-message-box__btns')[0].getElementsByTagName('button')[0].classList.add('el-button--primary')
                document.getElementsByClassName('org-Manage-changeprimaryforbutton')[0].getElementsByClassName('el-message-box__btns')[0].getElementsByTagName('button')[1].classList.remove('el-button--primary')
            });
        },
        // 树形控件过滤数据
        filterOrgTree (value, data) {
            if (!value) return true;
            return data.orgName.indexOf(value) !== -1;
        },
        setCheckedKeys () {
            this.defaultExpand = false;
            for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
                this.$refs.orgTree.store._getAllNodes()[i].expanded = this.defaultExpand;
            }
        },
        setCheckedNodes () {
            this.defaultExpand = true; // 展开所有节点
            for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
                this.$refs.orgTree.store._getAllNodes()[i].expanded = this.defaultExpand;
            }
        }
    }
}
</script>
<style scoped>
.og-st-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: keep-all;
    padding-right: 60px;
}

.organizManage-main {
    position: relative;
    min-width: 1000px;
    /* height: 600px; */
}

.public-function-div {
    font-size: 16px;
    padding: 10px 20px;
    border-bottom: 1px solid #d5d5d5;
    position: relative;
}

.organizManage-mainLeft {
    width: 30%;
    border-right: 1px solid #e0e0e0;
    float: left;
    overflow: hidden;
    height: inherit;
}

.el-tree {
    overflow-x: hidden !important;
}

.organizManage-mainRight {
    width: 70%;
    float: left;
}

.FormorganizManage-main {
    margin: 20px 20px;
}

.filterTree {
    width: 95%;
    margin: 10px 2.5%;
}
.el-tree-node__content .el-icon-plus {
    margin-right: 20px;
}
.postionTop {
    position: absolute;
    top: 0px;
}
.public-function-div .refresh {
    position: absolute;
    right: 100px;
    top: 10px;
}
.public-function-div .refresh2 {
    position: absolute;
    right: 165px;
    top: 10px;
}
.public-function-div .refresh3 {
    position: absolute;
    right: 10px;
    top: 10px;
}
.delMenuPr,
.addMenuPr {
    display: none;
}
.el-tree-node__content:hover {
    background-color: #bbdffb;
}
.el-tree-node:focus .el-tree-node__content {
    background-color: #bbdffb;
}
.el-tree .is-current .el-tree-node__content {
    background-color: #bbdffb;
}
.is-current .el-tree-node__children .el-tree-node .el-tree-node__content {
    background-color: #fff;
}
.green {
    color: #67C23A !important;
}
.red {
    color: #F56C6C !important;
}
</style>
