<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 0px;">
                        <Card :padding="0" :bordered="false" dis-hover>
                            <BillDetailForm ref="form" :config="myConfig.detailConfig" :dictData="dictData"/>
                        </Card>
                    </div>
                </template>
            </Split>
        </div>
        <Modal  title="操作日志" v-model="showBilloperlog" :width="logcurrentWidth" :footer-hide="true">
            <BillOperLog ref="billoperlog" :config="billOperLogConfig"/>
        </Modal>
    </div>
</template>

<script>
import ListBtnToolbar from './listbtntoolbar.vue';
import BillDetailForm from '@/components/masterplate/billdetailform.vue';
import elementResizeDetectorMaker from 'element-resize-detector';
import BillOperLog from './operlog.vue';

export default {
    name: 'mleftlistrightdetails',
    components: {BillOperLog, ListBtnToolbar, BillDetailForm},
    data() {
        return {
            myConfig: {
                billKey: 'ph_key',
                gridtitle: '列表',
                splitNum: 0.33,
                resources: '',
                className: '',
                gridConfig: {},
                formConfig: {},
                adjustHeight: 160,
                quickQueryConfig: {}
            },
            searchPlaceholder: '请输入',
            menuToolbar: {
                enablePermissions: true
            },
            ph_key: '',
            searchValue: '',
            headHeight: 63,
            showBilloperlog:false,
            billOperLogConfig:{
                showOperLog:false,
                operLogKey:'billno'
            },
            logName:[],
            logData:null,
        };
    },
    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;
        },
        logcurrentWidth () {
            return this.$Store.state.app.clientWidth * 0.8;
        },
    },
    created() {
        this.myConfig = Object.assign({}, this.myConfig, this.config);
        this.myConfig.gridConfig.onSelectionChange = this.gridOnSelectionChange;
        this.myConfig.gridConfig.overrideData = this.gridOverrideData;
        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.pageShowElevator = false;
        this.myConfig.gridConfig.pageSize = "small";
        this.myConfig.gridConfig.showBorder = true;
        this.myConfig.gridConfig.showStripe = true;
        this.myConfig.gridConfig.generalOrientation = true;
        if (this.myConfig.gridConfig.title !== undefined) {
            this.myConfig.gridtitle = this.myConfig.gridConfig.title;
        }

        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);
        }

        if (this.myConfig.billOperLogConfig) {
            this.billOperLogConfig = Object.assign({},this.billOperLogConfig, this.myConfig.billOperLogConfig);
            if (this.billOperLogConfig.showOperLog) {
                this.menuToolbar.billoperlog = true;
                this.setLogName();
            }
        }

        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: {
        setLogName() {
            this.logName.push({code:this.myConfig.response,name:'主表'});
            this.myConfig.detailConfig.formsConfig.items.forEach(el => {
                this.initLogName(el.items,this.myConfig.response,el.title)
            });
            if (this.myConfig.detailConfig.billDetailConfig !== undefined && this.myConfig.detailConfig.billDetailConfig.items) {
                this.myConfig.detailConfig.billDetailConfig.items.forEach(el => {
                    if (el.type === 'EditGridCard') {
                        this.logName.push({code:el.name,name:el.title,isdetail:'1'});
                        this.initLogName(el.items,el.name,el.title,{isdetail:'1'});
                    } else if (el.type === 'DetailsBox') {
                        this.logName.push({code:el.name,name:el.title,isdetail:'1'});
                        this.initLogName(el.formConfig.items,el.name,el.title,{isdetail:'1'});
                        this.logName.push({code:el.gridName, name:el.gridConfig.title,isdetail:'2',headtitle:el.title,uniqueKeys:el.uniqueKeys});
                        this.initLogName(el.gridConfig.items,el.gridName,el.gridConfig.title,{headtitle:el.title,uniqueKeys:el.uniqueKeys,isdetail:'2'});
                    }
                });
            }
            this.billOperLogConfig.logName = this.$Method.copy(this.logName);
        },
        initLogName(list,headname,headtitle,pro) {
            if (!pro) {
                pro = {};
            }
            list.forEach(el => {
                if (el.name) {
                    let obj = {};
                    obj.title = headtitle;
                    obj.code = headname+'.' + el.name;
                    obj.name = el.label;
                    Object.assign(obj,pro);
                    this.logName.push(obj);
                }
                if (el.textName) {
                    let obj = {};
                    obj.title = headtitle;
                    obj.code = headname +'.' + el.textName;
                    obj.name = el.label;
                    Object.assign(obj,pro);
                    this.logName.push(obj);
                }
                if (el.sname) {
                    let obj = {};
                    obj.title = el.headtitle;
                    obj.code = headname +'.' + el.sname;
                    obj.name = el.label;
                    Object.assign(obj,pro);
                    this.logName.push(obj);
                }
                if (el.ename) {
                    let obj = {};
                    obj.title = el.headtitle;
                    obj.code = headname + '.' + el.ename;
                    obj.name = el.label;
                    Object.assign(obj,pro);
                    this.logName.push(obj);
                }
            });
        },
        openBilloperlog() {
            if (this.logData != null) {
                this.$refs.billoperlog.setData(this.logData[this.billOperLogConfig.operLogKey],this.logData);
                this.showBilloperlog = true;
            } else {
                this.alert('未产生日志');
            }
        },
        search() {
            this.$refs.form.clearData();
            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.form.clearData();
            this.$refs.grid.refurbish();
        },
        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.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.billKey];
                    self.initForm(data[index]);
                    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);
                this.$refs.menutoolbar.setReadOnly('addData', false);
            }
            return data;
        },
        gridClick(e) {
            let obj = {};
            let self = this;
            obj.onOk = () => {
                self.ph_key = e.ph_key;
                self.initForm(e);
                self.$refs.menutoolbar.setAllReadOnly(false);
                self.$refs.menutoolbar.setReadOnly('saveData', true);
            };
            obj.onCancel = () => {
                let data = self.$refs.form.getData();
                if (data.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);
        },
        getForm() {
            return this.$refs.form;
        },
        getGrid() {
            return this.$refs.grid;
        },
        quickChagne() {
            this.ph_key = '';
            this.search();
        },
        getMenuToolbar() {
            return this.$refs.menutoolbar;
        },
        initForm(para) {
            this.$refs.form.clearData();
            let data = this.getFormData(para);
            this.logData = this.$Method.copy(data);
            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);
            }
            let result = {};
            let self = this;
            if (!para.ph_key) {
                para.ph_key = this.ph_key;
            }
            self.synchroPost(
                self.myConfig.resources,
                self.myConfig.classPrefix + '.get',
                {ph_key: para.ph_key},
                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 === 'addData' ||
                obj.name === 'editData' ||
                obj.name === 'openBilloperlog' ||
                obj.name === 'searchData'
            ) {
                let flag = true;
                if (this.$parent[methodBefore]) {
                    flag = this.$parent[methodBefore](obj);
                }
                if (flag) {
                    if (obj.name === 'addData') {
                        this.$refs.form.setReadOnly(false);
                        this.$refs.form.clearData();
                        this.$refs.menutoolbar.setAllReadOnly(true);
                        this.$refs.menutoolbar.setReadOnly('saveData', false);
                        this.$refs.grid.clearCurrentRow();
                    }
                    if (obj.name === 'editData') {
                        this.$refs.form.setReadOnly(false);
                        this.$refs.menutoolbar.setReadOnly('editData', true);
                        this.$refs.menutoolbar.setReadOnly('saveData', false);
                    }
                    if (obj.name === 'searchData') {
                        let temp = {};
                        let self = this;
                        temp.onOk = () => {
                            self.$refs.quick.filterSearch();
                        };
                        this.checkData(temp);
                    }

                    // '打开日志'
                    if (obj.name === 'openBilloperlog') {
                        if (this.$parent.openBilloperlog) {
                            this.$parent.openBilloperlog();
                        } else {
                            this.openBilloperlog();
                        }
                    }

                    if (this.$parent[methodAfter]) {
                        this.$parent[methodAfter]();
                    }
                }
            } else {
                let flag = true;
                if (this.$parent[methodBefore]) {
                    flag = this.$parent[methodBefore](obj);
                }
                if (!flag) {
                    return;
                }
                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();
                    if (data.flag === 'U') {
                        obj.editFlag = true;
                    }
                    obj.para = [];
                    obj.para.push(data);
                }
                if (obj.name === 'delData') {
                    let tempData = this.$refs.grid.getSelection();
                    if (tempData && tempData.length > 0) {
                        tempData.forEach(el => {
                            el.flag = 'D';
                        });
                        obj.para = tempData;
                    } else {
                        this.alert('没有数据可删除，请检查');
                        return false;
                    }
                }
                obj.onOk = this.onOk;
                if (obj.name === 'delData') {
                    let 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.ph_key = data[0].ph_key;
                if (action.editFlag) {
                    this.$refs.grid.refurbish({}, true);
                } else {
                    this.$refs.grid.refurbish();
                }
                this.initForm(data[0]);
                this.$refs.menutoolbar.setReadOnly('editData', false);
                this.$refs.menutoolbar.setReadOnly('saveData', true);
            }
            if (action.name === 'delData') {
                this.ph_key = '';
                this.$refs.form.clearData();
                this.$refs.grid.refurbish();
                this.$refs.form.setReadOnly(true);
                this.$refs.menutoolbar.setAllReadOnly(false);
                this.$refs.menutoolbar.setReadOnly('saveData', true);
            }
        },
        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();
                }
            }
        },
        setOutsideHeight() {
            let height = this.$refs.head.offsetHeight + this.$refs.para.offsetHeight + 80;
            this.$refs.grid.setOutsideHeight(height);
            let height2 = this.$refs.head.offsetHeight;
            this.$refs.form.setOutsideHeight(height2);
        },
        getChangeData() {
            return this.$refs.form.getChangeData();
        },
        setDetailVisible(name, value) {
            this.$refs.form.setVisible(name, value);
        }
    },
    mounted() {
        this.observer = elementResizeDetectorMaker();
        if (this.$refs.head) {
            this.observer.listenTo(this.$refs.head, this.setOutsideHeight);
        }
        if (this.$refs.para) {
            this.observer.listenTo(this.$refs.para, this.setOutsideHeight);
        }
        this.$refs.grid.refurbish();
        this.headHeight = this.$refs.head.offsetHeight;
        this.$nextTick(() => {
            this.$refs.form.setReadOnly(true);
            this.$refs.menutoolbar.setAllReadOnly(false);
            this.$refs.menutoolbar.setReadOnly('saveData', true);
        });
    },
    beforeUnmount() {
        this.observer.removeListener(this.$refs.head, this.setOutsideHeight);
        this.observer.removeListener(this.$refs.para, this.setOutsideHeight);
    }
};
</script>
