import { immutable, excludedInJSON, action } from '../decorators';
import { history, utils, LEVEL_ENUM, Logic, Param, Schema, config, ActionOptions } from '..';
import { convert2RefType, convert2SchemaType } from '../data/dataTypeUtils';
import { getBasicTypeDefaultValue } from '../data/basicTypes';
import { viewService } from '../../service/page';
import { View } from './View';
import { schemaService } from '../../service/common';

/**
 * 页面输入参数
 */
export class ViewParam extends Param {
    /**
     * 概念类型
     */
    @immutable()
    public readonly level: LEVEL_ENUM = LEVEL_ENUM.param;
    /**
     * 页面
     */
    @excludedInJSON()
    @immutable()
    public readonly view: View = undefined;
    /**
     * 默认值
     * 按 JSON string 处理
     * - string: 666 -> '666'
     * - string: true -> 'true'
     * - number: 666 -> 666
     * - boolean: true -> true
     */
    public defaultValue: string = undefined;
    /**
     * @param source 需要合并的部分参数
     */
    constructor(source?: Partial<ViewParam>) {
        super();
        source && this.assign(source);
    }
    /**
     * 添加页面输入参数
     */
    @action('添加页面输入参数')
    async create(none?: void, actionOptions?: ActionOptions) {
        config.defaultApp?.emit('saving');

        const body = this.toJSON('', ['ideVersion', 'editable']);
        // convert2SchemaType(body.schema);
        utils.logger.debug('添加页面输入参数', body);

        body.viewId = this.view.id;
        const result: ViewParam = await viewService.createViewParam({
            headers: {
                appId: config.defaultApp?.id,
                operationAction: actionOptions?.actionName || 'ViewParam.create',
                operationDesc: actionOptions?.actionDesc || `添加页面"${this.view.name}"输入参数"${this.name}"`,
            },
            body,
        });
        // convert2RefType(result.schema);
        this.deepPick(result, ['id']);
        this.assign({ code: this.genCode() });

        if (this.view) {
            this.view.page.service.emit('pageTreeChange');
            this.view.emit('change');
        }

        await config.defaultApp?.history.load();
        config.defaultApp?.emit('saved');
        return this;
    }
    /**
     * 删除页面输入参数
     */
    @action('删除页面输入参数')
    async delete(none?: void, actionOptions?: ActionOptions) {
        config.defaultApp?.emit('saving');

        if (this.id) {
            try {
                await viewService.deleteViewParam({
                    headers: {
                        appId: config.defaultApp?.id,
                        operationAction: actionOptions?.actionName || 'ViewParam.delete',
                        operationDesc: `删除页面"${this.view.name}"输入参数"${this.name}"`,
                    },
                    query: {
                        id: this.id,
                    },
                });
            } catch(err) {
                await config.defaultApp?.history.load();
                throw err;
            }
        }

        const { params } = this.view.$def;
        const pos = params.indexOf(this);
        if (pos >= 0)
            params.splice(pos, 1);

        this.destroy();
        if (this.view) {
            this.view.page.service.emit('pageTreeChange');
            this.view.emit('change');
        }

        await config.defaultApp?.history.load();
        config.defaultApp?.emit('saved');
    }
    /**
     * 修改页面输入参数
     */
    async update(none?: void, actionOptions?: ActionOptions, then?: () => Promise<any>) {
        config.defaultApp?.emit('saving');

        const body = this.toJSON();
        delete body.ideVersion;
        delete body.editable;
        // convert2SchemaType(body.schema);
        utils.logger.debug('修改页面输入参数', body);

        body.viewId = this.view.id;
        const result = await viewService.updateViewParam({
            headers: {
                appId: config.defaultApp?.id,
                operationAction: actionOptions?.actionName || 'ViewParam.update',
                operationDesc: actionOptions?.actionDesc || `修改页面"${this.view.name}"输入参数"${this.name}"`,
            },
            body,
        });
        // convert2RefType(result.schema);
        // this.plainAssign(result);

        await then?.();
        await config.defaultApp?.history.load();
        config.defaultApp?.emit('saved');
        return this;
    }
    /**
     * 设置页面输入参数名称
     * @param name 名称
     */
    @action('设置页面输入参数名称')
    async setName(name: string) {
        const oldName = this.name;
        this.assign({ name });
        await this.update(undefined, {
            actionDesc: `设置页面"${this.view.name}"的输入参数"${oldName}"的名称为"${name}"`,
        });

        if (this.view) {
            this.view.page.service.emit('pageTreeChange');
            this.view.emit('change');
        }
    }
    /**
     * 设置页面输入参数描述
     * @param description 描述
     */
    @action('设置页面输入参数描述')
    async setDescription(description: string) {
        this.assign({ description });
        await this.update(undefined, {
            actionDesc: `设置页面"${this.view.name}"的输入参数"${this.name}"的描述为"${description}"`,
        });
    }
    /**
     * 查找schema 顶点被引用的逻辑顶点列表
     */
    async getSchemaUsage() {
        if (this.schema) {
            const schemaId = this.schema.type === 'genericType' ? this.id : this.schema.id;
            const result = await schemaService.getSchemaUsage({
                query: {
                    schemaId,
                    valSource: 'view_param',
                },
            });
            return result;
        }
    }
    /**
     * 设置页面输入参数的数据类型
     */
    @action('设置页面输入参数的数据类型')
    async setDataType(schema: Schema) {
        // 用于update失败后还原数据
        const originalData = {
            schema: Object.assign({}, this.schema),
            defaultValue: this.defaultValue,
        };
        Object.assign(this.schema, {
            $ref: undefined, //引用到Entity或者structure
            type: undefined,
            format: undefined,
            typeInstantiation: undefined,
        });
        Object.assign(this.schema, schema);
        this.assign({ defaultValue: getBasicTypeDefaultValue() });
        try {
            await this.update(undefined, {
                actionDesc: `设置页面"${this.view.name}"的输入参数"${this.name}"的数据类型为"${this.schema.typeKey}"`,
            });
            this.genSchemaChildren();

            if (this.view) {
                this.view.page.service.emit('pageTreeChange');
                this.view.emit('change');
            }
        } catch (err) {
            this.assign(originalData);
            config.defaultApp?.emit('saved');
            throw err;
        }
    }
    /**
     * 设置页面输入参数是否为列表
     * @param isArray
     */
    @action('设置页面输入参数是否为列表')
    async setAsList(isArray: boolean) {
        this.schema.isArray = isArray;
        this.assign({ defaultValue: getBasicTypeDefaultValue() });

        await this.update(undefined, {
            actionDesc: `设置页面"${this.view.name}"的输入参数"${this.name}"${isArray ? '为' : '不为'}列表`,
        });
        this.genSchemaChildren();

        if (this.view) {
            this.view.page.service.emit('pageTreeChange');
            this.view.emit('change');
        }
    }
    /**
     * 设置页面输入参数的默认值
     */
    @action('设置页面输入参数的默认值')
    async setDefaultValue(defaultValue: string) {
        this.assign({ defaultValue });
        await this.update(undefined, {
            actionDesc: `设置页面输入参数的默认值`,
        });

        if (this.view) {
            this.view.page.service.emit('pageTreeChange');
            this.view.emit('change');
        }
    }
    /**
     * 从后端 JSON 生成规范的 ViewParam 对象
     */
    public static from(source: any, view: View | Logic) {
        convert2RefType(source.schema);
        source.view = view;
        source.code = 'ID_' + source.id;
        const viewParam = new ViewParam(source);
        viewParam.genSchemaChildren();
        return viewParam;
    }
}

export default ViewParam;
