import { VueLifeCycleProcessing } from '@ibizstudio-ex/template-vue';
import { createUUID } from "qx-util";
import { Component, Prop, Vue } from 'vue-property-decorator';
import { DesignContainerBase } from '../design-container-base/design-container-base';
import './design-scroll-container.less'


/**
 * 子类型声明
 */
type ChildTypes = 'CONTAINER_SCROLL_HEADER' | 'CONTAINER_SCROLL_BOTTOM' | 'CONTAINER_SCROLL_LEFT' | 'CONTAINER_SCROLL_RIGHT' | 'CONTAINER_SCROLL_MAIN';

/**
 * 绘制滚动容器
 *
 * @export
 * @class DesignScrollContainer
 * @extends {DesignContainerBase}
 */
@Component({})
@VueLifeCycleProcessing()
export class DesignScrollContainer extends DesignContainerBase {


  /**
   * 布局控制
   */
  top: any;
  bottom: any;
  left: any;
  right: any;
  main: any;

  async load(): Promise<void> {
    await super.load()
    if (this.list.length > 0) {
      this.list.forEach(item => this.setChildData(item))
    }
    if (!this.main) {
      await this.createdChild('CONTAINER_SCROLL_MAIN');
    }
  }

  /**
  * 设置子项数据
  * @param {*} data
  */
  setChildData(data: any): void {
    switch (data?.predefinedtype) {
      case 'CONTAINER_SCROLL_HEADER':
        this.top = data;
        break;
      case 'CONTAINER_SCROLL_BOTTOM':
        this.bottom = data;
        break;
      case 'CONTAINER_SCROLL_LEFT':
        this.left = data;
        break;
      case 'CONTAINER_SCROLL_RIGHT':
        this.right = data;
        break;
      case 'CONTAINER_SCROLL_MAIN':
        this.main = data;
        break;
    }
    this.$forceUpdate();
  }

  /**
   * 创建项数据存入本地
   * @param context
   * @param parent
   * @param params
   */
  async createItem(context: any, parent: any, params?: any): Promise<any> {
    if (!params) {
      params = {};
    }
    Object.assign(params, { srfkey: createUUID(), showcaption: 0, showtitlebar: 0 });
    if (parent.srfkey) {
      Object.assign(params, { srfpkey: parent.srfkey });
      const res = await this.service.GetDraftTemp(context, params);
      if (res.ok) {
        const result = await this.service.CreateTemp(context, res.data);
        return result;
      }
    }
    return {}
  }

  /**
   * 更新子项数据（main）
   */
   updateChildData(){
    let mainWidth: number = 100;
    if(this.left && Object.is(this.left.widthmode,'PERCENTAGE') && this.left.width){
      mainWidth = Number(mainWidth - this.left.width)
    }
    if(this.right && Object.is(this.right.widthmode,'PERCENTAGE') && this.right.width){
      mainWidth = Number(mainWidth - this.right.width)
    }
    if (this.main) {
      this.main.width = mainWidth;
      this.service.UpdateTemp(this.context,this.main)
    }
  }

  /**
   * 创建
   * @param {ChildTypes} type
   */
  async createdChild(type: ChildTypes): Promise<void> {
    const params: any = { predefinedtype: type, itemtype: 'CONTAINER' };
    switch (type) {
      case 'CONTAINER_SCROLL_HEADER':
        params.top = 'top'
        params.heightmode = 'PX';
        params.height = '80';
        break;
      case 'CONTAINER_SCROLL_BOTTOM':
        params.bottom = 'bottom';
        params.heightmode = 'PX';
        params.height = '80';
        break;
      case 'CONTAINER_SCROLL_LEFT':
        params.left = 'left';
        params.widthmode = 'PERCENTAGE';
        params.width = '20';
        break;
      case 'CONTAINER_SCROLL_RIGHT':
        params.right = 'right';
        params.widthmode = 'PERCENTAGE';
        params.width = '20';
        break;
      case 'CONTAINER_SCROLL_MAIN':
        params.main = 'main';
        params.widthmode = 'PERCENTAGE';
        break;
    }
    const result = await this.createItem(this.context, this.data, params);
    if (result) { this.setChildData(result.data) }
    this.updateChildData()
  }

  /**
   * 移除布局
   * @param {string} type
   */
  async removeChild(type: string): Promise<void> {
    let data: any = null;
    switch (type) {
      case 'CONTAINER_SCROLL_HEADER':
        data = this.top;
        data.heightmode = '';
        data.height = '';
        this.top = null;
        break;
      case 'CONTAINER_SCROLL_BOTTOM':
        data = this.bottom;
        data.heightmode = '';
        data.height = '';
        this.bottom = null;
        break;
      case 'CONTAINER_SCROLL_LEFT':
        data = this.left;
        this.left = null;
        data.widthmode = '';
        data.width = '';
        break;
      case 'CONTAINER_SCROLL_RIGHT':
        data = this.right;
        this.right = null;
        data.widthmode = '';
        data.width = '';
        break;
      case 'CONTAINER_SCROLL_MAIN':
        data = this.main;
        this.main = null;
        break;
    }
    const result = await this.service.RemoveTemp(this.ctx.context, data);
    this.updateChildData()
    if (!result) {
      console.warn('删除失败', data);
    }
  }

  /**
   * 判断布局按钮创建&移除
   * @param {MouseEvent} e
   * @param {string} type
   */
  onLayoutChange(e: MouseEvent, type: string): void {
    e.stopPropagation();
    switch (type) {
      case 'CONTAINER_SCROLL_HEADER':
        if (this.top) {
          this.removeChild(type);
        } else {
          this.createdChild(type);
        }
        break;
      case 'CONTAINER_SCROLL_RIGHT':
        if (this.right) {
          this.removeChild(type);
        } else {
          this.createdChild(type);
        }
        break;
      case 'CONTAINER_SCROLL_BOTTOM':
        if (this.bottom) {
          this.removeChild(type);
        } else {
          this.createdChild(type);
        }
        break;
      case 'CONTAINER_SCROLL_LEFT':
        if (this.left) {
          this.removeChild(type);
        } else {
          this.createdChild(type);
        }
        break;
    }
  }

  /**
   * 获取宽度
   *
   * @memberof
   */
   getWidthStyle(data: any) {
    let style: any = {}
    if (Object.is(data.widthmode, 'FULL')) {
      style.width = '20%';
    } else if (data.width) {
      style.width = data.width + (Object.is(data.widthmode, 'PERCENTAGE') ? '%' : 'px');
    } else {
      style.width = '20%';
    }
    return style;
  }

  /**
   * 获取高度
   *
   * @memberof
   */
   getHeightStyle(data: any) {
    let style: any = {}
    if (Object.is(data.heightmode, 'FULL')) {
      style.height = '20%';
    } else if (data.height) {
      style.height = data.height + (Object.is(data.heightmode, 'PERCENTAGE') ? '%' : 'px');
    } else {
      style.height = '20%';
    }
    return style;
  }

  /**
   * 子项渲染
   * @param {string} pos
   * @param {any} data
   */
  renderContentItem(pos: string, data: any) {
    return <design-scroll-container-item ctx={this.ctx} data={data} parentData={this.data} />
  }

  /**
   * 绘制布局容器功能按钮
   * @returns
   */
  renderScrollActions() {
    return (
      <div class='scroll-actions flex-container'>
        <div class={{ 'sccroll-action-item': true, 'ibiz-middle': true, active: this.left }} on-click={(e: MouseEvent) => this.onLayoutChange(e, 'CONTAINER_SCROLL_LEFT')}>
          <context-ion-icon icon='./assets/svg/layout-left-fill.svg' />
        </div>
        <div class={{ 'sccroll-action-item': true, 'ibiz-middle': true, active: this.top }} on-click={(e: MouseEvent) => this.onLayoutChange(e, 'CONTAINER_SCROLL_HEADER')}>
          <context-ion-icon icon='./assets/svg/layout-top-fill.svg' />
        </div>
        <div class={{ 'sccroll-action-item': true, 'ibiz-middle': true, active: this.bottom }} on-click={(e: MouseEvent) => this.onLayoutChange(e, 'CONTAINER_SCROLL_BOTTOM')}>
          <context-ion-icon icon='./assets/svg/layout-bottom-fill.svg' />
        </div>
        <div class={{ 'sccroll-action-item': true, 'ibiz-middle': true, active: this.right }} on-click={(e: MouseEvent) => this.onLayoutChange(e, 'CONTAINER_SCROLL_RIGHT')}>
          <context-ion-icon icon='./assets/svg/layout-right-fill.svg' />
        </div>
      </div>
    )
  }

  renderContent(): any {
    const { text, showcaption, showtitlebar, predefinedtype } = this.data;
    const contentStyle = this.getContentStyle(this.data);
    const hiddenHeader = showcaption == 0 || showtitlebar == 0;
    return (
      <div class={{ 'ibz-design-group': true, 'drag-item-container': true, active: this.active, 'ibz-design-group-border-hidden': this.ctx.state.hidden }}>
        <div class={{ 'render-scroll-container': true, active: this.active }} style={contentStyle}>
          <div class='scroll-container-title'>
            {hiddenHeader ? (
              <div class='drag-item-info' v-show={hiddenHeader && !this.ctx.state.hidden}>
                <div class='drag-item-info-text'>{this.active && Object.is(predefinedtype, 'CONTAINER_SCROLL') ? this.renderScrollActions() : text}</div>
              </div>
            ) : (
              <div class='header' v-show={!hiddenHeader}>
                <div class='title'>{text}</div>
                <div class='arrow'>
                  <a-icon type='caret-down' />
                </div>
              </div>
            )}
          </div>
          <div class='scroll-container-rawp'>
            {this.top ? <div class='scroll-container__top' style={this.getHeightStyle(this.top!)}>{this.renderContentItem('top', this.top!)}</div> : null}
            <div class='scroll-container-content flex-container'>
              {this.left ? (
                <div class='scroll-container__content_left' style={this.getWidthStyle(this.left!)}>
                  {this.renderContentItem('left', this.left!)}
                </div>
              ) : null}
              {this.main ? <div class='scroll-container__content_main'>{this.renderContentItem('main', this.main!)}</div> : null}
              {this.right ? (
                <div class='scroll-container__content_right' style={this.getWidthStyle(this.right!)}>
                  {this.renderContentItem('right', this.right!)}
                </div>
              ) : null}
            </div>
            {this.bottom ? <div class='scroll-container__bottom' style={this.getHeightStyle(this.bottom!)}>{this.renderContentItem('bottom', this.bottom!)}</div> : null}
          </div>
        </div>
      </div>
    );
  }
}
