import moment from 'moment';
import { VNode } from 'vue';
import { Component, Prop, Vue } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import { acc } from '@ibizstudio/api';
import './design-item-content.less';

@Component
export class DesignItemContent extends Vue {
    /**
     * 绘制类型
     *
     * @type {('item'|'other')}
     * @memberof DesignItemContent
     */
    @Prop()
    renderType!: 'item' | 'other';

    /**
     * 数据
     *
     * @type {*}
     * @memberof DesignItemContent
     */
    @Prop()
    data!: any;

    /**
     * 上下文
     *
     * @type {*}
     * @memberof DesignItemContent
     */
    @Prop()
    ctx!: any;

    /**
     * 表单项标题宽度
     *
     * @type {number}
     */
    formItemlabelWidth:number = 0;

    /**
   * acc 订阅标识
   *
   * @type {string[]}
   * @memberof createPanelModal
   */
    accSubs: string[] = [];

    created() {
        // 初始化获取表单项标签宽度
        this.formItemlabelWidth = this.ctx.ctrl.formItemlabelWidth;
        this.accSubs.push(
            acc.commandLocal(
              (data: any) => {
                  // 发生变化前与发生变化后的值进行对比
                if (!Object.is(data.labelwidth,this.formItemlabelWidth)) {
                  this.formItemlabelWidth = data.labelwidth
                }
              },
              'update',
              'PSDEFORM',
            ),
        );
      }


    /**
     * 绘制函数
     *
     * @param {CreateElement} h
     * @return {*}
     * @memberof DesignItemContent
     */
    render(h: CreateElement) {
        return this.renderContent(h);
    }

    /**
     * 绘制内容
     *
     * @param {CreateElement} h
     * @return {*}
     * @memberof DesignItemContent
     */
    renderContent(h: CreateElement) {
        // 当前项数据
        const tag: any = this.data;
        // 标签位置
        const labelPos: string = tag.labelpos ? tag.labelpos.toLowerCase() : 'left';
        // 标签样式
        const labelStyle: string =
            Object.is(labelPos, 'top') || Object.is(labelPos, 'bottom') ? '' : `width: ${tag.labelwidth || this.formItemlabelWidth || 130}px;`;
        // // 编辑器样式
        const ctrlStyle: string = this.getFormCtrlStyle(tag, labelPos);

        if (tag.itemtype === 'FIELD') {
            return (
                <div class={`design-form-item ${labelPos || 'left'}`}>
                    <div class='design-form-editor-container' style={{ width: '100%', height: '100%' }}>
                        {this.renderDesignItem()}
                    </div>
                </div>
            );
        }

        if (this.renderType === 'item') {
            return (
                <div class={`design-form-item ${labelPos || 'left'}`}>
                    {tag.showcaption == '0' ? null : (
                        <div class='design-form-label' style={labelStyle}>
                            {tag.emptycaption == '1' ? null : (
                                <label>
                                    {Object.is(labelPos, 'right') ? '：' : ''}
                                    {tag.caption || tag.logicname}
                                    {!Object.is(labelPos, 'right') ? '：' : ''}
                                </label>
                            )}
                        </div>
                    )}
                    <div class='design-form-editor-container' style={ctrlStyle}>
                        {this.renderDesignItem()}
                    </div>
                </div>
            );
        } else if (this.renderType === 'other') {
            return this.renderDesignOtherItem();
        }
        return null;
    }

    /**
     * @description 获取内容样式
     * @param {*} data
     * @return {*}
     * @memberof DesignItemContent
     */
    getContentStyle(data: any) {
        if (data && data.rawcssstyle) {
            const res = data.rawcssstyle.split("\n");
            const target: string[] = [];
            for (let i = 0; i < res.length; i++) {
                target.push(...res[i].split(";").filter((value: string) => value));
            }
            return target.filter((value: string) => {
                return value.split(":").length === 2;
            }).join(";");
        }
    }

    /**
     * 获取表单控件样式
     *
     * @protected
     * @param {*} tag
     * @param {string} labelPos
     * @returns {string}
     * @memberof FormItem
     */
    protected getFormCtrlStyle(tag: any, labelPos: string): string {
        let style: string = '';
        if (
            Object.is(labelPos, 'none') ||
            Object.is(labelPos, 'top') ||
            Object.is(labelPos, 'bottom') ||
            tag.showcaption == '0'
        ) {
            if (tag.ctrlwidth) {
                style += `width: ${tag.ctrlwidth}px;`;
            } else {
                style += `width: 100%;`;
            }
        } else {
            if (tag.ctrlwidth) {
                style += `width: ${tag.ctrlwidth}px;`;
            } else {
                style += `width: calc(100% - ${tag.labelwidth || 130}px);`;
            }
        }
        if (tag.ctrlheight) {
            style += `height: ${tag.ctrlheight}px;`;
        } else {
            style += `height: 100%;`;
        }
        return style;
    }

    /**
     * 绘制项
     *
     * @param {PSDEFormDetail} data
     * @return {*}  {*}
     * @memberof DesignItemContent
     */
    public renderDesignItem(): any {
        const data = this.data;
        const contentStyle = this.getContentStyle(data);
        const { text} = data;
        const curDate = new Date();
        const previewHtml = data.previewhtml;
        if (previewHtml) {
          this.$nextTick(() => {
            const divRef = this.$refs[`${data.pssyseditorstyleid}`] as HTMLDivElement;
            if (divRef) {
              divRef.innerHTML = previewHtml;
            }
          });
          return <div class={[`${data.srfdename + '-' + data.pssyseditorstyleid}`, 'preview-html']} ref={data.pssyseditorstyleid} style={`padding-left: 10px;${contentStyle}`}></div>;
        }
        if (data) {
            switch (data.editortype) {
                case 'HIDDEN':
                    return (
                        <div style='padding-left: 10px;' class='design-item-hidden'>
                            隐藏表单项
                        </div>
                    );
                case 'SPAN':
                    return (
                        <span style={`padding-left: 10px;${contentStyle}`} class='design-design-editor'>
                            {text}
                        </span>
                    );
                // case 'HTMLEDITOR':
                //     return <span>{text}[HTML编辑框]</span>;
                // case 'IPADDRESSTEXTBOX':
                //     return <span>{text}[IP地址输入框]</span>;
                // case 'CODEEIDT':
                //     return <span>{text}[代码编辑器]</span>;
                case 'RADIOBUTTONLIST':
                    return (
                        <a-radio-group disabled>
                            <a-radio value={1}>选项一</a-radio>
                            <a-radio value={2}>选项二</a-radio>
                            <a-radio value={3}>选项三</a-radio>
                        </a-radio-group>
                    );
                case 'ADDRESSPICKUP':
                case 'ADDRESSPICKUP_AC':
                    return (
                        <a-select mode='tags' style='width: 100%' placeholder={text} disabled>
                            <a-select-option key='1'>选项一</a-select-option>
                            <a-select-option key='2'>选项二</a-select-option>
                            <a-select-option key='3'>选项三</a-select-option>
                        </a-select>
                    );
                // case 'LISTBOX':
                //     return <span>{text}[列表框]</span>;
                // case 'LISTBOXPICKUP':
                //     return <span>{text}[列表框（选择）]</span>;
                case 'TEXTAREA':
                    return (
                        <a-textarea
                            placeholder={text}
                            style={data.ctrlheight ? 'height: ' + data.ctrlheight + 'px;' : ''}
                            class='form-editor-item form-editor-item--textarea'
                            disabled
                        />
                    );
                case 'TEXTAREA_10':
                    return <a-textarea placeholder={text} rows={10} disabled />;
                case 'PASSWORD':
                    return <a-input placeholder={text} disabled />;
                case 'DATEPICKEREX':
                    return (
                        <a-date-picker
                            defaultValue={moment(curDate, 'YYYY-MM-DD HH:mm:ss')}
                            format='YYYY-MM-DD HH:mm:ss'
                            disabled
                        />
                    );
                case 'DATEPICKEREX_MINUTE':
                    return (
                        <a-date-picker
                            defaultValue={moment(curDate, 'YYYY-MM-DD HH:mm')}
                            format='YYYY-MM-DD HH:mm'
                            disabled
                        />
                    );
                case 'DATEPICKEREX_SECOND':
                    return (
                        <a-date-picker
                            defaultValue={moment(curDate, 'YYYY-MM-DD HH:mm:ss')}
                            format='YYYY-MM-DD HH:mm:ss'
                            disabled
                        />
                    );
                case 'DATEPICKEREX_NODAY':
                    return <a-date-picker defaultValue={moment(curDate, 'HH:mm:ss')} format='HH:mm:ss' disabled />;
                case 'DATEPICKEREX_NODAY_NOSECOND':
                    return <a-date-picker defaultValue={moment(curDate, 'HH:mm')} format='HH:mm' disabled />;
                case 'DATEPICKEREX_NOTIME':
                    return (
                        <a-date-picker defaultValue={moment(curDate, 'YYYY-MM-DD')} format='YYYY-MM-DD' disabled />
                    );
                case 'DATEPICKEREX_HOUR':
                    return (
                        <a-date-picker
                            defaultValue={moment(curDate, 'YYYY-MM-DD HH')}
                            format='YYYY-MM-DD HH'
                            disabled
                        />
                    );
                case 'DATEPICKER':
                    return (
                        <a-date-picker
                            defaultValue={moment(curDate, 'YYYY-MM-DD HH:mm:ss')}
                            format='YYYY-MM-DD HH:mm:ss'
                            disabled
                        />
                    );
                // case 'PICTURE':
                //     return <span>{text}[图片控件]</span>;
                // case 'PICTURE_ONE':
                //     return <span>{text}[图片控件（单项）]</span>;
                case 'TEXTBOX':
                    return <a-input style={contentStyle} placeholder={text} disabled />;
                case 'FILEUPLOADER':
                    return (
                        <a-button disabled>
                            <a-icon type='upload' /> {text}
                        </a-button>
                    );
                case 'AC':
                case 'AC_NOBUTTON':
                case 'AC_FS_NOBUTTON':
                case 'AC_FS':
                case 'PICKEREX_LINKONLY':
                case 'PICKER':
                case 'PICKUPVIEW':
                case 'PICKEREX_LINK':
                case 'PICKEREX_NOAC_LINK':
                case 'PICKEREX_NOAC':
                case 'PICKEREX_NOBUTTON':
                case 'PICKEREX_TRIGGER_LINK':
                case 'PICKEREX_TRIGGER':
                case 'DROPDOWNLIST':
                    return (
                        <a-select defaultValue='1' style='width: 100%' disabled>
                            <a-select-option value='1'>选项一</a-select-option>
                            <a-select-option value='2'>选项二</a-select-option>
                            <a-select-option value='3'>选项三</a-select-option>
                        </a-select>
                    );
                case 'MDROPDOWNLIST':
                    return (
                        <a-select defaultValue='1' style='width: 100%' disabled>
                            <a-select-option value='1'>选项一</a-select-option>
                            <a-select-option value='2'>选项二</a-select-option>
                            <a-select-option value='3'>选项三</a-select-option>
                        </a-select>
                    );
                case 'DROPDOWNLIST_100':
                    return (
                        <a-select defaultValue='1' style='width: 100px' disabled>
                            <a-select-option value='1'>选项一</a-select-option>
                            <a-select-option value='2'>选项二</a-select-option>
                            <a-select-option value='3'>选项三</a-select-option>
                        </a-select>
                    );
                case 'CHECKBOX':
                    return <a-checkbox disabled>选项</a-checkbox>;
                case 'CHECKBOXLIST':
                    return <a-checkbox-group options={['选项一', '选项二']} disabled />;
                case 'NUMBER':
                    return <a-input-number style='width: 100%' disabled />;
                // case 'USERCONTROL':
                //     return <span>{text}[用户自定义]</span>;
                // case 'RAW':
                //     return <span>{text}[直接内容]</span>;
                case 'RATING':
                    return <el-rate value={4} disabled={true} />;
                case 'SLIDER':
                    return <el-slider value={30} show-input={true} class='form-editor-item form-editor-item--slider' />;
                case 'DATERANGE':
                    return (
                        <el-date-picker
                            value={[curDate, curDate]}
                            type='daterange'
                            range-separator='至'
                            start-placeholder='开始日期'
                            end-placeholder='结束日期'
                            format='yyyy-MM-dd HH:mm:ss'
                            disabled={true}
                            prefix-icon='el-icon-time'
                            class='fomr-editor-item form-editor-item--daterange'
                        />
                    );
                case 'ARRAY':
                    return <panel-array-input placeholder={text} disabled={true} />;
                case 'MAPPICKER':
                    return <panel-map-picker disabled={true} />;
                case 'SWITCH':
                    return <a-switch disabled={true} />;
            }
        }
        return this.renderDefaultField();
    }

    /**
     * @description 绘制默认属性
     * @return {*}
     * @memberof DesignItemContent
     */
    protected renderDefaultField(): any {
        const data = this.data;
        const { text} = data;
        return <a-input placeholder={text} disabled />;
    }

    /**
     * 绘制项
     *
     * @param {*} data
     * @return {*}  {(VNode | null)}
     * @memberof DesignItemContent
     */
    public renderDesignOtherItem(): VNode | null {
        const data = this.data;
        switch (data.itemtype as any) {
            // 直接内容
            case 'RAWITEM':
                return this.renderRawItem(data);
            // 控件
            case 'CONTROL':
                return this.renderControl(data);
            // 自定义部件
            case 'USERCONTROL':
                return this.renderUserControl(data);
            // 按钮
            case 'BUTTON':
                return this.renderButton(data);
            // 分页部件
            case 'FORMPART':
                return this.renderFormPart(data);
            // 直接嵌入页面
            case 'IFRAME':
                return this.renderIframe(data);
            // 复合表单项
            case 'FORMITEMEX':
                return this.renderDesignItemContentEx(data);
            // 关系
            case 'DRUIPART':
                return this.renderDrUiPart(data);
            // 控件占位
            case 'CTRLPOS':
                return this.renderCtrlPos(data);
            // 嵌入视图
            case 'APPVIEW':
                return this.renderAppView(data);
            // 快速菜单栏
            case 'APPMENU':
                return this.renderAppMenu(data);
            // 系统门户部件
            case 'SYSPORTLET':
                return this.renderSysPortlet(data);
            default:
                return null;
        }
    }

    /**
     *  嵌入视图
     *
     * @param {*} data
     * @return {*}  {VNode}
     * @memberof DesignItemContent
     */
    private renderAppView(data: any): VNode {
        return <span>{data.text}-[嵌入视图]</span>;
    }

    /**
     *  快速菜单栏
     *
     * @param {*} data
     * @return {*}  {VNode}
     * @memberof DesignItemContent
     */
    private renderAppMenu(data: any): VNode {
        return <span>{data.text}-[快速菜单栏]</span>;
    }

    /**
     *  系统门户部件
     *
     * @param {*} data
     * @return {*}  {VNode}
     * @memberof DesignItemContent
     */
    private renderSysPortlet(data: any): VNode {
        return <span>{`${data.srftext} - [${data.title || '系统门户部件'}] `}</span>;
    }

    /**
     *  布局容器
     *
     * @param {*} data
     * @return {*}  {VNode}
     * @memberof DesignItemContent
     */
    private renderContainer(data: any): VNode {
        return <span>{data.text}-[布局容器]</span>;
    }

    /**
     * 控件
     *
     * @param {*} item
     * @returns {VNode}
     * @memberof DesignItemContent
     */
    private renderControl(data: any): VNode {
        return <span>{data.text}-[控件]</span>;
    }

    /**
     * 控件占位
     *
     * @param {*} item
     * @memberof DesignItemContent
     */
    protected renderCtrlPos(data: any): VNode {
        return <span>{data.text}-[控件占位]</span>;
    }

    /**
     * 隐藏表单项
     *
     * @param {any} data
     * @returns {*}
     * @memberof DesignItemContent
     */
    protected renderHiddenItem(data: any): any {
        return <div>{data.text}-[隐藏表单项]</div>;
    }

    /**
     * 直接内容
     *
     * @param {*} item
     * @memberof DesignItemContent
     */
    protected renderRawItem(data: any): VNode {
        return <div>{data.text}[直接内容]</div>;
    }

    /**
     * 自定义部件
     *
     * @param {*} item
     * @memberof DesignItemContent
     */
    protected renderUserControl(data: any): VNode {
        return <span>{data.text}</span>;
    }

    /**
     * 按钮
     *
     * @param {*} item
     * @memberof DesignItemContent
     */
    protected renderButton(data: any): VNode {
        const btnClass = data.detailstyle ? `ant-btn--${data.detailstyle.toLowerCase()}` : '';
        const contentStyle = this.getContentStyle(data);
        const text = data.showcaption != 0 ? data.text : '*';
        if(data.rendermode=="LINK"){
            //链接
            return <a-button type='link' style={contentStyle}>{text}</a-button>;
        }else{
            //按钮
            return <a-button class={btnClass} style={contentStyle}>{text}</a-button>;
        }
    }

    /**
     * 表单部件
     *
     * @param {*} item
     * @memberof DesignItemContent
     */
    protected renderFormPart(data: any): VNode {
        return <div>{data.text}[表单部件]</div>;
    }

    /**
     * 直接嵌入页面
     *
     * @param {*} item
     * @returns {VNode}
     * @memberof DesignItemContent
     */
    protected renderIframe(data: any): VNode {
        return <span>{data.text}[直接嵌入页面（iframe）]</span>;
    }

    /**
     * 复合表单项
     *
     * @param {*} item
     * @returns {VNode}
     * @memberof DesignItemContent
     */
    protected renderDesignItemContentEx(data: any): VNode {
        return <span>{data.text}[复合表单项]</span>;
    }

    /**
     * 关系
     *
     * @param {*} item
     * @returns {VNode}
     * @memberof DesignItemContent
     */
    protected renderDrUiPart(data: any): VNode {
        return <span>{data.text}[关系]</span>;
    }


    destroyed(): void {
        this.accSubs.forEach(sub => {
          acc.unsubscribeLocal(sub);
        });
    }
}
