import { __decorate } from "tslib";
import { Prop, Vue, Watch } from 'vue-property-decorator';
import { clone, mergeDeepRight } from 'ramda';
import { generateOrderValue } from 'qx-util';
import { Modal } from 'ant-design-vue';
import { Util } from '@ibizstudio-ex/runtime';
import './design-item-base.less';
/**
 * 中部设计区项基类
 *
 * @export
 * @class DesignItemBase
 * @extends {Vue}
 */
export class DesignItemBase extends Vue {
    constructor() {
        super(...arguments);
        /**
         * 数据
         *
         * @type {any[]}
         * @memberof DesignItemBase
         */
        this.list = [];
        /**
         * 拖拽参数
         *
         * @type {sortable.Options}
         * @memberof DesignMaterialPanelBase
         */
        this.options = {};
        /**
         * 是否禁用消息中心通知
         *
         * @memberof DesignItemBase
         */
        this.isAcc = true;
    }
    /**
     * 当前是否为激活状态
     *
     * @memberof DesignItemBase
     */
    get active() {
        var _a, _b, _c;
        return ((_a = this.data) === null || _a === void 0 ? void 0 : _a.srfkey) === ((_c = (_b = this.ctrl) === null || _b === void 0 ? void 0 : _b.select.data) === null || _c === void 0 ? void 0 : _c.srfkey);
    }
    dataWatch(newVal, oldVal) {
        this.dataChange(newVal, oldVal);
    }
    parentDataChange(newVal, old) {
        this.$forceUpdate();
    }
    /**
     * 启用应用消息订阅
     *
     * @memberof DesignItemBase
     */
    enableAcc() {
        this.isAcc = true;
    }
    /**
     * 禁用应用消息订阅
     *
     * @memberof DesignItemBase
     */
    disableAcc() {
        this.isAcc = false;
    }
    initOption() {
        this.options = {
            handle: '.drag-handle',
            group: {
                name: this.ctx.tag,
            },
            animation: 150,
        };
    }
    /**
     * 数据变更
     *
     * @param {any} _newVal
     * @param {any} _oldData
     * @memberof DesignItemBase
     */
    dataChange(_newVal, _oldData) { }
    /**
     * 组件创建完毕
     *
     * @memberof DesignItemBase
     */
    componentCreated() { }
    created() {
        if (!this.ctx) {
            console.error('未设置上下文「ctx」，初始化异常!', this);
            return;
        }
        this.ctrl = this.ctx.ctrl;
        this.globalService = this.ctx.gs;
        this.initOption();
        this.selectChange = this.selectChange.bind(this);
        this.ctrl.select.evt.on('change', this.selectChange);
        this.componentCreated();
    }
    /**
     * 组件加载完毕
     *
     * @memberof DesignItemBase
     */
    componentMounted() { }
    mounted() {
        this.el = this.$refs.designItem;
        this.options = mergeDeepRight(this.options, this.generateOption());
        this.ctrlCtrl = this.ctrl.ctx.ctrl.ctrlCtrl;
        this.context = Util.deepCopy(this.ctrl.ctx.context);
        this.componentMounted();
    }
    /**
     * 组件销毁
     *
     * @memberof DesignItemBase
     */
    componentDestroyed() { }
    destroyed() {
        this.ctrl.select.evt.off('change', this.selectChange);
        this.componentDestroyed();
    }
    /**
     * 查询数据
     *
     * @param {IParams} [params]
     * @return {*}  {Promise<any[]>}
     * @memberof DesignItemBase
     */
    async loadChild(params) {
        if (this.previewService) {
            const arr = await this.previewService.selectLocal(this.ctx.context, params);
            if (arr) {
                this.list.splice(0, this.list.length);
                this.list.push(...arr);
            }
            return arr;
        }
        console.warn('未设置当前设计对象所属服务', this);
        return [];
    }
    /**
     * 生成拖拽参数
     *
     * @return {*}  {sortable.Options}
     * @memberof DesignItemBase
     */
    generateOption() {
        return {};
    }
    /**
     * 绘制内容
     *
     * @param {CreateElement} _h
     * @return {*}  {VNode[]}
     * @memberof DesignItemBase
     */
    renderContentList(_h) {
        throw new Error('「renderContentList」此方法必须重写实现!');
    }
    /**
     * 设置选中数据
     *
     * @param {*} data
     * @memberof DesignItemBase
     */
    setSelect(data) {
        if (this.ctrl) {
            this.ctrl.select.set(data);
        }
    }
    /**
     * 选中数据变更
     *
     * @param {any} data
     * @memberof DesignItemBase
     */
    selectChange(data) {
        this.activeChange(data);
    }
    /**
     * 激活数据变更
     *
     * @param {any} data
     * @memberof DesignItemBase
     */
    activeChange(data) { }
    /**
     * 用户操作提示
     *
     * @param {any} data
     * @memberof DesignItemBase
     */
    userOperationTips(event) {
        var _a;
        if (event === null || event === void 0 ? void 0 : event.added) {
            const panelCtrl = ((_a = this.ctrl.ctx) === null || _a === void 0 ? void 0 : _a.panelCtrl) || this.ctrl;
            if (panelCtrl.evt) {
                panelCtrl.evt.emit('resetLayout');
            }
        }
        let select = '';
        const modal = Modal.confirm({
            class: 'operation-tips',
            width: 720,
            centered: true,
            maskClosable: false,
            content: () => {
                return (<div class="tips">
                        <div class="tips-title">
                            <span>新建布局</span>
                            <i class="ivu-icon ivu-icon-ios-close" on-click={() => onCancel()}/>
                        </div>
                        <div class="tips-content">
                            <span class="tips-info">当前为默认布局无法编辑，是否进行自定义布局</span>
                            <div class="select-area">
                                <div class={{ 'tips-item': true, 'selected': Object.is(select, 'cloneDefaultLayoutNew') }} on-click={() => selectNewMode('cloneDefaultLayoutNew')}>
                                    <img src="assets/img/cloneDefaultLayoutNew.png"></img>
                                    <div class="title">克隆默认布局新建</div>
                                    <div class="description">以当前视图默认布局为蓝本，建立用户自定义布局面板</div>
                                </div>
                                <div class={{ 'tips-item': true, 'selected': Object.is(select, 'useExistingLayout') }} on-click={() => selectNewMode('useExistingLayout')}>
                                    <img src="assets/img/useExistingLayout.png"></img>
                                    <div class="title">选用已有布局</div>
                                    <div class="description">选择已经建立的自定义布局面板数据</div>
                                </div>
                            </div>
                        </div>
                        <div class="tips-action">
                            <a-button on-click={() => onCancel()}>取消</a-button>
                            <a-button type="primary" on-click={() => nextStep()} disabled={!select}>下一步</a-button>
                        </div>
                    </div>);
            },
            onOk: () => {
                var _a;
                const panelCtrl = ((_a = this.ctrl.ctx) === null || _a === void 0 ? void 0 : _a.panelCtrl) || this.ctrl;
                if (panelCtrl.evt) {
                    if (Object.is(select, 'cloneDefaultLayoutNew')) {
                        panelCtrl.evt.emit('cloneDefaultLayout');
                    }
                    else {
                        panelCtrl.evt.emit('itemClick', { tag: 'switchpanel' });
                    }
                }
            },
            onCancel: () => {
            }
        });
        const selectNewMode = (model) => {
            select = model;
            modal === null || modal === void 0 ? void 0 : modal.update();
        };
        const onCancel = () => {
            modal === null || modal === void 0 ? void 0 : modal.destroy();
        };
        const nextStep = () => {
            var _a;
            modal === null || modal === void 0 ? void 0 : modal.destroy();
            const panelCtrl = ((_a = this.ctrl.ctx) === null || _a === void 0 ? void 0 : _a.panelCtrl) || this.ctrl;
            if (panelCtrl.evt) {
                if (Object.is(select, 'cloneDefaultLayoutNew')) {
                    panelCtrl.evt.emit('cloneDefaultLayout');
                }
                else if (Object.is(select, 'useExistingLayout')) {
                    panelCtrl.evt.emit('itemClick', { tag: 'switchpanel' });
                }
            }
        };
    }
    /**
     * 拖拽数据变更
     *
     * @param {*} evt
     * @memberof DesignItemBase
     */
    change(evt, list = []) {
        var _a, _b;
        if (((evt === null || evt === void 0 ? void 0 : evt.added) || (evt === null || evt === void 0 ? void 0 : evt.moved)) && ((_a = this.ctrl) === null || _a === void 0 ? void 0 : _a.isDefaultLayout)) {
            this.userOperationTips(evt);
        }
        else if (evt === null || evt === void 0 ? void 0 : evt.added) {
            if ((_b = this.ctrl) === null || _b === void 0 ? void 0 : _b.isDefaultLayout) {
                this.userOperationTips(evt);
            }
            else {
                const data = Object.assign(Object.assign({}, evt.added), { element: clone(Object.assign(evt.added.element) || {}) });
                if (data.element.isCtrls) {
                    this.addCtrlItem(data, list);
                }
                else {
                    this.add(data);
                }
            }
        }
        else if (evt === null || evt === void 0 ? void 0 : evt.moved) {
            this.move(evt.moved);
        }
    }
    /**
     * 新增项
     *
     * @param {{ element: any; newIndex: number }} _opt
     * @return {*}  {Promise<void>}
     * @memberof DesignItemBase
     */
    async add(_opt) { }
    /**
     * @description 新增拖拽部件
     * @param {*} arg
     * @memberof DesignItemBase
     */
    addCtrlItem(data, list) {
        var _a;
        const param = {
            psctrltypeid: (_a = data === null || data === void 0 ? void 0 : data.element) === null || _a === void 0 ? void 0 : _a.predefinedtype,
        };
        if (this.ctrl.evt) {
            this.ctrl.evt.emit('itemClick', {
                tag: 'viewctrlcreate',
                param: param,
                callback: (_data) => {
                    if (_data.codename) {
                        Object.assign(data.element, { pssysviewpanelitemname: _data.codename, isCtrls: false });
                        this.add(data);
                    }
                },
            });
        }
    }
    /**
     * 子项移动
     *
     * @param {{ data: any; newIndex: number; oldIndex: number }} opt
     * @return {*}  {Promise<void>}
     * @memberof DesignItemBase
     */
    async move(opt) {
        const { newIndex, oldIndex } = opt;
        // 根据变更位置更新排序值
        if (newIndex > oldIndex) {
            await this.updateOrderValue(oldIndex);
        }
        else {
            await this.updateOrderValue(newIndex);
        }
    }
    /**
     * 根据当前列表，更新排序值
     *
     * @param {number} [num=0] 更新起始下标，默认从0开始
     * @return {*}  {Promise<void>}
     * @memberof DesignItemBase
     */
    async updateOrderValue(num = 0) {
        this.disableAcc();
        for (let i = num; i < this.list.length; i++) {
            const item = this.list[i];
            item.ordervalue = generateOrderValue(i);
            item.srfordervalue = item.ordervalue;
            await this.service.UpdateTemp(this.ctx.context, item);
        }
        this.enableAcc();
    }
    /**
     * 获取拖拽容器样式
     *
     * @return {*}  {*}
     * @memberof DesignItemBase
     */
    getDraggableClass() {
        return {
            'transition-group': true,
            'draggable-warp': true,
            'ant-row': true,
        };
    }
    /**
     * 拖拽容器render额外参数
     *
     * @return {*}  {VNodeData}
     * @memberof DesignItemBase
     */
    getDraggableOtherParams() {
        return {};
    }
    /**
     * 绘制拖拽区
     *
     * @param {any[]} list
     * @param {*} content
     * @returns {*}
     * @memberof DragDesignBase
     */
    renderDraggable(list, content) {
        var _a;
        const h = this.$createElement;
        return h('draggable', {
            attrs: {
                handle: this.options.handle,
                group: this.options.group,
                animation: this.options.animation,
                list: list,
                disabled: (_a = this.ctx.ctrl) === null || _a === void 0 ? void 0 : _a.isViewDesign
            },
            class: 'draggable-container',
            on: {
                change: (e) => this.change(e),
            },
        }, [
            h('transition-group', Object.assign({ attrs: {
                    type: 'transition',
                    name: 'flip-list',
                }, class: this.getDraggableClass() }, this.getDraggableOtherParams()), content),
        ]);
    }
}
__decorate([
    Prop()
], DesignItemBase.prototype, "ctx", void 0);
__decorate([
    Prop()
], DesignItemBase.prototype, "data", void 0);
__decorate([
    Watch('data', { deep: true, immediate: true })
], DesignItemBase.prototype, "dataWatch", null);
__decorate([
    Prop()
], DesignItemBase.prototype, "parentData", void 0);
__decorate([
    Watch('parentData', { deep: true, immediate: true })
], DesignItemBase.prototype, "parentDataChange", null);
