<!--
基础通用表格
@Author: linqian
@Date: 2021-07-07 17:11
-->
<template>
    <div>
        <!-- 列表 -->
        <dg-table
            border
            ref="baseTable"
            :url="tableUrl"
            :condition="condition"
            :data="data"
            highlight-current-row
            :row-key="rowKey"
            :lazyLoad="lazyLoad"
            :load="load"
            :before-quest="handleBeforeQuest"
            :before-search="handleBeforeSearch"
            @selection-change="handleSelectionChange"
            @select="handleSelect"
            @select-all="handleCheckAll"
            @row-click="handleRowClick"
            v-bind="$attrs"
            v-on="$listeners"
        >
            <dg-table-column v-if="selection" type="selection" reserve-selection width="55" align="center" />
            <dg-table-column type="index" label="序号" width="75" align="center" />
            <template v-for="item in tableHeader">
                <dg-table-column :key="item[rowKey]" v-bind="item" align="center">
                    <template slot-scope="{ row }">
                        <span v-if="item.dateFormat">{{ row[item.prop] | dateFormatter(item.dateFormat) }}</span>
                        <slot v-if="item.custom" v-bind:row="row" :name="item.prop"></slot>
                    </template>
                </dg-table-column>
            </template>
            <slot></slot>
            <!--操作栏-->
            <dg-table-column label="操作" align="center" v-if="tableOptList.length" :width="optColumnWidth">
                <template slot-scope="{ row }">
                    <div class="u-table__operation">
                        <el-tooltip
                            v-for="(item, index) in tableOptList"
                            :key="index"
                            :content="item"
                            effect="dark"
                            placement="top-end"
                        >
                            <i :class="item | optIcon" @click="handleEvent(item, row)"></i>
                        </el-tooltip>
                    </div>
                </template>
            </dg-table-column>
        </dg-table>
    </div>
</template>

<script>
import _ from "lodash"
import DgTable from "@srcPath/components/jz-base/table"

export default {
    mixins: [DgTable],
    props: {
        tableUrl: String,
        tableHeader: Array,
        condition: {
            type: Object,
            default: () => {}
        },
        lazyLoad: {
            type: Boolean,
            default: false
        },
        load: {
            type: Function,
            default: conditions => conditions
        },
        rowKey: {
            type: String,
            default: "id"
        },
        selection: {
            type: Boolean,
            default: false
        },
        // 列表操作
        tableOptList: {
            type: Array,
            default: () => []
        },
        // 操作列宽度
        optColumnWidth: {
            type: [String, Number],
            default: "120"
        },
        // 默认选中的数据
        defaultSelectRows: {
            type: Array,
            default: () => []
        },
        // 设置合并行根据的key
        rowSpanKey: String
    },
    components: {},
    data() {
        return {
            newChooseArr: []
        }
    },
    computed: {},
    watch: {
        defaultSelectRows: {
            immediate: true,
            deep: true,
            handler(val) {
                this.newChooseArr = this.$lodash.cloneDeep(val)
            }
        }
    },
    methods: {
        /**
         * 查询
         */
        handleSearch() {
            this.$refs.baseTable.searchForm()
        },
        /**
         * 清除复选框选中的数据
         */
        handleClearSelection() {
            this.$refs.baseTable.clearAll()
            // this.newChooseArr = [];
        },
        toggleRowSelection(row, selected) {
            this.$refs.baseTable.toggleRowSelection(row, selected)
        },
        handleSelectionChange(data) {
            this.$emit("handleSelectionChange", data)
        },
        //  getReqSearchCondition() {
        //   return this.$refs.baseTable.getReqSearchCondition();
        // },

        handleBeforeSearch(conditions) {
            let searchConditionObj = JSON.parse(conditions.searchCondition)
            let result = []
            for (let i = 0; i < searchConditionObj.length; i++) {
                const { op, value } = searchConditionObj[i]
                if (op == "between" && value[0]) {
                    result.push({ ...searchConditionObj[i], op: ">=", value: value[0] })
                    result.push({ ...searchConditionObj[i], op: "<=", value: value[1] })
                } else {
                    result.push(searchConditionObj[i])
                }
            }
            conditions.searchCondition = JSON.stringify(result)
            conditions.sort = JSON.stringify(this.sortProps)
            return conditions
        },

        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
                return {
                    rowspan: row.rowspan,
                    colspan: 1
                }
            }
        },

        setRowSpans(tableData) {
            // 先给所有的数据都加一个v.rowspan = 1
            tableData.forEach(v => {
                v.rowspan = 1
            })
            // 双层循环
            for (let i = 0; i < tableData.length; i++) {
                // 内层循环，上面已经给所有的行都加了v.rowspan = 1
                // 这里进行判断
                // 如果当前行的id和下一行的id相等
                // 就把当前v.rowspan + 1
                // 下一行的v.rowspan - 1
                for (let j = i + 1; j < tableData.length; j++) {
                    // 此处可根据相同字段进行合并，此处是根据的id
                    if (tableData[i][this.rowSpanKey] === tableData[i][this.rowSpanKey]) {
                        tableData[i].rowspan++
                        tableData[j].rowspan--
                    }
                }
                // 这里跳过已经重复的数据
                i = i + tableData[i].rowspan - 1
            }
            return tableData
        },

        /**
         * 进入页面默认选中设置
         */
        handleBeforeQuest(res) {
            const { content, totalElements } = res.data
            this.currentPageContent = content
            if (this.newChooseArr.length > 0) {
                let rowKeys = []
                for (let j = 0; j < content.length; j++) {
                    const cItem = content[j]
                    const index = this.newChooseArr.findIndex(item => (item[this.rowKey] || item) == cItem[this.rowKey])
                    if (index > -1) {
                        rowKeys.push(this.newChooseArr[index][this.rowKey] || this.newChooseArr[index])
                    }
                }
                setTimeout(() => {
                    this.$refs.baseTable.setCheck(rowKeys)
                }, 500)
            }

            const result = {
                data: {
                    content: this.rowSpanKey ? this.setRowSpans(content) : content,
                    totalElements
                }
            }
            return result
        },
        /**
         * 选中某条数据
         */
        handleSelect(selection, row) {
            let copyAttr = _.cloneDeep(this.newChooseArr)
            const index = this.newChooseArr.findIndex(item => (item[this.rowKey] || item) == row[this.rowKey])
            if (index > -1) {
                copyAttr.splice(index, 1)
            } else {
                copyAttr.push(row)
            }
            this.newChooseArr = copyAttr
            console.log(this.newChooseArr)
        },
        /**
         * 选中/取消选中
         */
        handleCheckAll(selection) {
            const checked = selection.length == 0 ? false : true
            this.currentPageContent.forEach(row => {
                // this.handleSelect([], element);
                let copyAttr = _.cloneDeep(this.newChooseArr)
                const index = this.newChooseArr.findIndex(item => (item[this.rowKey] || item) == row[this.rowKey])
                if (checked) {
                    if (index < 0) {
                        copyAttr.push(row)
                    }
                } else {
                    if (index > -1) {
                        copyAttr.splice(index, 1)
                    }
                }
                this.newChooseArr = copyAttr
            })
            console.log(this.newChooseArr)
        },
        // 发送操作事件类型
        handleEvent(type, row) {
            this.$emit("submitTableOpt", type, row)
        },
        /**
         * 表格某行被点击
         * */
        handleRowClick(row) {
            this.$refs.baseTable.setCurrentRow(row)
            this.$emit("handleRowClick", row)
        }
    },
    created() {},
    mounted() {}
}
</script>

<style lang="scss"></style>
