/*
 * @Author: your name
 * @Date: 2022-04-11 17:19:22
 * @Description:
 * @FilePath: /zl-large-screen/src/components/LargeScreenSetting/index.tsx
 */

import React from 'react';
import LargeScreenTitle from '../LargeScreenTitle/index';
import LargeScreenSettingMain from './LargeScreenSettingMain/index';
import ControlBtn from '../Control-btn/index';
import LabelAlign from '../Unit/LabelAlign/index';
import Icon from '../Icon/index';
import LargeScreenLayerInput from '../LargeScreenLayer/LargeScreenLayerInput/index';
import Sortable from 'sortablejs';
import {
  ILargeScreenSettingProps,
  ILargeScreenSettingState
} from '../../type/LargeScreenSetting';
import { alignList } from '../../options/layout';
import { Dropdown, Menu, Popover } from 'antd';
import { gisChildLayer } from '../../options/layout';

class LargeScreenSetting extends React.Component<
  ILargeScreenSettingProps,
  ILargeScreenSettingState
> {
    constructor(props: ILargeScreenSettingProps) {
    super(props);

    this.state = {
      settingData: this.props.settingData,
      collapseDefaultActiveKey: this.props.collapseDefaultActiveKey,

      controlClass: '', //控制展开收起按钮样式
      wrapClass: '', //控制展开收起按钮样式
      iconType: 'icon-arrow-right-bold', ////控制展开收起按钮icon,

      scenes: this.props.scenes, // 场景列表,用于交互
      sceneSelectId: this.props.sceneSelectId, // 选中场景的页id
      cockpitList: this.props.cockpitList, // 驾驶舱列表
      GISChildren: this.props.GISChildren, //地图子组件
      gisChildLayerMenuList: [
        {
          key: 'shangyi',
          label: '上移一层',
          icon: <Icon name="custom-icon-shangyiyiceng" />
        },
        {
          key: 'xiayi',
          label: '下移一层',
          icon: <Icon name="custom-icon-xiayiyiceng" />
        },
        { key: 'del', label: '删除', icon: <Icon name="icon-shanchu" /> },
        {
          key: 'rename',
          label: '重命名',
          icon: <Icon name="icon-icon_zhongmingming" />
        }
      ],
      isCurrentInput: -1,
      isVisible: false, //开关
      sortableRef: null,
      dragRef: false
    };
  }
  
  componentDidUpdate(prevProps, prevState) {
    if (this.props.settingData !== prevProps.settingData) {
      this.setState({ settingData: this.props.settingData });
    }
    if (
      this.props.collapseDefaultActiveKey !== prevProps.collapseDefaultActiveKey
    ) {
      this.setState({
        collapseDefaultActiveKey: this.props.collapseDefaultActiveKey
      });
    }

    if (this.props.scenes !== prevProps.scenes) {
      this.setState({ scenes: this.props.scenes });
    }

    if (this.props.cockpitList !== prevProps.cockpitList) {
      this.setState({ cockpitList: this.props.cockpitList });
    }
    if (this.props.GISChildren !== prevState.GISChildren) {
      if (this.props.GISChildren?.length > 0 && this.refs.mapListRef) {
        this.state.sortableRef && this.state.sortableRef.destroy();
        this.initSort();
      }
      this.setState({ GISChildren: this.props.GISChildren });
    }

    document.addEventListener('mousedown', this.mousedown);
  }

  mousedown = (e) => {
    if (
      !(
        this.elementContains(
          document.querySelector('.zl-lagre-screen-add-gis-child-popover'),
          e.target
        ) ||
        this.elementContains(
          document.querySelector('.zl-large-screen-setting'),
          e.target
        )
      )
    ) {
      this.setState({ isVisible: false });
    }
  };

  // 判断父元素是否包含某个元素
  elementContains = (parent, child) =>
    parent !== child && parent?.contains(child);
  //展开收起的样式
  controlBtnClick = () => {
    if (this.state.wrapClass) {
      this.setState({
        wrapClass: '',
        controlClass: '',
        iconType: 'icon-arrow-right-bold'
      });
    } else {
      this.setState({
        wrapClass: 'zl-component-com-siler-close',
        controlClass: 'zl-right-control-up',
        iconType: 'icon-arrow-left-bold'
      });
    }
    this.props?.clickControlBtn('setting');
  };

  zoomMenu = (item, index) => {
    let menu = [...this.state.gisChildLayerMenuList];
    return (
      <Menu
        selectable
        items={menu}
        onClick={({ key, domEvent }) => {
          domEvent.preventDefault();
          domEvent.stopPropagation();
          if (key === 'rename') {
            this.setState({ isCurrentInput: index });
          }
          this.props?.changeSettingData({
            type: 'gis_menu',
            value: {
              key: key,
              item: item
            }
          });
        }}
      />
    );
  };

  content = (
    <div className="zl-lagre-screen-add-gis-child-popover">
      <p className="zl-lagre-screen-add-gis-child-popover-title">
        <span>点击添加子组件</span>
        <Icon
          name="icon-guanbi1"
          click={() => {
            this.setState({ isVisible: false });
          }}
        />
      </p>
      <div className="zl-lagre-screen-add-gis-child-popover-content">
        {gisChildLayer?.length > 0 &&
          gisChildLayer.map((item) => {
            return (
              <div
                key={item?.key}
                className="zl-lagre-screen-add-gis-child-popover-content-div"
                onClick={() => {
                  this.setState({ isVisible: false });
                  this.props?.changeSettingData({
                    type: 'gis_add',
                    value: {
                      key: item?.key,
                      item: item
                    }
                  });
                }}
              >
                <img src={item?.img} alt={item?.title} />
                <span>{item?.title}</span>
              </div>
            );
          })}
      </div>
    </div>
  );

  // 初始化sortable
  initSort = () => {
    let _this = this;
    let sortable;
    // 拖动配置
    const ops = {
      animation: 200, // 动画延迟
      group: 'name-map',
      sort: true,
      scroll: true,
      className: 'zl-lagre-screen-filter-end-map',
      selectedClass: 'sortable-selected-map', // 选择的类名
      ghostClass: 'sortable-ghostClass-map', // 选择的类名
      forceFallback: true,
      fallbackTolerance: 3,
      // selected: true,

      avoidImplicitDeselect: false, // true - if you don't want to deselect items on outside click
      onStart: function (evt) {
        _this.setState({ dragRef: true });
        _this.props?.changeSettingData({
          type: 'gis_clearFrist',
          value: ''
        });
      },
      onMove: function (evt) {},
      onEnd: function (evt) {
        _this.setState({
          dragRef: false
        });
      },
      // 更新
      onUpdate: function (/**Event*/ evt) {
        const { from, newIndex } = evt;
        const list = _this.updateSort(from);
        _this.props?.changeSettingData({
          type: 'gis_update',
          value: list
        });
      }
    };
    //初始化
    sortable = Sortable.create(this.refs.mapListRef, ops);
    _this.setState({
      sortableRef: sortable
    });
  };

  // 更新排序
  updateSort = (fromEle) => {
    const list = [];
    [...fromEle?.children]?.forEach((item) => {
      const layerId = item?.getAttribute('data-map-layerId');
      if (layerId) {
        list.push(layerId);
      }
    });
    return list;
  };

  render() {
    const {
      settingData,
      collapseDefaultActiveKey,
      controlClass,
      iconType,
      wrapClass,
      scenes,
      sceneSelectId,
      cockpitList
    } = this.state;

    return (
      <div className="zl-large-screen-setting">
        <ControlBtn
          style={{
            left: -21,
            borderRadius: '4px 0 0 4px',
            boxShadow: ' 0 4px 9px 0 rgb(0 0 0 / 8%)'
          }}
          click={this.controlBtnClick}
          className={controlClass}
          iconType={iconType}
        />
        <div className={`zl-large-screen-setting-wraps ${wrapClass}`}>
          <div
            style={
              settingData?.title !== '页面' &&
              settingData?.title !== '场景' &&
              !settingData?.hiddenAlign
                ? { flex: 1 }
                : {}
            }
          >
            <LargeScreenTitle
              clickBack={() =>
                this.props?.changeSettingData({ type: 'clickBack' })
              }
              title={settingData?.title}
              titleType={
                settingData?.titleType ? settingData?.titleType : 'title'
              }
              tabsList={settingData?.tabsList ? settingData?.tabsList : []}
              tabsEvent={(value) =>
                this.props?.changeSettingData({
                  type: 'titleTabs',
                  value: value
                })
              }
              activeTab={settingData?.activeTab ? settingData?.activeTab : ''}
              isClick={settingData.isClick}
            />
            {!settingData?.hiddenAlign &&
            ((settingData?.title !== '页面' && settingData?.title !== '场景') ||
              (settingData?.tabsList && settingData?.tabsList?.length > 0)) ? (
              <LabelAlign
                wrapStyle={{
                  height: 40,
                  padding: '0 20px',
                  borderBottom:
                    this.props.theme === 'white' ? '1px solid #e7e7e7' : 'none'
                }}
                alignList={alignList}
                change={(value) => {
                  this.props?.changeSettingData({
                    type: 'elementAlign',
                    value: value
                  });
                }}
              />
            ) : (
              <></>
            )}

            {settingData?.title === '自定义地图' &&
            (!settingData?.tabsList || settingData?.tabsList?.length === 0) ? (
              <>
                <div className="setting-map-childre-title">
                  <span>GIS图层</span>
                  <Popover
                    align={{ offset: [-12, 0] }}
                    placement="bottomLeft"
                    content={this.content}
                    trigger="click"
                    visible={this.state.isVisible}
                    overlayClassName="zl-lagre-screen-add-gis-child-popover-wrap"
                  >
                    <span>
                      <Icon
                        style={{ width: 20, height: 20 }}
                        name="icon-jia"
                        click={() => {
                          this.setState({ isVisible: true });
                        }}
                      />
                    </span>
                  </Popover>
                </div>
                <div
                  ref="mapListRef"
                  className="setting-map-chidren-wrap"
                  style={{ minHeight: 'calc(100% - 130px)' }}
                >
                  {this.state?.GISChildren &&
                    this.state.GISChildren?.length > 0 &&
                    this.state.GISChildren.map((item, index) => {
                      return (
                        <div data-map-layerId={item?.key} key={item?.key}>
                          <Dropdown
                            trigger={['contextMenu']}
                            overlay={this.zoomMenu(item, index)}
                            overlayClassName="zl-lagre-screen-gis-list-menu-dropdown"
                          >
                            <p
                              className="map-children"
                              key={item?.key}
                              onClick={() => {
                                if (index !== this.state.isCurrentInput) {
                                  this.props?.changeSettingData({
                                    type: 'gis_click',
                                    value: {
                                      key: item?.key,
                                      item: item
                                    }
                                  });
                                }
                              }}
                            >
                              <Icon name={item?.icon} />
                              {index === this.state.isCurrentInput ? (
                                <LargeScreenLayerInput
                                  value={item?.title}
                                  changeValue={(type, value) => {
                                    if (type === 'blur') {
                                      this.props?.changeSettingData({
                                        type: 'gis_input',
                                        value: {
                                          key: value,
                                          item: item
                                        }
                                      });
                                      this.setState({ isCurrentInput: -1 });
                                    }
                                  }}
                                />
                              ) : (
                                <span
                                  className="map-chilren-title"
                                  title={item?.title}
                                >
                                  {item?.title}
                                </span>
                              )}

                              {item?.isHide ? (
                                <Icon
                                  name="icon-yanjingyincangguanbi"
                                  click={(name, e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    this.props?.changeSettingData({
                                      type: 'gis_hide',
                                      value: {
                                        key: 'show',
                                        item: item
                                      }
                                    });
                                  }}
                                />
                              ) : (
                                <Icon
                                  name="icon-yanjingxianshi"
                                  click={(name, e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    this.props?.changeSettingData({
                                      type: 'gis_hide',
                                      value: {
                                        key: 'hid',
                                        item: item
                                      }
                                    });
                                  }}
                                />
                              )}
                              <Dropdown
                                trigger={['click']}
                                overlay={this.zoomMenu(item, index)}
                                overlayClassName="zl-lagre-screen-gis-list-menu-dropdown"
                              >
                                <span
                                  className="map-chilren-more"
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                  }}
                                >
                                  <Icon name="icon-a-icon__shezhisangedian" />
                                </span>
                              </Dropdown>
                            </p>
                          </Dropdown>
                        </div>
                      );
                    })}
                </div>
              </>
            ) : (
              <></>
            )}
          </div>

          <LargeScreenSettingMain
            settingData={settingData}
            settingList={settingData?.list}
            changeSettingData={this.props.changeSettingData}
            changeCollapse={this.props.changeCollapse}
            collapseDefaultActiveKey={collapseDefaultActiveKey}
            theme={this.props.theme}
            scenes={scenes}
            sceneSelectId={sceneSelectId}
            cockpitList={cockpitList}
          />
        </div>
      </div>
    );
  }
}

export default LargeScreenSetting;
