<!--单据列表查询，以表格形式展示通用模板窗口-->
<!--封装了数据获取请求、分页查询、高级搜索等用户交互方式-->
<!--events-->
<!--单元格点击cell-click，详见lj-grid-->
<!--行点击row-click，详见lj-grid-->
<!--高级筛选条件点击query-field-click，详见lj-query-list-->
<!--高级筛选条件值改变query-field-change，详见lj-query-list-->
<!--methods-->
<!--打开右侧抽屉openRightDrawer()-->
<!--关闭右侧抽屉closeRightDrawer()-->
<!--直接设置条件的值setQueryParam(property, value)同lj-query-list-->
<!--slots-->
<!--header：app bar中间，默认为标题-->
<!--header_right：appbar 右侧，通常为图标按钮-->
<!--header_sub： appbar下方子标题，固定在顶部-->
<!--footer：底部，固定-->
<template>
    <lj-win-common :title="title" right-drawer-title="搜索" :rightDrawerInitOpen="rightDrawerInitOpen" :closeWinHandler="closeWinHandler"
                   ref="baseWin">
        <slot slot="header" name="header"></slot>
        <mu-button v-if="columnCustomizable" icon slot="header_right"
                   @click="openSettingWin">
            <i class="iconfont icon-settings"></i>
        </mu-button>
        <mu-button v-if="showFilter" icon slot="header_right" @click="openRightDrawer">
            <i class="iconfont icon-filter"></i>
        </mu-button>
        <slot name="header_right" slot="header_right"></slot>
        <div slot="body">
            <slot name="header_sub" :ifShowSearchbar="ifShowSearchbar" :searchtext="searchText" :search="handleSearchbar">
                <lj-searchbar v-if="ifShowSearchbar" ref="searchbarDom" :hint="hint" v-model="searchText" @search="handleSearchbar" />
            </slot>
            <slot name="body_grid" :loading="loading" :tableData="list" :height="gridHeight">
                <lj-grid :loading="loading" :table-data="list" :columns="displayColumns" :height="gridHeight"
                     @row-click="$emit('row-click',$event)"
                     @cell-click="$emit('cell-click',$event)"/>
            </slot>
            <mu-pagination
                    v-if="pagination"
                    :total="totalRowCount"
                    :current.sync="currentPageIndex"
                    raised
                    @change="load"
                    :page-count="5"
                    :page-size="currentPageSize"
                    style="padding: 5px 0;"
                    ref="pagination"/>
            <mu-dialog :open.sync="moreDialogOpen" width="100%" scrollable>
                <lj-dictionary :columns="popupColumns" :data="currentRowObject"/>
            </mu-dialog>
        </div>
        <slot slot="footer" name="footer"></slot>
        <!-- 右方抽屉内容 -->
        <lj-query-list v-if="showFilter" slot="drawer_right" :query-fields="queryFields" :habit-key="apiName"
                       :hard-parms="queryHardParms"
                       :binding-parms="bindingParms"
                       :show-scan="ifShowScan"
                       @on-query-submit="handleQuerySubmit"
                       @field-click="handleQueryFieldClick"
                       @field-change="handleQueryFieldChange"
                       @scan-click="handleClickScan"
                       ref="queryList"/>
    </lj-win-common>
</template>

<script>
    import LjWinCommon from 'components/lj-win-common'
    import LjQueryList from "components/lj-query-list";
    import LjGrid from "components/lj-grid";
    import {Pagination} from 'muse-ui'
    import LjDictionary from "components/lj-dictionary";
    import LjSearchbar from 'components/lj-searchbar';

    export default {
        name: "lj-win-grid-view",
        components: {
            LjDictionary,
            LjGrid,
            LjQueryList,
            LjWinCommon,
            'mu-pagination': Pagination,
            LjSearchbar
        },
        props: {
            // 标题名称
            title: {
                type: String,
                required: true
            },
            // 同lj-query-list的queryFields，设置后显示筛选按钮，点击弹出高级筛选框
            queryFields: {
                type: Array
            },
            // 同lj-query-list的hardParms
            queryHardParms: {
                type: Object
            },
            // 同lj-query-list的bindingParms
            bindingParms: {
                type: Object
            },
            // 获取单据列表的接口的接口
            apiName: {
                type: String,
                required: true
            },
            // 字段设置，详见lj-grid
            columns: {
                type: Array
            },
            // 是否分页
            pagination: {
                type: Boolean,
                default: true
            },
            hint: {
                type: String,
                default: "请输入关键字搜索"
            },
            rightDrawerInitOpen: {
                type: Boolean,
                default: false
            },
            columnCustomizable: {
                type: Boolean,
                default: true
            },
            ifShowSearchbar: {
                type: Boolean,
                default: false
            },
            ifShowScan: {
                type: Boolean,
                default: false
            },
            searchText:{
                type: String,
                default: "" 
            },
            searchHeight:{
                type: Number,
                default: 0 
            },
            useInnerMergeCustomSetting:{
                type: Boolean,
                default: true
            },
            closeWinHandler: {
                type: Function,
            },
        },
        data() {
            return {
                loadedAll: true,
                loading: false,
                moreDialogOpen: false,
                gridHeight: 400,
                dwname: "L1APP",
                totalPage: 1,
                currentRowObject: {},
                currentPageIndex: 1,
                currentPageSize: 20,
                currentRequestBody: {},
                list: [],
                displayColumns: [],
                popupColumns: [],
                moreColumn: {
                    property: "more_button",
                    label: "更多",
                    width: 100,
                    slot: this.moreSlotRender
                }
                //searchText: ""
            }
        },
        mounted() {
            let paginationHeight = 0;
            if (this.$refs.pagination) {
                if (this.$refs.pagination.$el) {
                    paginationHeight = this.$refs.pagination.$el.offsetHeight;
                } else {
                    paginationHeight = this.$refs.pagination.offsetHeight;
                }
            }
            if (!this.$slots.header_sub) {
                // headerSubHeight = 40;
                // alert(this.$slots.header_sub.offsetHeight);
                // alert(this.$slots.header_sub.height);
                // alert(this.$slots.header_sub.clientHeight);
                if(this.ifShowSearchbar) {
                    let serchBarHeight = this.$refs.searchbarDom ? this.$refs.searchbarDom.$el.offsetHeight : this.searchHeight;
                    this.gridHeight = this.$refs.baseWin.contentStyle.minHeight.replace("px", "") - paginationHeight - serchBarHeight;
                } else {
                    this.gridHeight = this.$refs.baseWin.contentStyle.minHeight.replace("px", "") - paginationHeight;
                }
            }

            if(this.useInnerMergeCustomSetting){
                this.MergeCustomSetting();
            }

            // if (!this.showFilter) {
                this.refresh();
            // }
        },
        methods: {
            openRightDrawer() {
                this.$refs.baseWin.openRightDrawer();
            },
            closeRightDrawer() {
                this.$refs.baseWin.closeRightDrawer();
            },
            closeWin() {
                $lj.closeWin();
            },
            handleSearchbar() {
                this.refresh({keyword: this.searchText});
            },
            handleClickScan(){
                this.$emit("scan-click");
            },
            handleQuerySubmit(queryParams) {
                this.closeRightDrawer();
                this.list = [];
                this.refresh(queryParams);
            },
            refresh(queryParams) {
                this.currentPageIndex = 1;
                this.totalPage = 1;
                this.currentRequestBody = Object.assign(queryParams || this.currentRequestBody || {}, this.queryHardParms);
                this.load();
                this.$emit("refresh");
            },
            load() {
                this.currentRequestBody.token = $lj.getStorage("token");
                if (this.pagination) {
                    this.currentRequestBody.pageindex = this.currentPageIndex;
                    this.currentRequestBody.pagesize = this.currentPageSize;
                }
                this.loading = true;
                let self = this;
                $lj.postLJRequest(this.apiName, this.currentRequestBody, function (ret) {
                    self.loading = false;
                    if (ret) {
                        self.$emit("loadedAllData",ret);
                        for (let key in ret) {
                            if (self.currentPageIndex >= self.totalPage) {
                                let resultLength = ret[key].length;
                                if (resultLength === 0 && self.currentPageIndex > 1) {
                                    self.currentPageIndex--;
                                    self.totalPage = self.currentPageIndex;
                                    $lj.toast("数据已加载完毕");
                                    return;
                                } else if (resultLength < self.currentPageSize) {
                                    self.totalPage = self.currentPageIndex;
                                    $lj.toast("数据已加载完毕");
                                } else {
                                    self.totalPage = self.currentPageIndex + 1;
                                }
                            }
                            self.list = ret[key];
                            self.$emit("loaded", ret[key]);
                            return;
                        }
                    }
                })
            },
            MergeCustomSetting: function () {
                let userInfo = $lj.getStorage('userInfo');
                let empid = userInfo.empid;
                let requestBody = {
                    token: $lj.getStorage("token"),
                    empid: empid,
                    dwname: this.dwname,
                    itemname: this.apiName,
                    ifcompress: 1
                };
                let self = this;
                this.displayColumns = [];
                this.popupColumns = [];
                $lj.postLJRequest(
                    "GetSysUserFileString", requestBody,
                    function (ret) {
                        if (ret && ret.itemvalue) {
                            let customSetting = JSON.parse(ret.itemvalue);
                            // 构建field-style键值对
                            let customSettingDictionary = new Map();
                            for (let item of customSetting) {
                                customSettingDictionary.set(item.property, item);
                            }
                            // 合并过滤字段，以这个字典为准，用户历史设置多删少补
                            for (let item of self.columns) {
                                let curField = item.property;
                                let userStyle = customSettingDictionary.get(curField);
                                if (userStyle) {
                                    // for (let prop in userStyle) {
                                    //     item[prop] = userStyle[prop];
                                    // }
                                    item.order = userStyle.order;
                                    item.invisible = userStyle.invisible;
                                } else {
                                    // 新增字段，暂不显示
                                    item.invisible = true;
                                }
                            }
                        } else {
                            for (let i in self.columns) {
                                self.columns[i].order = i;
                            }
                        }
                        self.columns.sort(function (object1, object2) {
                            return object1.order - object2.order;
                        });
                        for (let i in self.columns) {
                            let item = self.columns[i];
                            item.order = i;
                            if (item.optionid) {
                                let optionName = $lj.getOptionValue(item.optionid);
                                item.label = optionName ? optionName : item.label;
                            }
                            if (item.fixed) {
                                self.displayColumns.push(item);
                            } else if (!item.invisible) {
                                self.popupColumns.push(item);
                            }
                        }
                        if (self.popupColumns.length > 0) {
                            self.displayColumns.push(self.moreColumn);
                        }
                    }
                );
            },
            openSettingWin() {
                let self = this;
                $lj.removeEventListener("grid_style_updated");
                $lj.addEventListener("grid_style_updated", function (ret) {
                    if (ret.value) {
                        if (ret.value.dwname === self.dwname && ret.value.itemname === self.apiName) {
                            self.MergeCustomSetting();
                        }
                    }
                });
                $lj.openWin('grid-view-setting', {
                    columns: this.columns,
                    apiName: this.apiName
                });
            },
            moreSlotRender(h, {row, column, rowIndex}) {
                let self = this;
                return h('mu-button', {
                        attrs: {icon: true},
                        on: {
                            click: function () {
                                self.currentRowObject = self.list[rowIndex];
                                self.moreDialogOpen = true;
                            }
                        }
                    },
                    [h('i', {class: ["iconfont", "icon-format-list-bulleted"]})]
                )
            },
            handleQueryFieldClick(event) {
                this.$emit("query-field-click", event);
            },
            handleQueryFieldChange(event){
                this.$emit("query-field-change", event);
            },
            setQueryParam(property, value) {
                this.$refs.queryList.setQueryParam(property, value);
            },
            setDisplayColumns(data){
                this.$nextTick(() => this.displayColumns = data);
            }
        },
        computed: {
            showFilter() {
                return this.queryFields && this.queryFields.length > 0;
            },
            hasLoadmoreFunction() {
                return this.dataLoadedCallback;
            },
            totalRowCount() {
                return this.totalPage * this.currentPageSize;
            }
        },
        watch: {
            searchHeight(newVal) {
                console.log('searchHeight 赋值新newVal :>> ', newVal);
                let paginationHeight = 0;
                if (this.$refs.pagination) {
                    if (this.$refs.pagination.$el) {
                        paginationHeight = this.$refs.pagination.$el.offsetHeight;
                    } else {
                        paginationHeight = this.$refs.pagination.offsetHeight;
                    }
                }
                if (!this.$slots.header_sub) {
                    if(this.ifShowSearchbar) {
                        let serchBarHeight = this.$refs.searchbarDom ? this.$refs.searchbarDom.$el.offsetHeight : newVal;
                        this.gridHeight = this.$refs.baseWin.contentStyle.minHeight.replace("px", "") - paginationHeight - serchBarHeight;
                    } else {
                        this.gridHeight = this.$refs.baseWin.contentStyle.minHeight.replace("px", "") - paginationHeight;
                    }
                }

            }
        }
    }
</script>

<style scoped>

</style>