<template>
<div :style="'background:#fff;overflow: hidden;height:' + clientHeight +'px'">
    <div ref="head">
        <Card :padding="0" style="padding-top:14px;padding-left:16px;padding-right:16px;border-radius:0px;"  :bordered="false" dis-hover>
            <ListBtnToolbar ref="menutoolbar" :config="menuToolbar"  :moduleMethod="moduleMethod"   @doAction="doAction"/>
            <Divider style="margin-top:16px;margin-bottom:0px;" />
        </Card>
    </div>
    <div class="efuture-demo-split" :style="'height:' + clientHeight2 +'px;'">
        <Split v-model="myConfig.splitNum">
            <template #left>
            <div  class="efuture-demo-split-pane" style="padding:14px 16px;">
                <Card :padding="0" :bordered="false" dis-hover >
                    <p  style="margin-bottom:10px;">
                       <span class="efuture-title-verticalline" /> <span style="font-size: 14px;font-weight:bold" v-text="myConfig.gridtitle" />
                    </p>
                    <div ref="para">
                        <Row v-if="showCondition">
                          <ControlBox  ref="condition"   style="width: 100%;margin-top:10xp;margin-bottom:10px" :config="conditionConfig"  ></ControlBox>
                        </Row>
                        <Row>
                            <Input  :placeholder="searchPlaceholder"  v-model="searchValue"  search style="width: 100%;margin-top:10xp;margin-bottom:10px" @on-search="search" @on-enter="search"/>
                        </Row>
                     </div>
                      <TreeBox v-show="showTree" ref="tree" :config="myConfig.treeConfig"   @onSelectChange="selectChange" />
                      <SimpleViewGrid  v-show="!showTree"  ref="grid" :config="myConfig.gridConfig" :dictData="dictData" @rowclick="gridClick"/>
                </Card>
            </div>
            </template>
            <template #right>
            <div  class="efuture-demo-split-pane" style="padding:14px 0px;">
                <Card :padding="0" :bordered="false" dis-hover >
                    <BillDetailForm ref="form" :config="myConfig.detailConfig" :dictData="dictData" />
                </Card>
            </div>
            </template>
        </Split>
    </div>
</div>
</template>

<script>
import ListBtnToolbar from './listbtntoolbar.vue';
import BillDetailForm from '@/components/masterplate/billdetailform.vue';
import elementResizeDetectorMaker from 'element-resize-detector';
export default {
    name:'mlefttreerightdetails',
    components:{ListBtnToolbar, BillDetailForm},
    data () {
        return {
            myConfig:{
                gridtitle:'列表',
                billKey:'ph_key',
                splitNum:0.25,
                resources:'',
                className:'',
                formTitle:'详情',
                adjustHeight:200,
                treeConfig:{},
                gridConfig:{},
            },
            conditionConfig:{},

            rootNode:{},
            levelData:[],
            menuToolbar:{
                enablePermissions:true
            },
            searchPlaceholder:'请输入编码或名称',
            showTree:true,
            ph_key:'',
            treeSeletedNode:[],
            searchValue:'',
            headHeight:63,
            conditionValue:''
        };
    },
    props:{
        config: {
            type:Object,
            default:null
        },
        dictData: {
            type: Object,
            default:null
        },
        moduleMethod:{
            type:Array,
            default: () => {
                return [];
            }
        }
    },
    computed: {
        clientHeight () {
            return this.$Store.state.app.clientHeight;
        },
        clientHeight2() {
            return this.$Store.state.app.clientHeight - this.headHeight;
        }
    },
    created () {
        this.myConfig =  Object.assign({},this.myConfig, this.config);
        this.myConfig.gridConfig.onSelectionChange = this.gridOnSelectionChange;
        this.myConfig.gridConfig.overrideData = this.gridOverrideData;
        this.myConfig.gridConfig.showCondition = false;
        this.myConfig.gridConfig.resources = this.myConfig.resources;
        this.myConfig.gridConfig.tableSize ='small';
        this.myConfig.gridConfig.showBorder = false;
        this.myConfig.gridConfig.pageShowSizer = false;
        this.myConfig.gridConfig.generalOrientation = true;
        this.myConfig.gridConfig.height = 1;
        this.myConfig.gridConfig.adjustHeight = 0;
        if (this.myConfig.gridConfig.title !== undefined) {
            this.myConfig.gridtitle = this.myConfig.gridConfig.title;
        }
        if (!this.myConfig.gridConfig.method) {
            this.myConfig.gridConfig.method = this.myConfig.classPrefix + '.search';
        }
        if (!this.myConfig.gridConfig.response) {
            this.myConfig.gridConfig.response = this.myConfig.response;
        }

        this.myConfig.gridConfig.multiSelect = false;
        if (this.myConfig.treeConfig.items) {
            this.myConfig.gridConfig.items = this.$Method.copy(this.myConfig.treeConfig.items);
        }
        if (this.myConfig.treeConfig.treeCondition) {
            this.conditionConfig = Object.assign({},this.conditionConfig,this.myConfig.treeConfig.treeCondition);
            if (this.conditionConfig.dictkey) {
                if (!this.conditionConfig.data) {
                    this.conditionConfig.data = this.$Method.copy(this.dictData[this.conditionConfig.dictkey]);
                }
            }
            if (this.conditionConfig.valueChanged) this.conditionConfig.onChange = this.$Method.copy(this.conditionConfig.valueChanged);
            this.conditionConfig.valueChanged = this.conditionValueChanged;
            this.showCondition = true;
        }

        if (this.myConfig.treeConfig.searchParam) {
            this.myConfig.gridConfig.searchParam = {};
            Object.assign(this.myConfig.gridConfig.searchParam, this.myConfig.treeConfig.searchParam);
        }


        // 处理树
        this.myConfig.treeConfig.resources = this.myConfig.resources;
        if (!this.myConfig.treeConfig.method) {
            this.myConfig.treeConfig.method = this.myConfig.classPrefix + '.search';
        }
        if (!this.myConfig.treeConfig.response) {
            this.myConfig.treeConfig.response = this.myConfig.response;
        }
        this.myConfig.treeConfig.showCondition = false;
        this.myConfig.treeConfig.showTitle = false;
        this.myConfig.treeConfig.bordered = false;
        this.myConfig.treeConfig.disHover = true;
        this.myConfig.treeConfig.height = 1;
        this.myConfig.treeConfig.adjustHeight =  0;
        this.myConfig.treeConfig.selectedRoot = true;
        if (this.myConfig.treeConfig.showCodeWithName === undefined) {
            this.myConfig.treeConfig.showCodeWithName = true;
        }
        if(this.myConfig.treeConfig.setTreeNodeIcon !== undefined) {
            this.setCustomTreeNodeIcon = this.myConfig.treeConfig.setTreeNodeIcon;
        }
        this.myConfig.treeConfig.setTreeNodeIcon = this.setTreeNodeIcon;

        // 处理按钮
        if (this.myConfig.menuToolbar !== undefined) {
          this.menuToolbar = Object.assign({}, this.menuToolbar, this.myConfig.menuToolbar);
        }
        this.menuToolbar.mainButton = 'editData';
        this.menuToolbar.mainButtonText = '修改';
        this.myConfig.detailConfig.modetype = '2';
        this.myConfig.detailConfig.billKey = this.myConfig.billKey;
        this.myConfig.detailConfig.showAnchorLink = false;
        this.myConfig.detailConfig.response = this.myConfig.response;
        this.myConfig.detailConfig.adjustHeight = 0;
        this.myConfig.detailConfig.resources = this.myConfig.resources;
    },
    methods:{
        selectChange (e) {
            let obj = {};
            let self = this;
            obj.onOk = () => {
                if (e && e.length > 0) {
                    self.$refs.menutoolbar.setAllReadOnly(true);
                    self.treeSeletedNode = self.$Method.copy(e);
                    self.initForm(e[0]);
                } else {
                    self.doCanCel();
                    this.$refs.menutoolbar.setAllReadOnly(true);
                    if (this.treeSeletedNode.length > 0) {
                        this.initForm(this.treeSeletedNode[0]);
                    }
                }
            };
            obj.onCancel = () => {
                self.doCanCel();
            };
            this.checkData(obj);
        },
        search () {
            let obj = this.getSearchParam();
            this.treeSeletedNode = [];
            if (!this.searchValue) {
                this.showTree = true;
            } else {
                obj['$or'] = [];
                let code = {};
                code[this.myConfig.treeConfig.responseCode] = {'LIKE':'%' + this.searchValue + '%'};
                obj['$or'].push(code);
                let name = {};
                code[this.myConfig.treeConfig.responseName] = {'LIKE':'%' + this.searchValue + '%'};
                obj['$or'].push(name);
                this.$refs.grid.clearSearchBeforeSearchParam();
                this.$refs.grid.setSearchBeforeSearchParam(obj);
                this.$refs.grid.refurbish();
                this.showTree = false;
            }
        },
        getSearchParam () {
            let searchParam = this.$Method.copy(this.myConfig.treeConfig.searchParam);
            if (!searchParam) {
                searchParam = {};
            }
            return searchParam;
        },
        refurbish () {
            this.treeSeletedNode = [];
            this.initTree();
        },
        gridOnSelectionChange(rows) {
            let obj = {};
            obj.name = 'gridOnSelectionChange';
            obj.para = rows;
            this.$emit('doAction', obj);
        },
        gridOverrideData (data) {
            if (data && data.length > 0) {
                let self = this;
                this.$nextTick(() => {
                    let index = 0;
                    if (self.treeSeletedNode.length > 0) {
                        let culIndex = data.findIndex(el => el[self.myConfig.billKey]=== self.treeSeletedNode[0][self.myConfig.billKey]);
                        if (culIndex > -1) {
                            index = culIndex;
                        }
                    }
                    self.$refs.grid.setRowHighlight(index,true);
                    self.ph_key = data[index].ph_key;
                    self.initForm(data[index]);
                    self.$refs.form.setReadOnly(true);
                    self.$refs.menutoolbar.setAllReadOnly(false);
                    self.$refs.menutoolbar.setReadOnly('saveData', true);
                });
            } else {
                this.$refs.form.clearData();
                this.$refs.form.setReadOnly(true);
                this.$refs.menutoolbar.setAllReadOnly(true);
            }

            return data;
        },
        gridClick(e) {
            let obj = {};
            let self = this;
            obj.onOk = () => {
                self.treeSeletedNode = [e];
                self.initForm(e);
            };
            obj.onCancel = () => {
                self.doCanCel();
            };
            this.checkData(obj);
        },
        doCanCel () {
            this.$nextTick(() => {
                if (this.showTree) {
                    this.$refs.tree.setData(this.treeSeletedNode);
                } else {
                    this.$refs.grid.setAllRowHighlight(false);
                    let data = self.$refs.grid.getData();
                    let index = data.findIndex(el => el[self.myConfig.billKey] === self.treeSeletedNode[0][self.myConfig.billKey]);
                    if (index > -1) {
                        this.$refs.grid.setRowHighlight(index, true);
                    } else {
                        this.$refs.grid.clearCurrentRow();
                    }
                }
            });

        },
        getForm() {
            return this.$refs.form;
        },
        getGrid() {
            return this.$refs.grid;
        },
        getTree() {
            return this.$refs.tree;
        },
        getMenuToolbar() {
            return this.$refs.menutoolbar;
        },
        quickChagne () {
            this.search();
        },
        initTree(flag) {
            this.$refs.tree.refurbish();
            this.$nextTick(() => {
                if (this.treeSeletedNode.length > 0) {
                    this.$refs.tree.setData(this.treeSeletedNode);
                }
                if (!flag) {
                    this.initForm(this.treeSeletedNode[0]);
                }
            });
        },
        updateTree(data,flag) {
            this.$refs.tree.updaeNode(data,'U');
        },
        initForm (para) {
            this.$refs.form.clearData();
            let data = {};
            this.$refs.menutoolbar.setAllReadOnly(true);
            if (!para) {
                return;
            }
            let rootNode = this.$refs.tree.getRootNode();
            if (para[this.myConfig.treeConfig.idField]  === rootNode[this.myConfig.treeConfig.idField]) {
                data = this.$Method.copy(rootNode);
                this.$refs.menutoolbar.setReadOnly(['addChildData'], false);
            } else {
                data = this.getFormData(para);
                if (this.$refs.tree.isChildren(para)) {
                    this.$refs.menutoolbar.setReadOnly(['editData','addSelfData','addChildData'], false);
                } else {
                    this.$refs.menutoolbar.setReadOnly(['editData','addSelfData','addChildData','delData'], false);
                }
            }
            if (this.$parent.setBillData) {
                data = this.$parent.setBillData(data);
            }
            this.$refs.form.setData(data);
            this.$nextTick(() => {
                this.$refs.form.setReadOnly(true);
            });
            if (this.$parent.initFormAfter) {
                this.$parent.initFormAfter(data);
            }
        },
        getFormData (para) {
            if (this.$parent.getFormData) {
                return this.$parent.getFormData(para);
            } else {
                let result = {};
                let self = this;
                let tmp = {};
                if (!para[this.myConfig.billKey]) {
                    tmp[this.myConfig.billKey] = this.ph_key;
                } else {
                    tmp[this.myConfig.billKey] = para[this.myConfig.billKey];
                }
                self.synchroPost(self.myConfig.resources,self.myConfig.classPrefix+'.get', tmp, function (data) {
                    result = data[self.config.response];
                });
                return result;
            }
        },
        doAction(obj) {
            const method = obj.name;
            const methodBefore = method + 'Before';
            const methodAfter = method + 'After';
            if (obj.name === 'addSelfData' || obj.name === 'addChildData' || obj.name === 'editData' ) {
                let flag =  true;
                let temp = {};
                if (this.$parent[methodBefore]) {
                    flag = this.$parent[methodBefore](temp);
                }
                if (flag) {
                    if (obj.name === 'addSelfData' || obj.name === 'addChildData') {
                        this.$refs.form.setReadOnly(false);
                        this.$refs.form.clearData();
                        this.$refs.form.setData(temp);
                        this.$refs.menutoolbar.setAllReadOnly(true);
                        this.$refs.menutoolbar.setReadOnly('saveData', false);
                    }
                    if (obj.name === 'editData') {
                        if (this.treeSeletedNode.length === 0) {
                            this.alert('请先选择节点');
                            return false;
                        }

                        let obj = this.$refs.tree.getRootNode();
                        if (obj[this.myConfig.treeConfig.responseCode] === this.treeSeletedNode[0][this.myConfig.treeConfig.responseCode]) {
                            this.alert('当前节点不允许修改');
                            return false;
                        }

                        this.$refs.form.setReadOnly(false);

                        this.$refs.menutoolbar.setReadOnly('editData', true);
                        this.$refs.menutoolbar.setReadOnly('saveData', false);
                    }

                    if (this.$parent[methodAfter]) {
                        this.$parent[methodAfter]();
                    }
                }
            } else {
                if (obj.name === 'saveData') {
                    let flag = this.$refs.form.checkValidate();
                    if (flag) {
                        this.alert('必填项不允许为空');
                        return false;
                    }
                    flag = this.$refs.form.isEdit();
                    if (flag) {
                        this.alert('存在数据未确认');
                        return false;
                    }
                    let data = this.$refs.form.getChangeData();
                    obj.para = [];
                    obj.para.push(data);

                }
                if (obj.name === 'delData') {
                    let tempData = this.$refs.form.getData();
                    tempData.flag = 'D';
                    obj.para = tempData;
                }
                obj.onOk = this.onOk;
                let flag =  true;
                if (this.$parent[methodBefore]) {
                    flag = this.$parent[methodBefore](obj);
                }
                if (!flag) {
                    return;
                }
                if (obj.name === 'delData') {
                    let text = '保存';
                    if (obj.name === 'delData') {
                        text = '删除';
                    }
                    let self = this;
                    self.$Modal.confirm({
                        title:'确认',
                        content:'是否确认'+text+'数据？',
                        onOk:() => {
                            self.$emit('doAction', obj);
                        }
                    });
                } else {
                    this.$emit('doAction', obj);
                }
            }
        },
        onOk (action, data) {
            if (action.name === 'saveData') {
                this.$refs.menutoolbar.setAllReadOnly(true);
                this.initForm(data[0]);
                this.$refs.form.setReadOnly(true);
                let temp = this.$refs.form.getData();
                this.treeSeletedNode =[temp];
                //this.initTree(true);
                this.$refs.tree.updateNode(temp,'U');
                if (!this.showTree) {
                    this.$refs.grid.refurbish();
                }
                this.$refs.menutoolbar.setReadOnly(['addSelfData','addChildData','editData'], false);
            }
            if (action.name === 'delData') {
                this.$refs.tree.updateNode(this.treeSeletedNode[0],'D');
                this.treeSeletedNode = [];
                this.$refs.form.setReadOnly(true);
                this.$refs.form.clearData();
                if (!this.showTree) {
                    this.$refs.grid.refurbish();
                }
                this.$refs.menutoolbar.setReadOnly(['addSelfData','addChildData','editData'], false);
            }
        },
        checkData (obj) {
            let tempflag = false;
            tempflag = this.$refs.form.isEdit();
            if (tempflag) {
                let self = this;
                self.$Modal.confirm({
                    title:'确认',
                    content:'数据存在数据未确认，是否放弃？',
                    onOk:() => {
                        this.checkChangeData(obj);
                    },
                    onCancel:() => {
                        if (obj.onCancel) {
                            obj.onCancel();
                        }
                    }
                });
            } else {
                this.checkChangeData(obj);
            }
        },
        checkChangeData(obj) {
            let flag = false;
            flag = this.$refs.form.isChange();
            if (flag) {
                let self = this;
                self.$Modal.confirm({
                    title:'确认',
                    content:'数据有修改未保存，是否放弃修改？',
                    onOk:() => {
                        if (obj.onOk) {
                            obj.onOk();
                        }
                    },
                    onCancel:() => {
                        if (obj.onCancel) {
                            obj.onCancel();
                        }
                    }
                });
            } else {
                if (obj.onOk) {
                    obj.onOk();
                }
            }
        },
        setTreeAndGridAndFormHeight() {
            let height = this.$refs.head.offsetHeight + this.$refs.para.offsetHeight + 62;
            this.$refs.tree.setOutsideHeight(height);
            this.$refs.grid.setOutsideHeight(height);
            let height2 = this.$refs.head.offsetHeight;
            this.$refs.form.setOutsideHeight(height2);
        },
        setTreeNodeIcon(params, obj) {

            const hasChildren =
                params.data.children &&
                params.data.children.length > 0

            if (hasChildren) {
                if (params.data.expand) {
                    obj.type = '_custom-wenjianzhankai'
                } else {
                    obj.type = '_custom-wenjianshouqi'
                }
            } else {
                obj.type = '_custom-yemian'
            }

            if (this.setCustomTreeNodeIcon) {
                obj = this.setCustomTreeNodeIcon(params, obj)
            }

            return obj
        },
        getSelectedNode() {
            let obj = {};
            if (this.treeSeletedNode.length > 0) {
               obj = this.$Method.copy(this.treeSeletedNode[0]);
            }
            return obj;
        },
        getChangeData() {
            return this.$refs.form.getChangeData();
        },
        setDetailVisible(name,value) {
            this.$refs.form.setVisible(name, value);
        },
        getTreeCondition() {
            return this.$refs.condition;
        },
        conditionValueChanged(e) {
            let flag = true;
            if (this.conditionConfig.onChange) flag = this.conditionConfig.onChange(e);
            if (flag === undefined) flag = true;
            if (!flag) return flag;

            this.$nextTick(() => {
                let tmp = {};
                let self = this;
                tmp.onOk = () => {
                    let para = {};
                    let value = self.$refs.condition.getValue();
                    if (value) {
                        para[self.conditionConfig.name] = value;
                    }
                    self.searchValue = '';
                    self.showTree = true;
                    self.treeSeletedNode = [];
                    self.$refs.form.clearData();
                    self.$refs.menutoolbar.setAllReadOnly(true);
                    self.$refs.form.setReadOnly(true);
                    self.$refs.tree.refurbish(para);
                    self.conditionValue = value;
                };
                tmp.onCancel = () => {
                    self.$refs.condition.setValue(self.conditionValue);
                }
                self.checkData(tmp);
            });
            return true;
        }
    },
    mounted () {
        this.observer = elementResizeDetectorMaker();
        if (this.$refs.head) {
            this.observer.listenTo(this.$refs.head, this.setTreeAndGridAndFormHeight);
        }
        if (this.$refs.para) {
            this.observer.listenTo(this.$refs.para, this.setTreeAndGridAndFormHeight);
        }
        this.headHeight = this.$refs.head.offsetHeight;
        this.$nextTick(() => {
            this.$refs.form.setReadOnly(true);
            this.$refs.menutoolbar.setAllReadOnly(false);
            this.refurbish();
        });
    },
    beforeUnmount() {
        if (this.$refs.head) {
            this.observer.removeListener(this.$refs.head, this.setTreeAndGridAndFormHeight);
        }
        if (this.$refs.para) {
            this.observer.removeListener(this.$refs.para, this.setTreeAndGridAndFormHeight);
        }
    }
};
</script>

<style>

</style>
