import { immutable, excludedInJSON, action } from '../decorators';
import { config, history, LEVEL_ENUM, Logic, Variable, ProcessComponent, Schema, ActionOptions } from '..';
import { convert2RefType } from '../data/dataTypeUtils';
import { getBasicTypeDefaultValue } from '../data/basicTypes';
import { schemaService } from '../../service/common';
import processService from '../../service/process';

/**
 * 流程组件局部变量
 */
export class ProcessComponentVariable extends Variable {
    /**
     * 概念类型
     */
    @immutable()
    public readonly level: LEVEL_ENUM = LEVEL_ENUM.processComponentVariable;
    /**
     * 流程组件 Id
     */
    @immutable()
    public readonly parentId: string = undefined;
    /**
     * 流程组件
     */
    @excludedInJSON()
    @immutable()
    public readonly processComponent: ProcessComponent = undefined;
    /**
     * 默认值
     * 按 JSON string 处理
     * - string: 666 -> '666'
     * - string: true -> 'true'
     * - number: 666 -> 666
     * - boolean: true -> true
     */
    public defaultValue: string = undefined;
    /**
     * @param source 需要合并的部分参数
     */
    constructor(source?: Partial<ProcessComponentVariable>) {
        super();
        source && this.assign(source);
    }
    genCode() {
        return `ID_${this.processComponent.process.id}.ID_${this.processComponent.id}.ID_${this.id}`;
    }
    /**
     * 添加流程组件局部变量
     */
    @action('添加流程组件局部变量')
    async create(none?: void, actionOptions?: ActionOptions) {
        config.defaultApp?.emit('saving');

        this.assign({ loading: true, editing: false });
        const body = this.toJSON();
        const result = await processService.addProcessVal({
            headers: {
                appId: config.defaultApp?.id,
                operationAction: actionOptions?.actionName || 'ProcessComponentVariable.create',
                operationDesc: actionOptions?.actionDesc || `添加流程组件"${this.processComponent.name}"局部变量"${this.name}"`,
            },
            body,
        });
        this.assign(ProcessComponentVariable.from(result, this.processComponent));

        await config.defaultApp?.history.load();
        config.defaultApp?.emit('saved');
        return this;
    }
    /**
     * 删除流程组件局部变量
     */
    @action('删除流程组件局部变量')
    async delete(none?: void, actionOptions?: ActionOptions) {
        if (this.id) {
            config.defaultApp?.emit('saving');

            this.assign({ loading: true });
            const body = this.toJSON();
            await processService.deleteProcessVal({
                headers: {
                    appId: config.defaultApp?.id,
                    operationAction: actionOptions?.actionName || 'ProcessComponentVariable.delete',
                    operationDesc: actionOptions?.actionDesc || `删除流程组件"${this.processComponent.name}"局部变量"${this.name}"`,
                },
                body,
            });
            const index = this.processComponent.variables.indexOf(this);
            ~index && this.processComponent.variables.splice(index, 1);
            this.destroy();

            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();
        const result = await processService.updateProcessVal({
            headers: {
                appId: config.defaultApp?.id,
                operationAction: actionOptions?.actionName || 'ProcessComponentVariable.update',
                operationDesc: actionOptions?.actionDesc || `修改流程组件"${this.processComponent.name}"局部变量"${this.name}"`,
            },
            body,
        });
        this.assign(ProcessComponentVariable.from(result, this.processComponent));

        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.processComponent.name}"的局部变量"${oldName}"的名称为"${name}"`,
        });
    }
    /**
     * 设置流程组件局部变量描述
     * @param description 描述
     */
    @action('设置流程组件局部变量描述')
    async setDescription(description: string) {
        this.assign({ description });
        await this.update(undefined, {
            actionDesc: `设置流程组件"${this.processComponent.name}"的局部变量"${this.name}"的描述为"${description}"`,
        });
    }
    /**
     * 设置流程组件局部变量的数据类型
     * @param $ref 数据类型
     */
    @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.processComponent.name}"的局部变量"${this.name}"的数据类型为"${this.schema.typeKey}"`,
            });
            this.genSchemaChildren();
            this.processComponent.process.checkType();
        } 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.processComponent.name}"的局部变量"${this.name}"${isArray ? '为' : '不为'}列表`,
        });
        this.genSchemaChildren();
    }
    /**
     * 设置流程组件局部变量的默认值
     * @param defaultValue 默认值
     */
    @action('设置流程组件局部变量的默认值')
    async setDefaultValue(defaultValue: string) {
        this.assign({ defaultValue });
        await this.update(undefined, {
            actionDesc: `设置流程组件"${this.processComponent.name}"的局部变量"${this.name}"的默认值为"${defaultValue}"`,
        });
    }
    /**
     * 查找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: 'process_component_variable',
                },
            });
            return result;
        }
    }
    /**
     * 从后端 JSON 生成规范的 ProcessComponentVariable 对象
     */
    public static from(source: any, processComponent: ProcessComponent | Logic) {
        convert2RefType(source.schema);
        source.processComponent = processComponent;
        source.parentId = processComponent.id;
        source.code = `ID_${(processComponent as ProcessComponent).process.id}.ID_${processComponent.id}.ID_${source.id}`;
        const processComponentVariable = new ProcessComponentVariable(source);
        processComponentVariable.genSchemaChildren();
        return processComponentVariable;
    }
}

export default ProcessComponentVariable;
