<template>
    <Card ref="card" :bordered="false" :padding="0" dis-hover>
        <!-- 如果myConfig.modetype为1，则显示 -->
        <template v-if="myConfig.modetype === '1'">
            <!-- 如果showTitle为true，则显示 -->
            <p v-if="showTitle" @click="toggle" style="cursor: pointer">
                <Row
                    type="flex"
                    justify="start"
                    align="middle"
                    style="margin-top: 14px; margin-bottom: 14px"
                >
                    <!-- 如果showGrid为true，则显示icon-custom-pack，否则显示icon-custom-spread -->
                    <Icon
                        custom="iconfont icon-custom-pack"
                        color="#f3b352"
                        v-show="showGrid"
                        size="14"
                    />
                    <Icon
                        v-show="!showGrid"
                        color="#f3b352"
                        custom="iconfont icon-custom-spread"
                        size="14"
                    />
                    <!-- 显示myConfig.title -->
                    <span
                        style="
                            margin-left: 10px;
                            font-size: 14px;
                            font-weight: bold;
                        "
                        v-text="myConfig.title"
                    />
                </Row>
            </p>
            <!-- 显示分割线 -->
            <Divider
                style="margin-left: 24px; margin-top: 0px; margin-bottom: 10px"
            />
        </template>
        <!-- 如果myConfig.modetype为2，则显示 -->
        <template v-if="myConfig.modetype === '2'">
            <div v-if="showTitle" style="margin-bottom: 10px">
                <span class="efuture-title-verticalline" /><span
                    style="font-size: 14px; font-weight: bold"
                    v-text="myConfig.title"
                />
            </div>
        </template>
        <div :style="divStyle">
            <!-- <div v-if="$slots.header">
                <slot name="header"></slot>
            </div> -->
            <!-- <Row
                v-else
                v-show="showGrid"
                type="flex"
                justify="start"
                align="middle"
                :gutter="0"
                style="margin-bottom: 10px"
            >
                <Col v-if="showAddBtn">
                    <Button
                        :style="btnStyle"
                        customIcon="iconfont icon-custom-rowadd3"
                        type="text"
                        :disabled="myConfig.readOnly"
                        @click="handleAddRow"
                        >添加</Button
                    >
                </Col>
                <Col v-if="showAddBtn && showDelBatchBtn">
                    <Divider type="vertical" style="margin: 0 6px 0 6px" />
                </Col>
                <Col v-if="showDelBatchBtn">
                    <Button
                        :style="btnStyle"
                        customIcon="iconfont icon-custom-rowdel3"
                        type="text"
                        :disabled="myConfig.readOnly"
                        @click="delBatchRow"
                        >删除</Button
                    >
                </Col>
            </Row> -->
            <Row v-show="showGrid" style="width: 100%">
                <!-- 编辑表格 覆写开始 -->
                <vxe-grid
                    ref="table"
                    keep-source
                    border="full"
                    style="width: 100%"
                    :columns="RewriteColumns"
                    :data="dataList"
                    :height="tableHeight"
                    :max-height="tableMaxHeight + 100"
                    :loading="loading"
                    :sort-config="{ remote: true, trigger: 'cell' }"
                    :valid-config="{
                        showMessage: false,
                        autoClear: false,
                    }"
                    :editConfig="editConfig"
                    :edit-rules="validRules"
                    :show-footer="showFooter"
                    :footer-method="footerMethod"
                    :footer-cell-class-name="footerCellClassName"
                    :toolbar-config="toolbarConfig"
                    :keyboard-config="VG_keyboardConfig"
                    :mouse-config="VG_mouseConfig"
                    @sort-change="RewriteTableOnSortChange"
                    @cell-dblclick="RewriteTableCellDBlclick"
                    @edit-activated="VG_editActivated"
                    @keydown="VG_keydown"
                >
                    <!-- 操作面板插槽 -->
                    <template #toolbar_buttons>
                        <Row
                            v-show="showGrid"
                            type="flex"
                            justify="start"
                            align="middle"
                            :gutter="0"
                        >
                            <Col v-if="showAddBtn">
                                <Button
                                    :style="btnStyle"
                                    customIcon="iconfont icon-custom-rowadd3"
                                    type="text"
                                    :disabled="myConfig.readOnly"
                                    @click="handleAddRow"
                                    >添加</Button
                                >
                            </Col>
                            <Col v-if="showAddBtn && showDelBatchBtn">
                                <Divider
                                    type="vertical"
                                    style="margin: 0 6px 0 6px"
                                />
                            </Col>
                            <Col v-if="showDelBatchBtn">
                                <Button
                                    :style="btnStyle"
                                    customIcon="iconfont icon-custom-rowdel3"
                                    type="text"
                                    :disabled="myConfig.readOnly"
                                    @click="delBatchRow"
                                    >删除</Button
                                >
                            </Col>
                        </Row>
                    </template>

                    <!-- 编辑列插槽 -->
                    <template #columnEdit="{ row, rowIndex, columnIndex }">
                        <BillInfoPanelEditTableControlbox
                            :autofocus="true"
                            :config="getTableColumnConfig(columnIndex)"
                            :valueData="row"
                            :editIndex="rowIndex"
                            @inputValue="
                                (params) => {
                                    cellInput({ params, row });
                                }
                            "
                            @doAction="doAction"
                        ></BillInfoPanelEditTableControlbox>
                    </template>
                </vxe-grid>
                <!-- 编辑表格 覆写结束 -->
                <div
                    ref="page"
                    v-if="myConfig.showPage"
                    style="background: #eee; padding-top: 5px; width: 100%"
                >
                    <Card
                        :bordered="false"
                        :padding="0"
                        :dis-hover="true"
                        style="border-radius: 0px"
                    >
                        <Row
                            type="flex"
                            justify="end"
                            style="padding: 5px; padding-right: 10px"
                        >
                            <Page
                                :total="myConfig.pageConfig.total_results"
                                :size="myConfig.pageSize"
                                :current="myConfig.pageConfig.page_no"
                                :page-size="myConfig.pageConfig.page_size"
                                :page-size-opts="
                                    myConfig.pageConfig.pageSizeList
                                "
                                @on-page-size-change="changePageSize"
                                @on-change="changePage"
                                :show-total="myConfig.pageShowTotal"
                                :show-elevator="myConfig.pageShowElevator"
                                :show-sizer="myConfig.pageShowSizer"
                            ></Page>
                        </Row>
                    </Card>
                </div>
            </Row>
            <p
                v-show="showGrid && showEffectValue"
                @click="toggleEffect"
                style="
                    cursor: pointer;
                    background-color: #fff2de;
                    height: 36px;
                    line-height: 36px;
                    border: 1px solid #f3b352;
                    margin-top: 10px;
                "
            >
                <Icon
                    custom="iconfont icon-custom-help"
                    size="20"
                    style="margin-left: 10px"
                    color="#D5882E"
                />
                <span style="margin-left: 4px; color: #d5882e">参考数据</span>
            </p>
            <Row
                v-show="showGrid && showEffectValue && showEffectGrid"
                class="efuture-effect-grid"
                style="margin-top: 10px"
            >
                <Table
                    ref="effect_table"
                    :row-class-name="rowClassName"
                    :loading="loading"
                    :size="myConfig.tableSize"
                    :border="myConfig.showBorder"
                    :stripe="myConfig.showStripe"
                    :maxHeight="tableMaxHeight"
                    :columns="tableColumns"
                    :data="curlEffectData"
                    @on-column-width-resize="onColumnWidthResize"
                >
                    <template
                        v-for="config in soltTableColumns"
                        v-slot:[config.key]="{ row, index }"
                        :key="'show_effect' + config.key"
                    >
                        <ShowText
                            :label="effectFormatValue(index, config, row)"
                            :contentAlign="config.contentAlign"
                            :class="config.cellClassName"
                            :config="config"
                            :rowIndex="index"
                        ></ShowText>
                    </template>
                </Table>
            </Row>
        </div>
        <Modal
            v-if="!editRowFlag"
            v-model="showEditRowForm"
            width="90%"
            title="编辑"
            @on-ok="editRow"
        >
            <div>
                <ExpandRow
                    ref="rowForm"
                    :config="myConfig"
                    :dictData="dictData"
                />
            </div>
        </Modal>
    </Card>
</template>
<script>
import editgridcard from "../editgridcard.vue";
import BillInfoPanelEditTableControlbox from "./BillInfoPanelEditTableControlbox.vue";
import useVxeGridEditTypeKeydownEventHook from "./mixins/useVxeGridEditTypeKeydownEventHook.js";

export default {
    name: "BillInfoPanelEditTable",
    extends: editgridcard,
    components: { BillInfoPanelEditTableControlbox },
    mixins: [useVxeGridEditTypeKeydownEventHook],
    data() {
        return {
            editType: false,
            editConfig: {
                trigger: "click",
                mode: "cell",
                autoClear: false,
                beforeEditMethod: (params) => {
                    const { column, row, rowIndex } = params;
                    if (this.editType) {
                        return false;
                    }
                    if (this.myConfig.cellbeginedit) {
                        return this.myConfig.cellbeginedit({
                            column: { ...column, name: column.property },
                            row: row,
                            rowIndex: rowIndex,
                            transmission: params,
                        });
                    }
                    return true;
                },
            },
            dataList: [],
        };
    },
    computed: {
        /**
         * 表格列定义清洗
         */
        RewriteColumns() {
            // console.log("this.tableColumns", this.tableColumns);
            const newColumns = this.tableColumns.map((item) => {
                const columnsItemType = this.getColumnsItemType(item.key);
                return {
                    ...(item.title && {
                        title: item.title,
                    }),
                    ...(item.name && {
                        field: item.name,
                    }),
                    ...(item.width && {
                        width: item.width < 60 ? 60 : item.width,
                    }),
                    ...(item.minWidth && {
                        minWidth: item.minWidth < 60 ? 60 : item.minWidth,
                    }),
                    ...(item.align && {
                        align: item.align,
                    }),
                    ...(item.resizable && {
                        resizable: item.resizable,
                    }),
                    sortable: false,
                    ...(columnsItemType && {
                        type: columnsItemType,
                        sortable: false,
                    }),
                    formatter: (params) => {
                        const { row, cellValue } = params;
                        const valueFormat = this.$Method.formatValue(
                            cellValue,
                            row,
                            item
                        );
                        return valueFormat;
                    },
                    editRender: {
                        enabled: false,
                        defaultValue: item.defaultValue || "",
                    },
                    ...(item.isFilters && {
                        filters: [{ data: null }],
                        filterRender: {
                            name: "FilterInput",
                        },
                    }),
                    ...(!item.readOnly &&
                        !columnsItemType && {
                            editRender: {
                                enabled: true,
                                autoselect: this.$utils.get(
                                    item,
                                    "autoselect",
                                    false
                                ),
                                autofocus: this.$utils.get(
                                    item,
                                    "autofocus",
                                    ""
                                ),
                                defaultValue: item.defaultValue || "",
                            },
                            slots: { edit: "columnEdit" },
                        }),
                };
            });
            // console.log("newColumns:", newColumns);
            return newColumns;
        },
        /**
         * 表格数据
         */
        validRules() {
            return this.$utils.reduce(
                this.tableColumns,
                (previous, item) => {
                    const columnsItemType = this.getColumnsItemType(item.key);
                    if (!columnsItemType) {
                        if (item.required) {
                            previous[item.name] = [
                                {
                                    required: true,
                                    message: `${item.label}必填`,
                                },
                            ];
                        }
                    }
                    return previous;
                },
                {}
            );
        },
        /**
         * 是否显示合计
         */
        showFooter() {
            const showType = this.myConfig.showSummary;
            return showType;
        },
        sumFields() {
            return this.tableColumns
                .filter((item) => item.summary)
                .map((item) => item.name);
        },
        toolbarConfig() {
            // console.log("this.myConfig", this.myConfig);
            return {
                zoom: this.myConfig.zoom,
                slots: {
                    // 自定义插槽模板
                    buttons: "toolbar_buttons",
                },
            };
        },
    },
    methods: {
        // ==================================================================

        /**
         * 【覆写】编辑项触发回车事件
         */
        enterKeyDown() {
            const $table = this.$refs.table;
            this.VG_keyCode13Event($table);
        },

        /**
         * 【覆写】手工触发编辑事件
         */
        valueChanged(obj) {
            const column = this.findColumnConfig(obj.name, this.myConfig.items);
            this.addRowInfo(obj, column);
            const valueChangedSucc = column.valueChanged(obj);
            this.updateFooterEvent();
            return valueChangedSucc;
        },
        setDataBefore(obj, that) {
            const column = this.findColumnConfig(
                that.myConfig.name,
                this.myConfig.items
            );
            let temp = {};
            temp.data = obj;
            temp.tabname = this.myConfig.name;
            this.addRowInfo(temp, column);
            const setDataBeforeSucc = column.setDataBefore(temp, that);
            this.updateFooterEvent();
            return setDataBeforeSucc;
        },

        /**
         * 【覆写】获取全量数据
         */
        getData() {
            const $table = this.$refs.table;
            return $table.getTableData().fullData;
        },

        /**
         * 【覆写】获取增量变更数据事件
         * 临时方案，待优化封装
         */
        getChangeData() {
            // console.log("我猜测到这里了获取变更数据");
            // this.$utils
            // this.$refs.table
            const $table = this.$refs.table;
            const keyField = "_X_ROW_KEY";
            // 获取编辑分组数据
            const { insertRecords, removeRecords, updateRecords } =
                $table.getRecordset();
            // 数据整理
            const reportconds = [
                ...removeRecords.map((item) => {
                    const itemFilterByKeyField = this.$utils.omit(
                        item,
                        keyField
                    );
                    return {
                        ...itemFilterByKeyField,
                        flag: item.flag || "D",
                    };
                }),
                ...updateRecords.map((item) => {
                    const itemFilterByKeyField = this.$utils.omit(
                        item,
                        keyField
                    );
                    return {
                        ...itemFilterByKeyField,
                        flag: item.flag || "U",
                    };
                }),
                ...insertRecords.map((item) => {
                    const itemFilterByKeyField = this.$utils.omit(
                        item,
                        keyField
                    );
                    return {
                        ...itemFilterByKeyField,
                        flag: item.flag || "I",
                    };
                }),
            ];
            // 排序字段处理逻辑
            const sortFieldName = "browno";
            const reportcondsGroupBy_Flag = this.$utils.groupBy(
                reportconds,
                "flag"
            );
            const reportcondsGroup_I = this.$utils.get(
                reportcondsGroupBy_Flag,
                "I",
                []
            );
            const reportcondsGroup_U = this.$utils.get(
                reportcondsGroupBy_Flag,
                "U",
                []
            );
            const reportcondsGroup_D = this.$utils.get(
                reportcondsGroupBy_Flag,
                "D",
                []
            );
            const fullData = $table.getTableData().fullData;
            const maxItem = this.$utils.max(fullData, sortFieldName);
            let serialidMaxSub = 1;
            if (maxItem) {
                serialidMaxSub = this.$utils.add(maxItem[sortFieldName], 1);
            }
            const insertRecordsForSortNum = reportcondsGroup_I.map((item) => {
                const f_item = { ...item };
                f_item[sortFieldName] = serialidMaxSub;
                serialidMaxSub = this.$utils.add(serialidMaxSub, 1);
                return f_item;
            });
            // 最终返回结果转换拼接返回
            const flagDataList = [
                ...insertRecordsForSortNum,
                ...reportcondsGroup_U,
                ...reportcondsGroup_D,
            ];
            return flagDataList;
        },

        /**
         * 覆写表格必填项校验
         */
        async tableCheckValidate() {
            const $tableVM = this.$refs.table;
            const errMap = await $tableVM.validate(true);
            return errMap ? true : false;
        },

        /**
         *  覆写增行事件
         */
        async handleAddRow() {
            const $tableVM = this.$refs.table;
            let rowData = null;
            if (this.myConfig.addRowBefore) {
                let temp = {};
                temp.name = this.myConfig.name;
                temp.grid = $tableVM;
                rowData = this.myConfig.addRowBefore(temp);
                if (rowData === false) {
                    return;
                }
            }
            if (!rowData || rowData === true) {
                rowData = {};
            }
            const errMap = await $tableVM.validate(true);
            if (errMap) {
                return false;
            }
            const { row: newRow } = await $tableVM.insertAt(rowData, -1);
            // 后续完善
            const tableColumns = $tableVM.getTableColumn();
            const visibleColumns = this.$utils.get(
                tableColumns,
                "visibleColumn",
                []
            );
            const column = this.$utils.find(visibleColumns, (column) => {
                return (
                    column &&
                    column.editRender &&
                    column.editRender.enabled !== false
                );
            });
            await $tableVM.setEditRow(newRow, false);
        },

        /**
         *  覆写选择删行事件
         */
        delBatchRow() {
            const $tableVM = this.$refs.table;
            $tableVM.removeCheckboxRow();
        },

        /**
         * 【覆写】表格数据赋值事件
         */
        setData(data = [], flag = "set") {
            switch (flag) {
                case "set":
                    // console.log("初始化表格数据触发");
                    this.dataList = [...data];
                    break;

                case "I":
                    // console.log("手工全量编辑触发");
                    const $tableVM = this.$refs.table;
                    // 移除表格组件
                    $tableVM.remove().then(() => {
                        $tableVM.insertAt([...data], -1);
                    });
                    break;

                default:
                    break;
            }
        },

        /**
         * 【覆写】编辑项内容整理透传
         */
        addRowInfo(obj, column) {
            const $tableVM = this.$refs.table;
            let editRecord = $tableVM.getEditRecord();
            if (!editRecord) {
                editRecord = this.VG_currentEditRecord;
            }
            obj.rowinfo = { ...editRecord, index: editRecord.rowIndex };
        },

        /**
         * 【覆写】手工更新当前编辑项事件
         */
        updataRow(editRecord, item) {
            const { row, $table } = editRecord;
            $table.setRow(row, item);
        },
        addRow(item) {
            const $tableVM = this.$refs.table;
            $tableVM.insertAt(item, -1);
        },
        delRow(editRecord) {
            const { row } = editRecord;
            const $tableVM = this.$refs.table;
            $tableVM.remove(row);
        },

        /**
         * 【覆写】获取多选数据事件
         */
        getSelection() {
            const selectDataList = this.$refs.table.getCheckboxRecords(true);
            return [...selectDataList];
        },

        /**
         * 【覆写】更改编辑状态事件
         */
        setReadOnly(value) {
            let obj = {};
            obj.readOnly = value;
            if (this.config.showCheckBox !== false) {
                if (obj.readOnly) {
                    obj.showCheckBox = false;
                } else {
                    obj.showCheckBox = true;
                }
            }
            this.editType = value;
            this.setPro(obj);
        },

        // ==================================================================

        /**
         * 在值发生改变时更新表尾合计
         */
        updateFooterEvent() {
            const $tableVM = this.$refs.table;
            $tableVM.updateFooter();
        },

        footerCellClassName() {
            return "efu-stable-footer-row";
        },

        footerMethod(params) {
            const { columns, data } = params;
            const sumSub = this.editType ? 1 : 2;
            return [
                columns.map((item, index) => {
                    if (index === sumSub) {
                        return "合计";
                    }
                    if (this.sumFields.includes(item.field)) {
                        const sumData = this.handleSumField({
                            list: data,
                            field: item.field,
                        });
                        const columnConfig = this.getTableColumnConfig(index);
                        const format = this.$utils.get(
                            columnConfig,
                            "format",
                            null
                        );
                        const notzero = this.$utils.get(
                            columnConfig,
                            "notzero",
                            null
                        );
                        const formatSumData = this.$Method.formatNumber(
                            sumData,
                            format,
                            notzero
                        );
                        return formatSumData;
                    }
                    return null;
                }),
            ];
        },

        handleSumField(params) {
            const { list, field } = params;
            let count = 0;
            list.forEach((item) => {
                count = this.$utils.add(count, item[field]);
            });
            return count;
        },

        getTableColumnConfig(index) {
            let column = this.tableColumns[index];
            if (column.type === "NumberBox") {
                column.place = "unset";
            }
            return this.tableColumns[index];
        },

        cellInput({ params, row }) {
            row[params.name] = params.value;
        },

        batchUpdateRows(dataList = []) {
            if (this.$utils.isEmpty(dataList)) return false;
            const $tableVM = this.$refs.table;
            const editRecord = $tableVM.getEditRecord();
            if (editRecord) {
                $tableVM.remove(editRecord.row);
            }
            $tableVM.insertAt(dataList, -1);
        },

        /**
         * 批量更新数据【待完善】
         */
        batchUpdateDatas(record = {}) {
            const $tableVM = this.$refs.table;
            const tableData = $tableVM.getTableData().fullData;
            tableData.forEach((item) => Object.assign(item, record));
        },

        /**
         * 清除表格数据数据
         */
        clearData() {
            // 获取表格组件的实例
            const $tableVM = this.$refs.table;
            // 移除表格组件
            $tableVM.remove();
        },

        /**
         * 表格列 type 类型转义
         */
        getColumnsItemType(key) {
            const columnsItemType = {
                selection: "checkbox",
                index: "seq",
            };
            return this.$utils.get(columnsItemType, key, null);
        },

        /**
         * 表格排序事件
         */
        RewriteTableOnSortChange(params) {
            const { order, field } = params;
            const orderType = order ? order : "normal";
            this.sortChagne({ order: orderType, key: field });
        },

        /**
         * 表格双击事件
         */
        RewriteTableCellDBlclick(params) {
            const { row } = params;
            this.dbclick(row);
        },

        handleZoom() {
            const $tableVM = this.$refs.table;
            $tableVM.zoom();
        },
    },
    mounted() {
        // console.log("我继承覆写了999999");
    },
};
</script>

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