<!--
 * @Author: zzy6937@qq.com
 * @Date: 2019-07-01 09:14:32
 * @LastEditors: wf
 * @LastEditTime: 2021-09-22 21:24:17
 * @Description:
 -->
<template>
    <div class="zz-table">
        <!-- :height='isScroll ? boxHeight : null' -->
        <el-table
            :border="settings.tableBorder"
            :height="height"
            style="width: 100%"
            ref="table"
            v-loading="loading"
            :data="data"
            :summary-method="getSummaries"
            :show-summary="!!(settings.summaryCol && settings.summaryCol.length)"
            tooltip-effect="light"
            size="small"
            :key="updateFlag"
            @selection-change="selectionChange"
            row-key="id"
            :expand-row-keys="expands"
            @expand-change="toggleRow"
            @sort-change="sortChange"
            :default-sort="settings.defaultSort"
            :empty-text="emptyText"
            :show-header="settings.showHeader"
            :row-class-name="setRowClassName"
            lazy
            :load="load"
            :tree-props="treeProps"
            class="customer-table"
        >
            <!-- 显示多选框 -->
            <el-table-column
                type="selection"
                width="60"
                align="center"
                v-if="settings.showCheckbox"
                :selectable="selectable"
            ></el-table-column>
            <!-- 显示单选框 -->
            <el-table-column width="50" align="left" v-if="settings.showRadio">
                <template slot-scope="scope">
                    <el-radio-group v-model="radioSelect">
                        <el-radio :label="scope.$index"></el-radio>
                    </el-radio-group>
                </template>
            </el-table-column>
            <!-- 显示序号 -->
            <el-table-column label="No." type="index" :width="70" align="left" v-if="settings.showIndex"></el-table-column>
            <el-table-column
                label="NO."
                type="index"
                :width="settings.showNumberWidth"
                align="left"
                v-if="settings.showNumber"
            ></el-table-column>
            <!-- 显示具体行 -->
            <el-table-column
                v-for="(item, index) in cols"
                :fixed="item.fixed"
                :width="item.width"
                :min-width="item.minWidth"
                :prop="item.prop"
                :label="item.label"
                :key="index"
                :type="item.type"
                align="left"
                :sortable="item.sort || false"
                filter-placement="bottom"
                :show-overflow-tooltip="!isIE"
            >
                <template slot="header" slot-scope="scope">
                    <slot v-if="item.headerSlot" :name="item.headerSlot" :data="scope"></slot>
                    <span v-else>{{ item.label }}</span>
                </template>
                <template slot-scope="scope">
                    <!-- 插槽 -->
                    <slotItem v-if="item.slot" :row="scope.row" :index="scope.$index" :slots="$scopedSlots[item.slot]"></slotItem>
                    <!-- 过滤方法 -->
                    <el-tooltip
                        v-else-if="item.format && isIE"
                        class="item"
                        effect="light"
                        placement="bottom"
                        :disabled="item.format(scope.row[item.prop]).length < 2"
                        :content="item.format(scope.row[item.prop])"
                    >
                        <p
                            @click="item.click ? item.click() : null"
                            v-html="
                                item.format(scope.row[item.prop], scope.row) ||
                                (item.format(scope.row[item.prop], scope.row) === 0 ? 0 : item.empty ? '' : '-')
                            "
                        ></p>
                    </el-tooltip>
                    <p
                        v-else-if="item.format && !isIE"
                        @click="item.click ? item.click() : null"
                        v-html="item.format(scope.row[item.prop]) || (item.format(scope.row[item.prop]) == 0 ? 0 : '-')"
                    ></p>
                    <!-- <p
                        v-else-if="item.format && isIE"          
                        class="item" effect="light" placement="top-start"  
                        @click="item.click ? item.click() : null"
                    >
                        {{
                            item.format(scope.row[item.prop], scope.row) ||
                            (item.format(scope.row[item.prop], scope.row) === 0 ? 0 : item.empty ? '' : '-')
                        }}
                    </p> -->
                    <!-- <p v-else-if="item.format" @click='item.click?item.click():null'>{{item.format(scope.row[item.prop]) || (item.format(scope.row[item.prop]) == 0 ? 0 : '-')}}</p> -->
                    <!-- 默认显示 -->
                    <el-tooltip
                        v-else-if="!item.slot && !item.format && isIE"
                        class="item"
                        effect="light"
                        placement="bottom"
                        :disabled="scope.row[item.prop] && scope.row[item.prop].length < 2"
                        :content="scope.row[item.prop]"
                    >
                        <p
                            @click="item.click ? item.click() : null"
                            v-html="scope.row[item.prop] || (scope.row[item.prop] === 0 ? 0 : item.empty ? '' : '-')"
                        ></p>
                    </el-tooltip>
                    <p
                        v-else
                        @click="item.click ? item.click() : null"
                        v-html="scope.row[item.prop] || (scope.row[item.prop] === 0 ? 0 : item.empty ? '' : '-')"
                    ></p>
                    <!-- <p v-else-if="item.fixToolTip" v-tip.same :data-txt="scope.row[item.prop]" @click="item.click ? item.click() : null">
                        {{ scope.row[item.prop] || (scope.row[item.prop] === 0 ? 0 : item.empty ? '' : '-') }}
                    </p> -->
                    <!-- <p v-else v-tip :data-txt="scope.row[item.prop]" @click="item.click ? item.click() : null">
                        {{ scope.row[item.prop] || (scope.row[item.prop] === 0 ? 0 : item.empty ? '' : '-') }}
                    </p> -->
                </template>
            </el-table-column>
        </el-table>
        <div class="foot" v-if="!settings.hideFoot">
            <!-- 手动全选及操作 -->
            <!-- <div v-if="false" class="selectAll" :class="{ hasIndex: settings.showIndex }">
                <el-checkbox v-if="checkHide()" v-model="isSelectAll" @change="checkAllChange"></el-checkbox>
                <el-tooltip class="item" effect="light" content="展示/隐藏" placement="bottom">
                    <span :class="checkHide()?'batch_display':'batch_collapse'" class="batch_button" @click="hideordisplay"></span>
                </el-tooltip>
                <slot v-if="checkHide()" name="batchtodo"></slot>
            </div> -->
            <el-pagination
                v-if="pageset.hasOwnProperty('total') && !settings.hidePagination"
                class="pagination"
                background
                @size-change="sizeChange"
                @current-change="currentChange"
                :current-page="currentPage"
                :page-sizes="pageset.pageSizes || [15, 30, 60, 120]"
                :page-size="pageset.pageSize || 15"
                :total="pageset.total || 0"
                layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>
        </div>
    </div>
</template>
<script>
export default {
    name: 'zz-table',
    props: {
        /*
		table例设置
		[{
			label: 例名.   必须.  String
			prop: 数据字段.  必须.  String
			fixed: 当前例是否固定.  值有left,right。 String
			width: 例宽.  Number
			slot: 插槽方式, String
			format: 数据过滤方法, Function
			click: 当前内容的点击事件, Function

		}]
		*/
        cols: {
            type: Array,
            default() {
                return [];
            }
        },
        /*
		table数据
		*/
        data: {
            type: Array,
            default() {
                return [];
            }
        },
        /*
		table表格设置
		*/
        settings: {
            type: Object,
            default() {
                return {
                    // 是否显示表头
                    showHeader: true,
                    // 是否显示序号
                    showIndex: false,
                    // 是否显示序列号大写
                    showNUmber: false,
                    // 序列号宽度
                    showNumberWidth: '70',
                    // 是否显示多选框
                    showCheckbox: false,
                    hideAllCheckbox: false,
                    // 是否显示单选框
                    showRadio: false,
                    // 需要统计列的prop集合，从0开始
                    summaryCol: [],
                    // 是否显示边框
                    tableBorder: false
                };
            }
        },
        /*
		分页设置
		*/
        pageset: {
            type: Object,
            default() {
                return {
                    total: 0,
                    pageSize: 10,
                    pageNum: 1,
                    pageSizes: [15, 30, 60, 120]
                };
            }
        },
        loading: {
            type: Boolean,
            default() {
                return false;
            }
        },
        height: 0,
        updateFlag: false, //触发表格重绘
        // 统计数据.传入统计数据则显示该统计数据，否则显示现有列表数据
        summaryData: {},
        // 判断多选框是否可以勾选
        selectable: {
            type: Function,
            default() {
                return (row, index) => {
                    return true;
                };
            }
        },
        expands: {
            type: Array,
            default() {
                return [];
            }
        },
        treeProps: {
            type: Object,
            default() {
                return {};
            }
        },
        load: {
            type: Function,
            default() {
                return () => {};
            }
        },
        emptyText: {
            type: String,
            default() {
                return '暂无相关结果';
            }
        }
    },
    data() {
        return {
            isIE: false,
            radioSelect: '',
            boxHeight: null,
            currentPage: 1,
            isSelectAll: false,
            isScroll: false,
            hideornot: true
        };
    },
    methods: {
        checkHide() {
            if (this.settings.showCheckbox && this.hideornot) {
                return true;
            } else {
                return false;
            }
        },
        hideordisplay() {
            this.hideornot = !this.hideornot;
        },
        setRadioIndex(index) {
            this.radioSelect = index;
        },
        sortChange(column, prop, order) {
            //点击排序按钮后拿到column.order，可以发送column.order给后台，后台再根据什么排序来返回排序过后的数据
            // console.log(column + '---' + column.prop + '---' + column.order)
            const data = JSON.parse(JSON.stringify(column));
            data.prop = (data.prop && data.prop.replace(/([A-Z])/g, '_$1').toLowerCase()) || null;
            if (this.settings.defaultSort && this.settings.defaultSort.propExtend) {
                data.prop = `${data.prop}${this.settings.defaultSort.propExtend}`;
            }
            data.order = data.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : null;
            this.$emit('sort-change', data);
        },
        toggleRow(row, expandedRows) {
            // this.expands = [];
            const index = _.findIndex(expandedRows, (v) => v.id == row.id);
            if (index != -1) {
                this.expands.push(row.id);
                this.$emit('toggle-change', row);
            } else {
                this.expands = _.filter(this.expands, (v) => v != row.id);
            }
        },
        // 多选派发事件selection-change
        selectionChange(val) {
            this.isSelectAll = val.length == this.data.length;
            this.$emit('selection-change', val);
        },
        /*
		页数改变时，派发pageChange事件，并传递当前分页参数；
		其中pageSize为每页显示多少条数据，page为当前显示多少页
		*/
        sizeChange(pageSize) {
            this.$emit('page-change', {
                pageSize: pageSize
            });
        },
        currentChange(page) {
            this.currentPage = page;
            this.$emit('page-change', {
                page: page
            });
        },
        // 合计
        getSummaries(params) {
            let { data } = params;
            if ('{}' != JSON.stringify(this.summaryData)) {
                data = [this.summaryData];
            }
            let sums = [];
            sums[0] = '合计';
            let cols = JSON.parse(JSON.stringify(this.settings.summaryCol));
            let i = cols.length;
            while (i--) {
                // 计算当前列的prop字段
                let index = cols[i];
                if (this.settings.showIndex) {
                    index -= 1;
                }
                if (this.settings.showCheckbox) {
                    index -= 1;
                }
                if (this.settings.showRadio) {
                    index -= 1;
                }
                let prop = this.cols[index].prop;
                const values = data.map((item) => Number(item[prop]));
                if (!values.every((value) => isNaN(value))) {
                    sums[cols[i]] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            let sumVa = Number(prev) + curr;
                            return sumVa.toFixed(2);
                        } else {
                            return Number(prev.toFixed(2));
                        }
                    }, 0);
                    sums[cols[i]];
                }
            }

            return sums;
        },
        checkAllChange(val) {
            if (val) {
                this.$refs.table.toggleAllSelection();
            } else {
                this.$refs.table.clearSelection();
            }
        },
        //自定义表头斑马线
        setRowClassName({ row, rowIndex }) {
            let index = rowIndex;
            if (index % 2 == 0) {
                return 'warning-row';
            }
        }
    },
    watch: {
        radioSelect(n) {
            this.$emit('radio-change', this.data[n]);
        },
        pageset: {
            deep: true,
            handler(n) {
                this.currentPage = n.pageNum;
            }
        }
    },
    components: {
        slotItem: {
            props: ['slots', 'row', 'index'],
            render(h) {
                let vnode = this.slots({
                    row: this.row,
                    index: this.index
                });
                return h('div', vnode);
            }
        }
    },
    created() {
        const userAgent = window.navigator.userAgent;
        const isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1; //判断是否IE<11浏览器
        const isEdge = userAgent.indexOf('Edge') > -1 && !isIE; //判断是否IE的Edge浏览器
        const isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
        this.isIE = isIE11 || isEdge || isIE;
    }
};
</script>

<style lang="scss" scoped>
@import '@assets/css/public-style.scss';
.zz-table .el-table {
    border-radius: 6px;
    /deep/ td {
        .opt {
            display: flex;
            align-items: center;
            cursor: pointer;
            i {
                margin-right: 20px;
                width: 14px;
                height: 14px;
                line-height: 14px;
                &:last-child {
                    margin-right: 0;
                }
            }
        }
    }
    /deep/ .el-table-column--selection .cell {
        padding-left: 0 !important;
        padding-right: 10px !important;
    }
    /deep/ .el-table__header .el-table-column--selection {
        .cell {
            padding-left: 0;
        }
    }
}
.foot {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    .selectAll {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .el-checkbox {
            text-align: center;
            width: 40px;
            margin-right: 10px;
        }
        //table下面foot的按钮样式
        .el-button.is-disabled {
            border: none;
            background: #ffffff !important;
            border: 1px solid #a6abb6;
            opacity: 0.5;
            border-radius: 4px;
            & span {
                font-size: 12px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                line-height: 16px;
                color: #b6b1b1 !important;
                opacity: 1;
            }
        }
        .el-button--primary.batch_btn {
            background-color: #ffffff;
            border: 1px solid #a6abb6;
            opacity: 1;
            border-radius: 4px;
            color: #7b7f86;
            &:hover {
                border-color: $mainTextColor !important;
                span {
                    color: $mainTextColor !important;
                }
            }
            &.is-disabled {
                color: #7b7f86ad;
                border: 0.01rem solid #a6abb66b;
                &:hover {
                    color: #7b7f86ad;
                    border-color: #a6abb66b !important;
                }
            }
            span {
                font-size: 12px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                line-height: 16px;
                color: #7b7f86 !important;
                opacity: 1;
            }
        }
        .batch_button {
            display: inline-block;
            width: 30px;
            height: 30px;
            background-size: 100% 100%;
            cursor: pointer;
            margin-right: 10px;
        }
        .batch_display {
            // background: url('~@/assets/img/btn_shou.png') center no-repeat;
            background-size: 100% 100%;
        }
        .batch_collapse {
            // background: url('~@/assets/img/btn_collapse.png') center no-repeat;
            background-size: 100% 100%;
        }
    }
}
</style>
