searchform-control-base.tsx 16.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
import { IPSApplication, IPSAppUtil, IPSControlHandler } from '@ibiz/dynamic-model-api';
import { EditFormControlBase } from './editform-control-base';
import moment from 'moment';
import { debounce, GetModelService, LogUtil, SearchFormControlInterface, Util } from 'ibiz-core';
import { CodeListTranslator } from '../app-service';
/**
 * 搜索表单部件基类
 *
 * @export
 * @class SearchFormControlBase
 * @extends {EditFormControlBase}
 */
export class SearchFormControlBase extends EditFormControlBase implements SearchFormControlInterface {

    /**
     * 代码表翻译器实例
     * 
     * @typedef {CodeListTranslator}
     * @memberof SearchFormControlBase
     */
    public codeListTranslator: CodeListTranslator = new CodeListTranslator();

    /**
     * 是否展开搜索表单
     *
     * @type {*}
     * @memberof SearchFormControlBase
     */
    public isExpandSearchForm: any = false;

    /**
     * 存储项名称
     * 
     * @type {string}
     * @memberof SearchFormControlBase
     */
    public saveItemName: string = '';

    /**
     * 历史记录
     * 
     * @type {any[]}
     * @memberof SearchFormControlBase
     */
    protected historyItems: any[] = [];

    /**
     * 选中记录
     * 
     * @type {any}
     * @memberof SearchFormControlBase
     */
    protected selectItem: any = null;

    /**
     * 模型id
     * 
     * @type {any}
     * @memberof SearchFormControlBase
     */
    public modelId: string = "";

    /**
     * 功能服务名称
     * 
     * @type {any}
     * @memberof SearchFormControlBase
     */
    public utilServiceName: string = "";

    /**
     * 是否开启保存查询条件
     * 
     * @type {any}
     * @memberof SearchFormControlBase
     */
    public enableSaveFilter: boolean = true;

    /**
     * @description 是否显示搜索下拉
     * @type {boolean}
     * @memberof SearchFormControlBase
     */
    public dropdownVisible: boolean = false;

    /**
     * 监听静态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof SearchFormControlBase
     */
    public onStaticPropsChange(newVal: any, oldVal: any) {
        this.enableSaveFilter = newVal.enableSaveFilter === false ? false : true;
        super.onStaticPropsChange(newVal, oldVal);
    }

    /**
     * 监听动态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof SearchFormControlBase
     */
    public onDynamicPropsChange(newVal: any, oldVal: any) {
        this.isExpandSearchForm = newVal?.isExpandSearchForm;
        //搜索表单绘制之后关闭清空数据
        // if (!this.isExpandSearchForm && this.controlIsLoaded) {
        //     Object.keys(this.data).forEach((key: any) => {
        //         this.data[key] = null;
        //     });
        // }
        super.onDynamicPropsChange(newVal, oldVal);
    }

    /**
     * 初始化搜索表单模型
     *
     * @memberof SearchFormControlBase
     */
    public async ctrlModelInit() {
        await super.ctrlModelInit();
        this.loaddraftAction = (this.controlInstance.getPSControlHandler() as IPSControlHandler)?.findPSControlHandlerAction('loaddraft')?.getPSAppDEMethod?.()?.codeName || 'GetDraft';
        this.loadAction = (this.controlInstance.getPSControlHandler() as IPSControlHandler)?.findPSControlHandlerAction('load')?.getPSAppDEMethod?.()?.codeName || 'Load';
        this.modelId = `searchform_${this.appDeCodeName ? this.appDeCodeName.toLowerCase() : 'app'}_${this.controlInstance.codeName.toLowerCase()}`;
        await this.initUtilService();
    }

    /**
     * 初始化功能服务名称
     *
     * @memberof SearchFormControlBase
     */
    public async initUtilService() {
        const appUtil: IPSAppUtil = ((await (await GetModelService(this.context))?.app as IPSApplication).getAllPSAppUtils() || []).find((util: any) => {
            return util.utilType == 'FILTERSTORAGE';
        }) as IPSAppUtil;
        if (appUtil) {
            this.utilServiceName = appUtil.codeName?.toLowerCase();
        }
        this.utilServiceName = "dynafilter";
    }

    /**
     * 部件创建完毕
     *
     * @memberof SearchFormControlBase
     */
    public ctrlInit(): void {
        super.ctrlInit();
        this.loadModel();
    }

    public loadModel() {
        let param: any = {};
        Object.assign(param, {
            appdeName: this.appDeCodeName,
            modelid: this.modelId,
            utilServiceName: this.utilServiceName,
            ...this.viewparams
        });
        let tempContext: any = JSON.parse(JSON.stringify(this.context));
        this.onControlRequset('load', tempContext, param);
        let post = this.service.loadModel(this.utilServiceName, tempContext, param);
        post.then((response: any) => {
            this.onControlResponse('load', response);
            if (response.status == 200 && response.data) {
                this.historyItems = response.data;
            }
        }).catch((response: any) => {
            this.onControlResponse('load', response);
            LogUtil.log(response);
        });
    }

    /**
     * 处理dataChang下发的事件
     *
     * @memberof SearchFormControlBase
     */
    public handleDataChange() {
        if (this.isAutoSave) {
            this.ctrlEvent({
                controlname: this.name,
                action: 'load',
                data: this.data,
            });
        }
    }

    /**
     * 加载草稿
     *
     * @param {*} opt 额外参数
     * @memberof SearchFormControlBase
     */
    public async loadDraft(opt: any = {}, mode?: string): Promise<void> {
        if (!this.loaddraftAction) {
            this.$throw('视图' + (this.$t('app.searchform.notconfig.loaddraftaction') as string), 'loadDraft');
            return;
        }
        const arg: any = { ...opt };
203
        let viewparamResult: any = Object.assign(arg, this.viewparams);
204
        let tempContext: any = JSON.parse(JSON.stringify(this.context));
205 206 207 208 209 210 211 212 213 214
        // 处理新建默认值(表单数据覆盖视图参数)V8由请求响应处理新建默认值调整为请求前处理新建默认值
        this.createDefault();
        if(this.data && Object.keys(this.data).length >0){
            Object.keys(this.data).forEach((key:string) =>{
                if(this.data[key] !== null){
                    Object.assign(viewparamResult,{[key]: this.data[key]});
                }
            })
        }
        if (!(await this.handleCtrlEvents('onbeforeloaddraft', { action: this.loaddraftAction, navParam: viewparamResult }))) {
215 216
            return;
        }
217
        this.onControlRequset('loadDraft', tempContext, viewparamResult);
218
        try {
219
            const response: any = await this.service.loadDraft(this.loaddraftAction, tempContext, viewparamResult, this.showBusyIndicator);
220 221
            this.onControlResponse('loadDraft', response);
            if (!response.status || response.status !== 200) {
222
                if (!(await this.handleCtrlEvents('onloaddrafterror', { action: this.loaddraftAction, navParam: viewparamResult, data: response?.data }))) {
223 224 225 226 227 228
                    return;
                }
                this.$throw(response, 'loadDraft');
                return;
            }
            const data = response.data;
229
            if (!(await this.handleCtrlEvents('onloaddraftsuccess', { action: this.loaddraftAction, navParam: viewparamResult, data: data }))) {
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
                return;
            }
            this.resetDraftFormStates();
            await this.onFormLoad(data, 'loadDraft');
            setTimeout(() => {
                const form: any = this.$refs[this.name];
                if (form) {
                    form.fields.forEach((field: any) => {
                        field.validateMessage = "";
                        field.validateState = "";
                        field.validateStatus = false;
                    });
                }
            });
            if (Object.is(mode, 'RESET')) {
                if (!this.formValidateStatus()) {
                    return;
                }
            }
            this.ctrlEvent({
                controlname: this.name,
                action: 'load',
                data: this.data,
            });
            this.$nextTick(() => {
                this.formState.next({ type: 'load', data: data });
            });
        } catch (error: any) {
            this.onControlResponse('loadDraft', error);
259
            if (!(await this.handleCtrlEvents('onloaddrafterror', { action: this.loaddraftAction, navParam: viewparamResult, data: error?.data }))) {
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
                return;
            }
            this.$throw(error, 'loadDraft');
        }
    }

    /**
     * 表单值变化
     *
     * @param {{ name: string, newVal: any, oldVal: any }} param
     * @memberof SearchFormControlBase
     */
    public formDataChange(param: { name: string; newVal: any; oldVal: any }): void {
        super.formDataChange(param);
        this.ctrlEvent({
            controlname: this.name,
            action: 'valuechange',
            data: this.data,
        });
    }

    /**
     * 表单加载完成
     *
     * @param {*} [data={}]
     * @param {string} action
     * @memberof SearchFormControlBase
     */
    public async onFormLoad(data: any = {}, action: string): Promise<void> {
        this.setFormEnableCond(data);
        await this.fillForm(data, action)
        this.formLogic({ name: '' });
    }

    /**
     * 回车事件
     *
     * @param {*} $event
     * @memberof SearchFormControlBase
     */
    public onEnter($event: any): void {
        this.ctrlEvent({
            controlname: this.name,
            action: 'search',
            data: this.data,
        });
    }

    /**
     * 搜索
     *
     * @memberof SearchFormControlBase
     */
    public search() {
        this.handleCtrlEvents('onsearch', { action: 'search', data: this.data }).then((result: boolean) => {
            if (!result) {
                return;
            }
            this.ctrlEvent({
                controlname: this.name,
                action: 'search',
                data: this.data,
            });
        })
    }

    /**
     * 确定
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    public onOk() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let propip: any = this.$refs.propip;
        propip.handleMouseleave();
        this.onSave(this.saveItemName);
        this.dropdownVisible = false;
    }

    /**
     * 取消设置
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    public onCancel() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let propip: any = this.$refs.propip;
        propip.handleMouseleave();
        this.dropdownVisible = false;
    }

    /**
     * @description 填充搜索表单
     * @param {string} value 历史记录值
     * @memberof SearchFormControlBase
     */
    public fillSearchForm(value: string) {
      const find = this.historyItems.find((item: any) => Object.is(item.value, value));
      if (find) {
        this.data = JSON.parse(JSON.stringify(find.data));
        this.dropdownVisible = false;
      }
    }

    /**
     * 删除记录
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    public removeHistoryItem(event: any, item: any) {
        event.stopPropagation();
        if (!(item && item.name && item.value)) {
            return;
        }
        const index = this.historyItems.findIndex((_item: any) => {
            return _item.name == item.name && _item.value == _item.value;
        });
        if (index !== -1) {
            this.historyItems.splice(index, 1);
            if (this.selectItem == item.value) {
                if (this.historyItems.length > 0) {
                    this.selectItem = this.historyItems[0].value;
                    this.data = JSON.parse(JSON.stringify(this.historyItems[0].data));
                } else {
                    this.selectItem = null;
                    Object.keys(this.data).forEach((key: any) => {
                        this.data[key] = null;
                    })
                }
            }
            let param: any = {};
            Object.assign(param, {
                model: JSON.parse(JSON.stringify(this.historyItems)),
                appdeName: this.appDeCodeName,
                modelid: this.modelId,
                utilServiceName: this.utilServiceName,
                ...this.viewparams
            });
            let post = this.service.saveModel(this.utilServiceName, this.context, param);
            post.then((response: any) => {
                this.ctrlEvent({ controlname: this.controlInstance.name, action: "save", data: response.data });
            }).catch((response: any) => {
                LogUtil.log(response);
            });
        }
    }

    /**
     * 保存
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    public async onSave(name?: string) {
        if (Util.isEmptyObject(this.data)) {
            LogUtil.warn(this.$t('app.searchform.nosearchparam'));
            return;
        }
        let time = moment();
        this.historyItems.push({
            name: await this.getSaveName(name),
            value: time.unix().toString(),
            data: JSON.parse(JSON.stringify(this.data))
        })
        this.selectItem = time.unix().toString();
        let param: any = {};
        Object.assign(param, {
            model: JSON.parse(JSON.stringify(this.historyItems)),
            appdeName: this.appDeCodeName,
            modelid: this.modelId,
            utilServiceName: this.utilServiceName,
            ...this.viewparams
        });
        try {
            const response = await this.service.saveModel(this.utilServiceName, this.context, param);
            this.ctrlEvent({ controlname: this.controlInstance.name, action: "save", data: response.data });
        } catch (error: any) {
            LogUtil.error(error);
        }
    }

    /**
     * 改变过滤条件
     *
     * @return {*}
     * @memberof SearchFormControlBase
     */
    public onFilterChange(evt: any) {
        let item: any = this.historyItems.find((item: any) => Object.is(evt, item.value));
        if (item) {
            this.selectItem = item.value;
            this.data = JSON.parse(JSON.stringify(item.data));
        }
    }

    /**
     * 重置
     *
     * @memberof SearchFormControlBase
     */
    public reset() {
        this.handleCtrlEvents('onreset', { action: 'reset' }).then((result: boolean) => {
            if (!result) {
                return;
            }
472 473 474 475 476
            if(this.data && Object.keys(this.data).length >0){
                Object.keys(this.data).forEach((key:string) =>{
                    this.data[key] = null;
                })
            }
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
            this.loadDraft({}, 'RESET');
        });
    }

    /**
     * 开启自动搜索时,值变更触发搜索
     * 
     * @param $event 
     * @memberof SearchFormControlBase
     */
    public onFormItemValueChange($event: { name: string, value: any }): void {
        super.onFormItemValueChange($event);
        //  自动搜索
        if ((this.controlInstance as any).enableAutoSearch) {
            this.search();
        }
    }

    /**
     * 保存查询条件时获取保存名称
     * 
     * @memberof SearchFormControlBase
     */
    public async getSaveName(name?: string): Promise<string> {
        if (name) {
            return name;
        }
        for (const key of Object.keys(this.data)) {
            if (key.search(/n_\\S*_\\S*/) && Util.isExistAndNotEmpty(this.data[key])) {
                const field = this.controlInstance.findPSDEFormItem(key)?.getPSAppDEField?.();
                if (field) {
                    const editItem = this.findFormItemByField(field.name);
                    let value = await this.formatCodelistValue(this.data[key], editItem);
                    if (editItem) {
                        name += `${name == '' ? '' : ', '}${field.logicName}: ${value}`;
                    }
                }
            }
        }
        return name || moment().unix().toString();
    }

    /**
     * 转化代码表值
     * 
     * @memberof SearchFormControlBase
     */
    public async formatCodelistValue(value: any, item: any): Promise<any> {
        const codeList = item.getPSEditor?.()?.getPSAppCodeList?.();
        if (codeList) {
            try {
                let response = await this.codeListTranslator.getCodeListText(value, codeList, this, Util.deepCopy(this.context), Util.deepCopy(this.viewparams));
                if (response) {
                    return response;
                }
            } catch {
                return value;
            }
        }
        return value;
    }
}