import { MPickupViewEngine, ModelTool, throttle, Util } from '@ibizstudio/runtime';
import { MainViewBase } from './mainview-base';
/**
 * 数据多项选择视图基类
 *
 * @export
 * @class MPickUpViewBase
 * @extends {MainViewBase}
 * @implements {MPickUpViewInterface}
 */
export class MPickUpViewBase extends MainViewBase {
    constructor() {
        super(...arguments);
        /**
         * 视图引擎
         *
         * @public
         * @type {Engine}
         * @memberof MPickUpViewBase
         */
        this.engine = new MPickupViewEngine();
        /**
         * 是否显示按钮
         *
         * @type {boolean}
         * @memberof MPickUpViewBase
         */
        this.isShowButton = true;
        /**
         * 选中数据的字符串
         *
         * @type {string}
         * @memberof MPickUpViewBase
         */
        this.selectedData = "";
        /**
         * 是否初始化已选中项
         *
         * @type {any[]}
         * @memberof MPickUpViewBase
         */
        this.isInitSelected = false;
        /**
         * 视图选中数据
         *
         * @type {any[]}
         * @memberof MPickUpViewBase
         */
        this.viewSelections = [];
        /**
         * 是否单选
         *
         * @type {boolean}
         * @memberof MPickUpViewBase
         */
        this.isSingleSelect = false;
    }
    /**
     * 监听部件动态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof MPickUpViewBase
     */
    onDynamicPropsChange(newVal, oldVal) {
        var _a;
        super.onDynamicPropsChange(newVal, oldVal);
        if ((_a = this.viewparams) === null || _a === void 0 ? void 0 : _a.selectedData) {
            this.selectedData = JSON.stringify(this.viewparams.selectedData);
        }
    }
    /**
     * 监听部件静态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof MPickUpViewBase
     */
    onStaticPropsChange(newVal, oldVal) {
        this.isShowButton = (newVal === null || newVal === void 0 ? void 0 : newVal.isShowButton) !== false;
        super.onStaticPropsChange(newVal, oldVal);
    }
    /**
     * 引擎初始化
     *
     * @public
     * @memberof MPickUpViewBase
     */
    engineInit() {
        var _a;
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        let engineOpts = ({
            view: this,
            parentContainer: this.$parent,
            p2k: '0',
            pickupViewPanel: this.$refs[(_a = this.pickUpViewPanelInstance) === null || _a === void 0 ? void 0 : _a.name].ctrl,
            keyPSDEField: this.appDeCodeName.toLowerCase(),
            majorPSDEField: this.appDeMajorFieldName.toLowerCase(),
        });
        this.engine.init(engineOpts);
    }
    /**
     *  视图初始化
     *
     * @memberof MPickUpViewBase
     */
    async viewMounted() {
        var _a;
        super.viewMounted();
        if ((_a = this.viewparams) === null || _a === void 0 ? void 0 : _a.selectedData) {
            this.engine.onCtrlEvent('pickupviewpanel', 'selectionchange', this.viewparams.selectedData);
        }
    }
    /**
     * 初始化分页导航视图实例
     *
     * @memberof MPickUpViewBase
     */
    async viewModelInit() {
        var _a;
        this.viewInstance = ((_a = this.staticProps) === null || _a === void 0 ? void 0 : _a.modeldata);
        await super.viewModelInit();
        this.pickUpViewPanelInstance = ModelTool.findPSControlByType("PICKUPVIEWPANEL", this.viewInstance.getPSControls());
    }
    /**
     * 渲染视图主体内容区
     *
     * @memberof MPickUpViewBase
     */
    renderMainContent() {
        return [this.renderBodyMessage(),
            <div class="translate-contant">
            <div class="center" style={{ width: !this.isShowButton ? '100%' : '' }}>
                {this.renderControlContent()}
            </div>
            {this.isShowButton && <div class="translate-buttons">
                {this.renderButtons()}
            </div>}
            {this.isShowButton && <div class="right">
                {this.renderMpickerSelect()}
            </div>}
        </div>,
            this.isShowButton && this.renderFooter(),
        ];
    }
    /**
     *  渲染视图底部按钮
     * @memberof MPickUpViewBase
     */
    renderFooter() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const { viewStyle } = this.viewInstance;
        const style2 = <template slot="footer">
                {this.isShowButton && <div style={{ 'textAlign': 'right' }}>
                    <i-button type="primary" disabled={this.viewSelections.length > 0 ? false : true} on-click={(...params) => throttle(this.onClickOk, params, this)}>{(_b = (_a = this.containerModel) === null || _a === void 0 ? void 0 : _a.view_okbtn) === null || _b === void 0 ? void 0 : _b.text}</i-button>
                    &nbsp;&nbsp;
                <i-button on-click={(...params) => throttle(this.onClickCancel, params, this)}>{(_d = (_c = this.containerModel) === null || _c === void 0 ? void 0 : _c.view_cancelbtn) === null || _d === void 0 ? void 0 : _d.text}</i-button>
                </div>}
            </template>;
        const defaultStyle = <card dis-hover={true} bordered={false} class="footer">
                <row style={{ 'textAlign': 'right' }}>
                    <i-button type="primary" disabled={this.viewSelections.length > 0 ? false : true} on-click={(...params) => throttle(this.onClickOk, params, this)}>{(_f = (_e = this.containerModel) === null || _e === void 0 ? void 0 : _e.view_okbtn) === null || _f === void 0 ? void 0 : _f.text}</i-button>
                      &nbsp;&nbsp;
                  <i-button on-click={(...params) => throttle(this.onClickCancel, params, this)}>{(_h = (_g = this.containerModel) === null || _g === void 0 ? void 0 : _g.view_cancelbtn) === null || _h === void 0 ? void 0 : _h.text}</i-button>
                </row>
            </card>;
        return viewStyle === 'STYLE2' ? style2 : defaultStyle;
    }
    /**
     * 渲染按钮
     *
     * @memberof MPickUpViewBase
     */
    renderButtons() {
        var _a, _b, _c, _d, _e, _f;
        return <div class="buttons">
            <i-button type="primary" title={(_a = this.containerModel) === null || _a === void 0 ? void 0 : _a.view_rightbtn.text} disabled={(_b = this.containerModel) === null || _b === void 0 ? void 0 : _b.view_rightbtn.disabled} on-click={(...params) => throttle(this.onCLickRight, params, this)}>
                <i class="el-icon-arrow-right"></i>
            </i-button>
            <i-button type="primary" title={(_c = this.containerModel) === null || _c === void 0 ? void 0 : _c.view_leftbtn.text} disabled={(_d = this.containerModel) === null || _d === void 0 ? void 0 : _d.view_leftbtn.disabled} on-click={(...params) => throttle(this.onCLickLeft, params, this)}>
                <i class="el-icon-arrow-left"></i>
            </i-button>
            <i-button type="primary" title={(_e = this.containerModel) === null || _e === void 0 ? void 0 : _e.view_allrightbtn.text} on-click={(...params) => throttle(this.onCLickAllRight, params, this)}>
                <i class="el-icon-d-arrow-right"></i>
            </i-button>
            <i-button type="primary" title={(_f = this.containerModel) === null || _f === void 0 ? void 0 : _f.view_allleftbtn.text} on-click={(...params) => throttle(this.onCLickAllLeft, params, this)}>
                <i class="el-icon-d-arrow-left"></i>
            </i-button>
        </div>;
    }
    /**
     * 渲染多数据选择
     *
     * @memberof MPickUpViewBase
     */
    renderMpickerSelect() {
        return <div class="mpicker-select">
            {this.viewSelections.map((item, index) => {
                return <div key={index} class={{ 'select': item._select, 'picker-item': true }} on-click={() => throttle(this.selectionsClick, [item], this)} on-dblclick={() => throttle(this.selectionsDBLClick, [item], this)}>
                    <span>{item.srfmajortext}</span>
                </div>;
            })}
        </div>;
    }
    /**
     * 渲染选择视图面板
     *
     * @memberof MPickUpViewBase
     */
    renderControlContent() {
        var _a;
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.pickUpViewPanelInstance);
        return this.$createElement(targetCtrlName, { props: targetCtrlParam, ref: (_a = this.pickUpViewPanelInstance) === null || _a === void 0 ? void 0 : _a.name, on: targetCtrlEvent });
    }
    /**
     * 计算目标部件所需参数
     *
     * @param {string} [controlType]
     * @returns
     * @memberof MPickUpViewBase
     */
    computeTargetCtrlData(controlInstance) {
        const { targetCtrlName, targetCtrlParam, targetCtrlEvent } = super.computeTargetCtrlData(controlInstance);
        Object.assign(targetCtrlParam.dynamicProps, {
            selectedData: this.selectedData,
        });
        Object.assign(targetCtrlParam.staticProps, {
            isSingleSelect: false,
            isShowButton: this.isShowButton,
        });
        return { targetCtrlName, targetCtrlParam, targetCtrlEvent };
    }
    /**
     * 部件事件
     *
     * @param controlname 部件名称
     * @param action  行为
     * @param data 数据
     *
     * @memberof MPickUpViewBase
     */
    onCtrlEvent(controlname, action, data) {
        if (action === 'load') {
            this.containerModel[`view_${controlname}`].datas = [];
        }
        super.onCtrlEvent(controlname, action, data);
    }
    /**
     * 选中数据单击
     *
     * @param {*} item
     * @memberof MPickUpViewBase
     */
    selectionsClick(item) {
        item._select = !item._select;
        const removeSelect = this.viewSelections.some((selection) => selection._select);
        this.containerModel.view_leftbtn.disabled = !removeSelect;
    }
    /**
     * 选中树双击
     *
     * @param {*} item
     * @memberof MPickUpViewBase
     */
    selectionsDBLClick(item) {
        const index = this.viewSelections.findIndex((selection) => Object.is(selection.srfkey, item.srfkey));
        if (index !== -1) {
            this.viewSelections.splice(index, 1);
        }
        const removeSelect = this.viewSelections.some((selection) => selection._select);
        this.containerModel.view_leftbtn.disabled = !removeSelect;
        this.selectedData = JSON.stringify(this.viewSelections);
    }
    /**
     * 删除右侧全部选中数据
     *
     * @memberof MPickUpViewBase
     */
    onCLickLeft() {
        const _selectiions = [...Util.deepCopy(this.viewSelections)];
        _selectiions.forEach((item) => {
            if (!item._select) {
                return;
            }
            const index = this.viewSelections.findIndex((selection) => Object.is(item.srfkey, selection.srfkey));
            if (index !== -1) {
                this.viewSelections.splice(index, 1);
            }
        });
        const removeSelect = this.viewSelections.some((selection) => selection._select);
        this.containerModel.view_leftbtn.disabled = !removeSelect;
        this.selectedData = JSON.stringify(this.viewSelections);
    }
    /**
     * 添加左侧选中数据
     *
     * @memberof MPickUpViewBase
     */
    onCLickRight() {
        Object.values(this.containerModel).forEach((model) => {
            if (!Object.is(model.type, 'PICKUPVIEWPANEL')) {
                return;
            }
            let newSelections = [];
            model.selections.forEach((item) => {
                const index = this.viewSelections.findIndex((selection) => Object.is(item.srfkey, selection.srfkey));
                if (index === -1) {
                    let _item = Object.assign({}, Util.deepCopy(item));
                    Object.assign(_item, { _select: false });
                    newSelections.push(_item);
                }
                else {
                    newSelections.push(this.viewSelections[index]);
                }
            });
            this.viewSelections = this.removeDuplicates([...newSelections, ...this.viewSelections]);
        });
    }
    /**
     * 去重
     *
     * @memberof MPickUpViewBase
     */
    removeDuplicates(data) {
        const uniqueSet = new Set(data);
        return [...uniqueSet];
    }
    /**
     * 选中数据全部删除
     *
     * @memberof MPickUpViewBase
     */
    onCLickAllLeft() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        this.viewSelections = [];
        this.containerModel.view_leftbtn.disabled = true;
        this.engine.onCtrlEvent('pickupviewpanel', 'selectionchange', []);
        this.selectedData = JSON.stringify(this.viewSelections);
    }
    /**
     * 添加左侧面板所有数据到右侧
     *
     * @memberof MPickUpViewBase
     */
    onCLickAllRight() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        Object.values(this.containerModel).forEach((model) => {
            if (!Object.is(model.type, 'PICKUPVIEWPANEL')) {
                return;
            }
            if (model.datas.length > 0) {
                model.datas.forEach((data, index) => {
                    if (!data.srfmajortext) {
                        let fieldCodeName = this.appDeMajorFieldName.toLowerCase();
                        Object.assign(data, { srfmajortext: data[fieldCodeName] });
                    }
                });
            }
            model.datas.forEach((item) => {
                const index = this.viewSelections.findIndex((selection) => Object.is(item.srfkey, selection.srfkey));
                if (index === -1) {
                    let _item = Object.assign({}, Util.deepCopy(item));
                    Object.assign(_item, { _select: false });
                    this.viewSelections.push(_item);
                }
            });
        });
        this.selectedData = JSON.stringify(this.viewSelections);
    }
    /**
     * 确定
     *
     * @memberof MPickUpViewBase
     */
    onClickOk() {
        var _a, _b;
        this.$emit('view-event', { viewName: (_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.name, action: 'viewdataschange', data: this.viewSelections });
        this.$emit('view-event', { viewName: (_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.name, action: 'close', data: null });
    }
    /**
     * 取消
     *
     * @memberof MPickUpViewBase
     */
    onClickCancel() {
        var _a, _b;
        this.$emit('view-event', { viewName: (_a = this.viewInstance) === null || _a === void 0 ? void 0 : _a.name, action: 'viewdataschange', data: null });
        this.$emit('view-event', { viewName: (_b = this.viewInstance) === null || _b === void 0 ? void 0 : _b.name, action: 'close', data: null });
    }
}
