<template>
    <lj-win-common :title="title" @fix-body="autoFixBody"
                   ref="baseWin">
        <div slot="body">
            <div ref="header_sub">
                <lj-searchbar-pro
                    ref="searchbarPro"
                    :keyword="keyword"
                    :apiName="apiName"
                    v-on:update:keyword="emitChangeKeyword"
                    :actions="searchActions"
                    hint="账号名称"
                    @search="handleSearchbar"
                    @cancel="handleSearchbarCancel"
                    @focusSearch="handleSearchFocus"
                    @blurSearch="handleSearchBlur"
                >
                </lj-searchbar-pro>
            </div>
            <!-- <div class="header_filtrate">
                <lj-tabs-filtrate
                    ref="ljTabsFiltrate"
                    :apiName="apiName"
                    :query-fields="queryQuick"
                    @confirm="handleFilterConfirm"
                >
                </lj-tabs-filtrate>
            </div> -->
            <div class="body">
                <lj-grid ref="ljGrid" 
                    :loading="loading" 
                    :table-data="allData" 
                    :columns="displayColumns" 
                    :height="gridHeight"
                    @cell-click="hanleGridCellClick"/>
                <mu-pagination
                    :total="totalRowCount"
                    :current.sync="currentPageIndex"
                    raised
                    @change="handlePaginationChange(currentPageIndex)"
                    :page-count="5"
                    :page-size="currentPageSize"
                    style="padding: 5px 0;justify-content:center"
                    ref="pagination"/>
            </div>
        </div>
        <div slot="footer">
            <mu-button large color="primary" @click="chooseCommit" style="width:100%">选择</mu-button>
        </div>
    </lj-win-common>
</template>

<script>
    import LjWinCommon from 'components/lj-win-common'
    import LjGrid from "components/lj-grid";
    import LjSearchbarPro from 'components/lj-searchbar-pro';
    import LjTabsFiltrate from 'components/filtrate-widget/lj-tabs-filtrate';
    import {Pagination} from 'muse-ui'

    export default {
        components: {
            LjWinCommon,
            LjGrid,
            LjSearchbarPro,
            LjTabsFiltrate,
            'mu-pagination': Pagination,
        },
        data() {
            return {
                winMode: "",
                allData: [],
                queryHardParms: {
                    dsname: "app_accounts_list",
                    queryparams: {kind: -1}
                },
                queryQuick: [

                ],
                searchActions: [
                    { 
                        title: '全部',
                        property: 'keyword'
                    },
                    { 
                        title: '账号名称',
                        property: 'accountsname' 
                    }
                ],
                columns: [
                    {property: "checked", label: "选", type: "selection",editable: true,width: 70,fixed: true},
                    {property: "accountscode", label: "账号编号", width: screen.width * 0.3, fixed: true},
                    {property: "accountsname", label: "账号名称", width: screen.width * 0.3, fixed: true},
                    {property: "simplename", label: "账号简称", width: screen.width * 0.3, fixed: true},
                    {property: "accountstype", label: "账号类别", width: screen.width * 0.3, fixed: true},
                    {property: "currencyname", label: "币种", width: screen.width * 0.3, fixed: true},
                    {property: "accountrep", label: "负责人", width: screen.width * 0.3, fixed: true},
                    {property: "dscrp", label: "备注", width: screen.width * 0.3, fixed: true},
                    {property: "banktypename", label: "默认\r\n结算方式", width: screen.width * 0.3, fixed: true},
                    {property: "displaycode", label: "会计科目", width: screen.width * 0.3, fixed: true},
                ],
                keyword: '',
                apiName: "CommonDynamicSelect",
                dwname: "L1APP-accounts-selection",
                selectedItems: [],

                totalPage: 1,
                currentRequestBody: {},
                currentRowObject: {},
                currentPageIndex: 1,
                currentPageSize: 15,
                loadedAll: true,
                loading: false,
                gridHeight: 380,
                displayColumns: [],
            }
        },
        created() {
            let pageParam = $lj.getPageParam();
            if (pageParam) {
                pageParam.queryParams = pageParam.queryParams || {};
                this.queryHardParms.queryparams = Object.assign(this.queryHardParms.queryparams, pageParam.queryParams);
            }
        },
        mounted() {
            this.getGridHeight(0,0);

            this.MergeCustomSetting();

            this.refresh(this.queryHardParms);
        },
        methods: {
            autoFixBody(item) {
                this.getGridHeight(this.searchHeight, this.paginationHeight);
            },
            getGridHeight(searchH, paginationH) {
                let paginationHeight = 0;
                if (this.$refs.pagination) {
                    if (this.$refs.pagination.$el) {
                        paginationHeight = this.$refs.pagination.$el.offsetHeight;
                    } else {
                        paginationHeight = this.$refs.pagination.offsetHeight;
                    }
                }
                paginationHeight = paginationH > 0 ? paginationH : paginationHeight;
                console.log('!!!!!!!!!!! paginationHeight :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(paginationHeight));
                if (!this.$slots.header_sub) {
                    let serchBarHeight = this.$refs.searchbarPro ? this.$refs.searchbarPro.$el.offsetHeight : searchH;
                    let tabsFiltrateHeight = this.$refs.ljTabsFiltrate ? this.$refs.ljTabsFiltrate.$el.offsetHeight : searchH;
                    this.gridHeight = this.$refs.baseWin.contentStyle.minHeight.replace("px", "") - paginationHeight - serchBarHeight - tabsFiltrateHeight;
                }
            },
            /**回调绑定值 */
            emitChangeKeyword(val) {
                this.keyword = val;
            },
            /**搜索 */
            handleSearchbar(item, ifscan) {
                let queryparams = {};
                for(let key in item) {
                    if(item[key] && item[key] != "") queryparams[key] = item[key];
                }

                if(Object.keys(queryparams).length <= 0) queryparams["keyword"] = "";

                this.refresh({searchActions: queryparams});

                this.$refs.ljTabsFiltrate && this.$refs.ljTabsFiltrate.close();
                // this.$refs.ljBottomFiltrate.initSearched(item);
                this.$refs.searchbarPro.clearText();
            },
            /**取消搜索 */
            handleSearchbarCancel(item) {
                this.refresh({searchActions: item});
                // this.$refs.ljBottomFiltrate.initSearched(item);
                this.$refs.ljTabsFiltrate && this.$refs.ljTabsFiltrate.close();
            },
            /**聚焦搜索条 */
            handleSearchFocus() {
                this.$refs.ljTabsFiltrate && this.$refs.ljTabsFiltrate.close();
            },
            /**失去聚焦搜索条 */
            handleSearchBlur() {
                setTimeout(() => {
                    this.$refs.baseWin.initStyle();
                }, 200);
            },
            /**tabs栏-筛选 */
            handleFilterConfirm(item, titles) {
                console.log('handleFilterConfirm item :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(item));
                console.log('handleFilterConfirm titles :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(titles));
                this.refresh({queryQuick: item});
            },
            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
                });
            },
            refresh(item) {
                this.currentPageIndex = 1;
                this.totalPage = 1;

                this.currentRequestBody = Object.assign({}, this.queryHardParms,this.currentRequestBody);

                if (item.queryQuick && Object.keys(item.queryQuick).length > 0) {
                    for(let key in item.queryQuick) {
                        this.currentRequestBody.queryparams[key] = item.queryQuick[key];
                    }
                }

                if(item.searchActions && Object.keys(item.searchActions).length > 0) {

                    for(let action of this.searchActions) {
                        if(this.currentRequestBody.queryparams.hasOwnProperty(action.property)) {
                            this.currentRequestBody.queryparams[action.property] = undefined;
                        }
                    }
                
                    for(let key in item.searchActions) {
                        this.currentRequestBody.queryparams[key] = item.searchActions[key];
                    }
                }

                if(!this.currentRequestBody.hasOwnProperty('queryparams')) this.currentRequestBody.queryparams = {}
                
                this.handleLoadDate();
            },
            handleLoadDate() {
                this.currentRequestBody.token = $lj.getStorage("token");
                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) {
                        if(ret.datatable) {
                            if (self.currentPageIndex >= self.totalPage) {
                                let resultLength = ret.datatable.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.allData = ret.datatable;
                        }
                    }
                })
            },
            handleResetQueryParms() {
                return this.initQueryParams;
            },
            hanleGridCellClick(eventData) {
                if (!eventData.column) {
                    return;
                }

                if(eventData.column.property === 'checked') {
                    // 单选
                    for (let item of this.selectedItems) {
                        this.$set(item, "checked", false);
                    }

                    this.$set(eventData.row, "checked", true);
                    this.selectedItems = [];
                    eventData.row.checked && this.selectedItems.push(eventData.row);
                }
                
            },
            chooseCommit() {
                if (this.selectedItems.length <= 0) {
                    $lj.toast('请选择账号!');
                    return;
                }
                $lj.sendEvent("accounts_select", this.selectedItems);
                $lj.closeWin();
            },
            handlePaginationChange(index) {
                console.log('handlePaginationChange index :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(index));
                this.currentPageIndex = index;
                this.handleLoadDate();
            },
        },
        computed: {
            isSelectMode() {
                return this.winMode === "single-select";
            },
            title() {
                if (this.winMode === 'single-select') {
                    return "账号选择";
                } else {
                    return "账号管理";
                }
            },
            totalRowCount() {
                return this.totalPage * this.currentPageSize;
            },
        }
    }
</script>