import { deepCopy, IParam, isExistAndNotEmpty, IActionParam } from "@core";
import { ListControlState } from "./list-control-state";
import { MDControl } from "../md-control";

/**
 * @description 列表部件
 * @export
 * @class ListControl
 * @extends {MDControl}
 */
export class ListControl extends MDControl {

    /**
     * @description 部件状态
     * @type {ListControlState}
     * @memberof ListControl
     */
    public declare state: ListControlState;

    /**
     * @description 处理状态变化
     * @memberof ListControl
     */
    public handleStateChange() {
        // 计算列表数据界面行为权限
        const { items, uIActions } = toRefs(this.state);
        if (items.value.length > 0 && uIActions.value && Object.keys(uIActions.value).length > 0) {
            Object.keys(uIActions.value).forEach((key: string) => {
                const tempActionModel = uIActions.value[key];
                items.value.forEach((item: any) => {
                    Object.assign(item, { [key]: this.getActionAuthState(item, [tempActionModel]) });
                });
            })
        }
        //  清空选中数据，避免多次加载选中效果异常
        this.state.selections = [];
        // 处理分组
        this.handleDataGroup();
        // 处理默认选中
        this.handleDefaultSelect();
    }

    /**
     * @description 自动分组
     * @protected
     * @memberof ListControl
     */
    protected autoGroupData() {
        const { groupField } = this.state.mdCtrlGroup;
        const { items } = toRefs(this.state);
        if (!items.value || items.value.length === 0) {
            return;
        }
        //  所有的分组值
        const groupValueMap: string[] = [];
        items.value.forEach((item: IParam) => {
            if (isExistAndNotEmpty(item[groupField]) && !groupValueMap.includes(item[groupField])) {
                groupValueMap.push(item[groupField]);
            }
        });
        if (groupValueMap.length) {
            const listData: IParam[] = [];
            groupValueMap.forEach((value: string, index: number) => {
                const children: IParam[] = [];
                items.value.forEach((item: IParam) => {
                    if (item[groupField] === value) {
                        children.push(item);
                    }
                });
                listData.push({
                    srfmajortext: value,
                    type: 'GROUP',
                    expanded: false,
                    children: children
                });
            })
            items.value = listData;
        }
    }

    /**
     * @description 代码表分组
     * @protected
     * @memberof ListControl
     */
    protected async codeListGroupData() {
        const { groupCodeList, groupField } = this.state.mdCtrlGroup;
        if (!groupCodeList) {
            App.getNotificationService().warning({
                message: '警告',
                description: '未配置分组代码表'
            });
            return;
        }
        const { context, viewParams } = this.state;
        const { items } = toRefs(this.state);
        const codeListService = App.getCodeListService();
        let codeListItems: IParam[] = [];
        try {
            codeListItems = await codeListService.getCodeListItems({
                tag: groupCodeList.codeListTag,
                context,
                viewParams
            });
        } catch(error) {
            console.warn(`分组代码表 ${groupCodeList.codeListTag} 获取数据项异常`);
        }
        if (codeListItems.length) {
            const listData: IParam[] = [];
            codeListItems.forEach((codeListItem: IParam, index: number) => {
                const children: IParam[] = [];
                items.value.forEach((item: IParam) => {
                    if (item[groupField] === codeListItem.value) {
                        children.push(item);
                    }
                });
                listData.push({
                    srfmajortext: codeListItem.text,
                    type: 'GROUP',
                    expanded: false,
                    children: children
                });
            });
            const otherGroupItems: IParam[] = [];
            items.value.forEach((item: IParam) => {
                if (codeListItems.findIndex((codeListItem: IParam) => codeListItem.value === item[groupField]) === -1) {
                    otherGroupItems.push(item);
                }
            });
            if (otherGroupItems.length) {
                listData.push({
                    srfmajortext: '其他',
                    type: 'GROUP',
                    expanded: false,
                    children: otherGroupItems
                });
            }
            items.value = listData;
        }
    }

    /**
     * @description 默认选中
     * @private
     * @memberof ListControl
     */
    private handleDefaultSelect() {
        const { selectFirstDefault } = this.state;
        const { selections, items } = toRefs(this.state);
        if (selectFirstDefault) {
            if (items.value && items.value.length > 0) {
                selections.value.push(items.value[0]);
                this.emit("ctrlEvent", {
                    tag: this.props.name,
                    action: "selectionChange",
                    data: [items.value[0]],
                });
            }
        }
    }

    /**
     * @description 触发界面行为
     * @protected
     * @param {IParam} item 列表数据
     * @param {IParam} action 界面行为
     * @param {MouseEvent} event 鼠标源事件
     * @memberof ListControl
     */
    protected onUIAction(item: IParam, action: IParam, event: MouseEvent) {
        if (!item || !action) {
            console.warn("行为执行参数不足");
            return;
        }
        const inputParam = {
            context: this.state.context,
            viewParams: this.state.viewParams,
            data: [item],
            event: event,
            actionEnvironment: this
        };
        // 执行行为
        App.getAppActionService().execute(action, inputParam);
    }

    /**
     * @description 使用自定义模块
     * @protected
     * @return {*} 
     * @memberof ListControl
     */
    protected useCustom() {
        /**
         * 列表项选中
         * @param item 
         * @param event 
         */
        const onListItemSelected = (item: IParam, event: MouseEvent) => {
            const { isMultiple } = this.state;
            const { selections } = toRefs(this.state);
            const index = selections.value.findIndex((selection: any) => selection.srfkey === item.srfkey);
            //  存在选中则删除
            if (index !== -1) {
                selections.value.splice(index, 1);
            } else {
                //  单选清空已选中
                if (!isMultiple) {
                    selections.value.splice(index, selections.value.length);
                }
                selections.value.push(item);
            }
            this.emit('ctrlEvent', { tag: this.props.name, action: 'selectionChange', data: selections.value });
        }

        /**
         * 是否选中
         * @param item 列表项
         * @returns 
         */
        const isSelected = (item: IParam): boolean => {
            const { selections } = toRefs(this.state);
            return selections.value.findIndex((selection: any) => selection.srfkey === item.srfkey) !== -1;
        }

        /**
         * 加载更多
         * @param event 
         */
        const loadMore = (event: MouseEvent) => {
            const { mdCtrlPaging } = this.state;
            let { current, pageSize } = mdCtrlPaging;
            current += 1;
            this.load();
        }
        return {
            onListItemSelected: onListItemSelected.bind(this),
            isSelected: isSelected.bind(this),
            loadMore: loadMore.bind(this)
        }
    }

    /**
     * @description 安装部件所有功能模块的方法
     * @return {*} 
     * @memberof ListControl
     */
    public moduleInstall() {
        const superParams = super.moduleInstall();
        return {
            ...superParams,
            onUIAction: this.onUIAction.bind(this),
            useCustom: this.useCustom()
        }
    }

}