<style lang="less">
.v-table-title-cell {}

.nx-grid-image-c-1 {
    img {
        margin-top: 8px;
        width: 80px;
        height: 80px;
    }
}

.nx-grid-image-c-2 {
    img {
        margin-top: 4px;
        width: 36px;
        height: 36px;
    }
}

.nx-sql-grid-head {
    padding: 3px 0 3px 20px;
    border-bottom: 1px solid #e0e8ef;

    button {
        margin-right: 4px;
    }
}

.nx-filter-pane {
    padding: 3px 0;
}

.nx-data-table {
    /*width: 100%;*/
}

#page-container {
    height: 40px;
    line-height: 40px;
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: right; // padding-right: 10px;

    // padding-top: 4px;
    .nv-sql-grid-toolbar {
        margin-left: 20px;
        float: left;
    }

    .nv-sql-grid-pagination {
        margin-top: 4px;
        margin-right: 10px;
    }
}

.container {
    max-height: 300px;
    overflow: auto;
    user-select: none;

    >div {
        height: 32px;
        line-height: 32px;
        font-size: 12px;
        border: 1px solid #eee;
        margin: 2px;
        color: #000;
    }
}

.sort-dragger {
    border: 1px solid red;
    z-index: 99999;
    height: 32px;
    line-height: 32px;
    font-size: 12px;
}
</style>
<template>
    <div class="visit-grid">
        <div v-show="isLoaded" class="nx-sql-grid-head">
            <Button v-for="act in actions" :key="act.show_index" @click="doAction(act.action)">{{act.caption}}</Button>
        </div>
        <FilterPane class="nx-filter-pane" v-show="isLoaded" :filters="filters" :advancedFilters="advancedFilters" @on-filter="filterTable" @on-filter-datasets="onFilterDatasets">
        </FilterPane>
        <v-table class="nx-data-table" ref="mainTable" style="width:100%" :columns="columns" :title-rows="titleRows" is-vertical-resize :vertical-resize-offset="40" column-width-drag is-horizontal-resize :paging-index="(pageIndex-1)*pageSize" :table-data="data" :is-loading="isLoading" :row-height="rowHeight" title-bg-color="#f8f8f9" even-bg-color="#f8f8f9" row-hover-color="#ebf7ff" row-click-color="#ebf7ff" :select-change="changeItem" :select-all="changeItem">
        </v-table>
        <div v-show="isLoaded" id="page-container">
            <div class="nv-sql-grid-toolbar">
                <!-- <Button icon="ios-download-outline" shape="circle" title="导出Excel"></Button> -->
                <Button icon="ios-list" shape="circle" title="调整列次序" @click="adjustColumnOrder"></Button>
            </div>
            <v-pagination class="nv-sql-grid-pagination" :total="total" @page-change="pageChange" @page-size-change="pageSizeChange" :page-index="pageIndex" :page-size="pageSize" :layout="['total', 'prev', 'pager', 'next', 'sizer', 'jumper']" :page-size-option="[10, 20, 50, 100, 200, 400]"></v-pagination>
        </div>
        <Modal title="调整列次序" v-model="showSetOrder" @on-ok="ok" @on-cancel="cancel" :mask-closable="false">
            <span style="font-weight: bold;">拖动调整次序</span>
            <SortableList lockAxis="y" :distance="10" v-model="tempOrderFieldArr" helperClass="sort-dragger">
                <SortableItem v-for="(item, index) in tempOrderFieldArr" :index="index" :key="index" :item="item" />
            </SortableList>
        </Modal>
    </div>
</template>
<script>
import { ContainerMixin, ElementMixin } from 'vue-slicksort';
import Cookies from 'js-cookie';
import Data from '@/data/visit-grid.js';
import FilterPane from '@/components/filter-pane';
import ColumnUtils from './column-utils'
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';
// import remoteLoad from '@/libs/remote-load.js'

const SortableList = {
    mixins: [ContainerMixin],
    template: `
    <div class="container">
      <slot />
    </div>
  `,
};

const SortableItem = {
    mixins: [ElementMixin],
    props: ['item'],
    template: `
    <div>{{item}}</div>
  `,
};

const TYPES = {
    "INPUT": "Input",
    "SELECT": "Select",
    "DATE": "Date"
};

export default {
    name: 'WebGrid',
    data() {
        return {
            conf: undefined,
            pageIndex: 1,
            pageSize: 20,
            titleRows: undefined,
            total: 0,
            data: undefined,
            datasets: {},
            actions: [],
            advancedFilters: [],
            filters: [],
            whereItems: [],
            /*外部传递参数*/
            params: {
                /*网格Guid*/
                grid_guid: undefined,
                /*企业Id*/
                tenant_id: undefined,
                /*部门Guid*/
                dept_guid: undefined,
                /*员工Guid*/
                emp_guid: undefined,
                /*拜访组Guid*/
                step_guid: undefined
            },
            isLoading: false,
            isLoaded: false,
            selectItems: [],
            selectItem: undefined,
            columnOrdersKey: undefined,
            /*图片查看对象*/
            viewers: [],

            //列排序
            showSetOrder: false,
            //所有列名
            orderFieldArr: [],
            tempOrderFieldArr: [],
        }
    },
    components: {
        FilterPane,
        SortableList,
        SortableItem
    },
    mixins: [ColumnUtils],
    computed: {},
    methods: {
        /*提供给外部使用的函数*/
        /*确认是单选*/
        ensureSingleSelect() {
            if (this.selectItems.length == 0) {
                this.$Modal.warning({
                    title: '警告信息',
                    content: '请先选择一条信息'
                })

                return false;
            } else if (this.selectItems.length > 1) {
                this.$Modal.warning({
                    title: '警告信息',
                    content: '只能选择一条信息'
                })

                return false;
            }

            return true;
        },

        /*确认是多选*/
        ensureMultiSelect() {
            if (this.selectItems.length == 0) {
                this.$Modal.warning({
                    title: '警告信息',
                    content: '请选择处理信息'
                })

                return false;
            }

            return true;
        },

        /*获取所有数据*/
        getData() {
            return this.data;
        },

        /*获取选中项*/
        getSelect() {
            return this.selectItem;
        },

        /**
         * 获取选中的Guid
         */
        getSelectGuid() {
            return this.selectItem["guid"];
        },

        /**
         * 获取所有选中的Guid
         */
        getSelectGuids() {
            let guids = [];
            this.selectItems.forEach((item) => {
                guids.push(item["guid"]);
            });

            return guids;
        },

        pageChange(pageIndex) {
            this.pageIndex = pageIndex;
            this.getTableData();
        },

        pageSizeChange(pageSize) {
            this.pageIndex = 1;
            this.pageSize = pageSize;
            this.getTableData();
        },

        changeItem(obj) {
            this.selectItems = [];
            this.selectItems = this.selectItems.concat(obj);

            if (this.selectItems.length > 0) {
                this.selectItem = this.selectItems[0];
            } else {
                this.selectItem = {};
            }
        },
        /*点击过滤*/
        filterTable(fa) {
            this.whereItems = fa;
            this.pageIndex = 1;
            let model = this.getQueryModel();

            this.isLoading = true;
            Data.queryVisitDataAndTotal(model).then((res) => {
                this.setupData(res.data);
                this.total = res.total;
                this.isLoading = false;
            });
        },

        setUpOrderFields(conf) {
            this.orderFieldArr = conf.columns.filter((item) => {
                return item["visible"] == 1;
            }).map((item) => {
                return item.caption;
            });

            const order = Cookies.get(this.columnOrdersKey);
            if (order) {
                this.orderFieldArr.sort((a, b) => {
                    return order.indexOf(a) - order.indexOf(b);
                });
            }
        },

        adjustColumnOrder() {
            this.tempOrderFieldArr = this.orderFieldArr.concat();
            this.showSetOrder = true;
        },

        ok() {
            this.showSetOrder = false;
            this.orderFieldArr = this.tempOrderFieldArr;
            Cookies.set(this.columnOrdersKey, this.orderFieldArr);

            this.setupColumns(this.conf);
        },

        cancel() {
            this.showSetOrder = false;
        },
        /*过滤中数据集信息*/
        onFilterDatasets(datasets) {
            this.datasets = datasets;
        },

        getTableData() {
            this.isLoading = true;
            Data.queryVisitData(this.getQueryModel()).then((res) => {
                this.setupData(res.data);
                this.isLoading = false;
            });
        },

        setupData(dataSource) {
            let data = dataSource.data;

            let indexMap = {};
            for (let d of data) {
                indexMap[d["guid"]] = d;
            }

            /*不会配20项吧*/
            const is = [...Array(20).keys()];
            for (let f of is) {
                const currData = dataSource["data_" + f];
                if (!currData) {
                    break;
                }

                this.addToData(indexMap, currData);
            }

            this.data = data;
            this.$nextTick(() => {
                this.viewers.forEach((viewer) => {
                    viewer.destroy();
                });
                this.viewers.length = 0;

                let ids = this.$el.querySelectorAll(".nx-grid-image-c");
                ids.forEach((id) => {
                    let viewer = new Viewer(id, { url: "original" });
                    this.viewers.push(viewer);
                });
            });
        },

        addToData(indexMap, currData) {
            for (let d of currData) {
                indexMap[d["visit_guid"]] = Object.assign(indexMap[d["visit_guid"]], d);
            }
        },

        setupActions(conf) {
            let actions = [];
            for (let a of conf.actions) {
                let act = {
                    caption: a.caption,
                    action: a.action
                }

                actions.push(act);
            }

            this.actions = actions;
        },
        setupFilters(conf) {
            let filters = [];

            //处理过滤信息
            let confFilters = conf.filters;
            confFilters.sort(function(a, b) {
                return a.show_index - b.show_index;
            });

            for (let f of confFilters) {
                let filter = {
                    type: this.getFilterType(f.editor),
                    label: f.caption,
                    code: f.field,
                    op: f.operator
                }

                this.setDefaultValue(filter, f);
                this.setDataset(filter, f);

                filters.push(filter);
            }

            this.filters = filters;

            //处理高级过滤信息
            let columns = conf.columns;
            let advancedFilters = [];
            columns.forEach((col) => {
                if (col["show_in_super_filter"] === 1 && col["visible"] === 1 && col["type"] === "STRING") {
                    advancedFilters.push({
                        "caption": col["caption"],
                        "field": col["code"],
                        "type": col["type"]
                    });
                }
            });

            this.advancedFilters = advancedFilters;
        },

        setDefaultValue(filter, f) {
            if (f.editor == "DATE") {
                if (f.operator == 'between') {
                    /*日期型范围默认月初到当天*/
                    filter.defValue = "FirstToCurrentOfMonth";
                } else {
                    /*日期型默认当天*/
                    filter.defValue = "CurrentDate";
                }
            }
        },
        getFilterType(editor) {
            return TYPES[editor] ? TYPES[editor] : editor;
        },

        /*根据配置设置数据集*/
        setDataset(filter, conf) {
            switch (conf.editor) {
                case "SELECT":
                    this.setSelectDataset(filter, conf);
                    this.datasets[conf.field] = true;
                    break;
            }
        },

        setSelectDataset(filter, conf) {
            const ds = conf.datasource;
            if (ds && ds.indexOf("data__") == 0) {
                filter['ds'] = JSON.parse(ds.substr(6));
                filter['dsType'] = 'SET';
            }
        },

        /*构造查询模型*/
        getQueryModel() {
            return Object.assign({
                "page_index": this.pageIndex,
                "page_size": this.pageSize,
                "_where": JSON.stringify(this.whereItems)
            }, this.params);
        },

        /*读取参数*/
        readParams() {
            this.params = Object.assign(this.params, this.$route.query);
            this.columnOrdersKey = this.params["grid_guid"] + this.params["step_guid"] + this.params["emp_guid"];
        },

        /*执行操作*/
        doAction(action) {
            if (action) {
                // console.log(action);
                // alert(action);
                // eval(action);
                let a = new Function('return ' + action);
                alert(a);
            } else {
                let a = new Function("m", "return mmm(m)");
                // alert("没有设置功能属性");
                a(this);
            }
        }
    },
    mounted() {
        this.readParams();
        this.isLoading = true;

        // remoteLoad("http://localhost:8080/static/test.js");
        Data.queryVisitConfig(this.getQueryModel()).then((res) => {
            this.conf = res.config;
            this.setupFilters(this.conf);
            this.setUpOrderFields(this.conf);
            // this.setupActions(res.config);
            this.setupColumns(this.conf);
            this.isLoading = false;
            this.isLoaded = true;
        });
    }
};
</script>