<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">
                      <Input  :placeholder="searchPlaceholder"  v-model="searchValue"  search style="width: 98%;margin-top:10xp;margin-bottom:10px" @on-search="search" @on-enter="search"/>
                     </div>   
                      <SimpleViewGrid   ref="grid" :config="myConfig.gridConfig" :dictData="dictData" @rowclick="gridClick"/>
                </Card>
            </div>
            </template>
            <template #right>
            <div class="efuture-demo-split-pane"  style="padding:14px 16px;">
                <Card v-for="tmp in myConfig.detailGridsConfig" :key="'detail_' + tmp.name"  v-show="showDetail[tmp.name]" :padding="0"  style="padding-left:6px;"  :bordered="false" dis-hover >
                    <EditGridCardS  :ref="tmp.name" :config="tmp"  :dictData="dictData" style="padding-bottom:10px" />
                </Card>
            </div>
             </template>
        </Split>
    </div>
  </div>
</template>

<script>
import ListBtnToolbar from './listbtntoolbar.vue';
import EditGridCardS from './editgridcard.vue';
import elementResizeDetectorMaker from 'element-resize-detector';
export default {
    name: 'mleftlistrightdetails',
    components: { EditGridCardS,ListBtnToolbar },
    data() {
        return {
            myConfig: {
                billKey: 'ph_key',
                splitNum:0.33,
                resources: '',
                className: '',
                gridtitle:'列表',
                gridConfig: {}
            },
            showDetail:{},
            menuToolbar: {
                enablePermissions: true,
                items: [
                    {
                        name: 'editData',
                        text: '编辑'
                    },
                    {
                        name: 'saveData',
                        text: '保存'
                    },
                    {
                        name: 'addData',
                        text: '新增明细'
                    },
                    {
                        name: 'delData',
                        text: '删除明细'
                    }
                ]
            },
            ph_key: '',
            searchValue:'',
            searchPlaceholder:'请输入',
        };
    },
    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 - 63;
        },
        clientHeight3() {
            let size = this.myConfig.detailGridsConfig.length;
            let height = (this.$Store.state.app.clientHeight - 63)/2;
            return height;
        }
    },
    created() {
        this.myConfig = Object.assign({}, this.myConfig, this.config);
        this.myConfig.gridConfig.headStyle = '';
        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.method = this.myConfig.classPrefix + '.search';
        this.myConfig.gridConfig.response = this.myConfig.response;
        this.myConfig.gridConfig.height = 1;
        this.myConfig.gridConfig.adjustHeight = 0;
        this.myConfig.gridConfig.showBorder = true;
        this.myConfig.gridConfig.showStripe = true;
        this.myConfig.gridConfig.pageShowElevator = false;
        this.myConfig.gridConfig.pageSize= 'small';
        this.myConfig.gridConfig.showPage = true;

        this.myConfig.gridConfig.generalOrientation = true;

        if (this.myConfig.gridConfig.title) {
            this.myConfig.gridtitle = this.myConfig.gridConfig.title;
        }
        let size = this.myConfig.detailGridsConfig.length;
        this.myConfig.detailGridsConfig.forEach((el,index) => {
            let curlName = el.name;
            if (!el.name) {
                el.name='detailgrid_' + index;
            }
            if (!el.title) {
                let size = index + 1;
                el.title = '明细(' + size +')' ;
            }
            el.adjustHeight = 0;
            if (size > 1) {
                el.height = 0.5;
                el.adjustHeight = 124;
            } else {
                el.height = 1; 
                el.adjustHeight = 168;
            }
            el.width = 1;
            el.adjustWidth = 0;
            el.modetype = '2';
            el.showBorder = true;
            el.showStripe = true;
            el.generalOrientation = true;
            if (el.editItemMaxNum === undefined){
                el.editItemMaxNum = 20;
            }
            if (curlName) {
                this.showDetail[curlName] = true;
            } else {
                this.showDetail[el.name] = true;
            }
            
        });
        if (this.myConfig.gridConfig.multiSelect === undefined) {
            this.myConfig.gridConfig.multiSelect = false;
        }
        let searchPlaceholder = '';
        this.myConfig.gridConfig.items.forEach(el => {
            if (el.type !== 'CheckBox') {
                if (el.tooltip === undefined) {
                    el.tooltip = true;
                }
            }
            if (el.condition) {
                searchPlaceholder = searchPlaceholder + el.label + '/';
            }
        });
        if (searchPlaceholder) {
            searchPlaceholder = searchPlaceholder.substring(0,searchPlaceholder.length - 1);
            this.searchPlaceholder = this.searchPlaceholder + searchPlaceholder;
        }
        // 处理按钮
        if (this.myConfig.menuToolbar && this.myConfig.menuToolbar.items) {
            this.menuToolbar = this.$Method.copy(this.myConfig.menuToolbar);     
        } 
        this.menuToolbar.mainButton = 'editData';
        this.menuToolbar.mainButtonText = '修改';
    },
    methods: {
        search() {
            this.myConfig.detailGridsConfig.forEach(el =>{
                if (this.$refs[el.name] && this.$refs[el.name][0]) {
                    this.$refs[el.name][0].setData([]);
                }
            })
            this.$refs.grid.clearSearchBeforeSearchParam();
            this.$refs.grid.setSearchBeforeSearchParam(this.getSearchParam());
            this.$refs.grid.refurbish();
        },
        getSearchParam() {
            let para = {};
            if (this.searchValue) {
                para['$or'] = [];
                this.myConfig.gridConfig.items.forEach(el => {
                    if(el.condition) {
                        let obj = {};
                        obj[el.name] = {'LIKE':'%' + this.searchValue + '%'};
                         para['$or'].push(obj);
                    }
                })
            }
            return para;
        },
        refurbish(ph_key) {
            if (ph_key) {
                this.ph_key = ph_key;
            } else {
                this.ph_key = '';
            }
            this.$refs.grid.refurbish();
        },
        gridOnSelectionChange(rows) {
            let obj = {};
            obj.name = 'gridOnSelectionChange';
            obj.para = rows;
            this.$emit('doAction', obj);
        },
        fromGridOnSelectionChange(rows) {
            let obj = {};
            obj.name = 'fromGridOnSelectionChange';
            obj.para = rows;
            this.$emit('doAction', obj);
        },
        gridOverrideData(data) {
            if (data && data.length > 0) {
                let self = this;
                this.$nextTick(() => {
                    let index = 0;
                    if (self.ph_key) {
                        let culIndex = data.findIndex(el => el[self.myConfig.billKey] === self.ph_key);
                        if (culIndex > -1) {
                            index = culIndex;
                        }
                    }
                    self.$refs.grid.setRowHighlight(index, true);
                    self.ph_key = data[index][self.myConfig.billKey];
                    self.initFromGrid(data[index]);
                    self.$refs.menutoolbar.setAllReadOnly(true);
                    self.$refs.menutoolbar.setReadOnly('editData', false);
                });
            } else {
                this.$refs.menutoolbar.setAllReadOnly(true);
                this.$refs.menutoolbar.setReadOnly('editData', false);
            }
            return data;
        },
        gridClick(e) {
            let obj = {};
            let self = this;
            obj.onOk = () => {
                self.ph_key = e.ph_key;
                self.initFromGrid(e);
                self.$refs.menutoolbar.setAllReadOnly(true);
                self.$refs.menutoolbar.setReadOnly('editData', false);
            };
            obj.onCancel = () => {
                if (self.ph_key) {
                    let data = self.$refs.grid.getData();
                    let culIndex = data.findIndex(
                        el => el[self.myConfig.billKey] === self.ph_key
                    );
                    if (culIndex > -1) {
                        self.$refs.grid.clearCurrentRow();
                        self.$nextTick(() => {
                            self.$refs.grid.setRowHighlight(culIndex, true);
                        });
                    }
                } else {
                    self.$refs.grid.clearCurrentRow();
                }
            };
            this.checkData(obj);
        },
        getGrid() {
            return this.$refs.grid;
        },
        getDetailGrids(name) {
            if (this.$refs[name] && this.$refs[name][0]) {
                return  this.$refs[name][0];
            }
            return null;
        },
        getMenuToolbar() {
            return this.$refs.menutoolbar;
        },
        initFromGrid(para) {
            let data = this.getFromGridData(para);
            if (this.$parent.setBillData) {
                data = this.$parent.setBillData(data);
            }
            this.myConfig.detailGridsConfig.forEach(el => {
                if (this.$refs[el.name] && this.$refs[el.name][0]) {
                    this.$refs[el.name][0].setData(data[el.name]);
                    this.$refs[el.name][0].setReadOnly(true);
                }
            });
            if (this.$parent.initFromGridAfter) {
                this.$parent.initFromGridAfter(data);
            }
        },
        getFromGridData(para) {
            if (this.$parent.getFormData) {
                return this.$parent.getFormData(para);
            }
            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.myConfig.response]; 
                }
            );
            return result;
        },
        doAction(obj) {
            const method = obj.name;
            const methodBefore = method + 'Before';
            const methodAfter = method + 'After';
            if (obj.name === 'editData') {
                let flag = true;
                if (this.$parent[methodBefore]) {
                    flag = this.$parent[methodBefore](obj);
                }
                if (flag) {
                    if (obj.name === 'editData') {
                        let tempData = this.$refs.grid.getSelection();
                        if (tempData.length === 0) {
                            this.alert('请先选中行');
                            return ;
                        }
                        this.myConfig.detailGridsConfig.forEach(el => {
                            if (this.$refs[el.name] && this.$refs[el.name][0]) {
                                this.$refs[el.name][0].setReadOnly(false);
                            }
                        });
                        this.$refs.menutoolbar.setAllReadOnly(false);
                        this.$refs.menutoolbar.setReadOnly('editData', true);
                    }
                 
                    if (this.$parent[methodAfter]) {
                        this.$parent[methodAfter]();
                    }
                }
            } else {
                if (obj.name === 'saveData') {
                    let  checkflag = false;
                    this.myConfig.detailGridsConfig.some(el => {
                        if (this.$refs[el.name] && this.$refs[el.name][0]) {
                            checkflag = this.$refs[el.name][0].checkValidate();
                            if (checkflag) {
                                return true;
                            }
                        }
                    });
                    if (checkflag) {
                        this.alert('必填项不允许为空');
                        return false;
                    }
                    obj.para = [];
                    obj.para.push(this.getChangeData());
                }
                obj.onOk = this.onOk;
                let flag =  true;
                if (this.$parent[methodBefore]) {
                    flag = this.$parent[methodBefore](obj);
                }
                if (!flag) {
                    return;
                }
                this.$emit('doAction', obj);
            }
        },
        getChangeData() {
            let tempData = this.$refs.grid.getSelection();
            let tmp = Object.assign({},{},tempData[0]);
            tmp.flag = 'U';
            this.myConfig.detailGridsConfig.forEach(el => {
                if (this.$refs[el.name] && this.$refs[el.name][0]) {
                    tmp[el.name] =  this.$refs[el.name][0].getChangeData();
                }
            });
            return tmp
        },
        onOk(action, data) {
            if (action.name === 'saveData') {
                this.ph_key = data[0][this.myConfig.billKey];
                this.$refs.grid.refurbish({}, true);
                this.$refs.menutoolbar.setReadOnly('editData', false);
                this.$refs.menutoolbar.setReadOnly('saveData', true);
            }
        },
        checkData(obj) {
            let tempData = [];
             this.myConfig.detailGridsConfig.forEach(el => {
                if (this.$refs[el.name] && this.$refs[el.name][0]) {
                    let data =  this.$refs[el.name][0].getChangeData();
                    tempData = tempData.concat(data);
                }
            });
            if (tempData && tempData.length>0) {
                let self = this;
                self.$Modal.confirm({
                    title: '确认',
                    content: '数据存在数据未确认，是否放弃？',
                    onOk: () => {
                         obj.onOk();
                    },
                    onCancel: () => {
                        if (obj.onCancel) {
                            obj.onCancel();
                        }
                    }
                });
            } else {
                 obj.onOk();
            }
        },
        setOutsideHeight () {
            let height = this.$refs.head.offsetHeight + this.$refs.para.offsetHeight + 63;
            this.$refs.grid.setOutsideHeight(height);
        },
        setDetailVisible(name,value) {
            let tmp = {};
            tmp[name] = value;
            this.showDetail  = Object.assign({},this.showDetail,tmp);
        }
    },
    mounted() {
        this.observer = elementResizeDetectorMaker();
        if (this.$refs.head) {
            this.observer.listenTo(this.$refs.head, this.setOutsideHeight);
        }
        this.$nextTick(() => {
            this.$refs.menutoolbar.setAllReadOnly(true);
            this.$refs.menutoolbar.setReadOnly('editData', false);
            this.refurbish();

        });
    },
    beforeUnmount() {
        if (this.$refs.head) {
            this.observer.removeListener(this.$refs.head, this.setOutsideHeight);
        }
    }
};
</script>