import { Transition, defineComponent, onMounted, ref } from 'vue';
import LayoutSilder from './layoutSilder';
import LayoutTop from './layoutTop';
import styles from './index.module.less';
import { NImage, NModal, NPopover } from 'naive-ui';
import Moveable from 'moveable';
import toolStartClass from './images/toolStartClass.png';
import toolbox from './images/toolbox.png';
import setTimeIcon from './images/setTimeIcon.png';
import beatIcon from './images/beatIcon.png';
import toneIcon from './images/toneIcon.png';
import beatImage from './images/beatImage.png';
import toneImage from './images/toneImage.png';
import setTimeImage from './images/setTimeImage.png';
import dragingBoxIcon from './images/dragingBoxIcon.png';
import TimerMeter from '../timerMeter';
import { useRoute } from 'vue-router';
import { vaildUrl } from '/src/utils/urlUtils';
import ChioseModal from '/src/views/home/modals/chioseModal';
export default defineComponent({
  name: 'layoutView',
  setup() {
    const directionType = ref('left');
    const showClass = ref(false);
    const showModalBeat = ref(false);
    const showModalTone = ref(false);
    const showModalTime = ref(false);
    const route = useRoute();
    const isDragIng = ref(false);
    const initMoveable = async () => {
      if (document.querySelector('.wrap')) {
        const moveable = new Moveable(document.querySelector('.wrap') as any, {
          target: document.querySelector('#moveNPopover') as any,
          // If the container is null, the position is fixed. (default: parentElement(document.body))
          container: document.querySelector('.wrap') as any,
          // snappable: true,
          // bounds: {"left":100,"top":100,"right":100,"bottom":100},
          draggable: true,
          resizable: false,
          scalable: false,
          rotatable: false,
          warpable: false,
          pinchable: false, // ["resizable", "scalable", "rotatable"]
          origin: false,
          keepRatio: false,
          // Resize, Scale Events at edges.
          edge: false,
          throttleDrag: 0,
          throttleResize: 0,
          throttleScale: 0,
          throttleRotate: 0
        });
        moveable
          // .on('dragStart', ({ target, clientX, clientY }) => {
          //   console.log('dragStart');
          // })
          .on(
            'drag',
            ({
              target,
              // transform,
              left,
              top,
              right,
              bottom
              // beforeDelta,
              // beforeDist,
              // delta,
              // dist,
              // clientX,
              // clientY
            }) => {
              isDragIng.value = true;
              const subdEl = document.getElementById(
                `moveNPopover`
              ) as HTMLDivElement;
              // console.log(subdEl, "subdEl", "drag");
              const subdElStyle = getComputedStyle(subdEl, null);
              const RectInfo = {
                left: Number(subdElStyle.left.replace('px', '')),
                top: Number(subdElStyle.top.replace('px', '')),
                width: Number(subdElStyle.width.replace('px', '')),
                height: Number(subdElStyle.height.replace('px', ''))
              };

              const mainWidth =
                parseInt(
                  window.getComputedStyle(
                    document.querySelector('.wrap') as Element
                  ).width
                ) - RectInfo.width;

              const mainHeight =
                parseInt(
                  window.getComputedStyle(
                    document.querySelector('.wrap') as Element
                  ).height
                ) - RectInfo.height;

              if (left < 0) {
                left = 2;
              }
              if (top < 0) {
                top = 2;
              }
              if (right < 0) {
                right = 2;
              }
              if (bottom < 0) {
                bottom = 2;
              }
              if (left > mainWidth - 2) {
                left = mainWidth - 2;
              }
              if (top > mainHeight - 2) {
                top = mainHeight - 2;
              }

              target!.style.left = `${left}px`;
              target!.style.top = `${top}px`;
            }
          )
          .on(
            'dragEnd',
            async ({
              // target, isDrag,
              clientX
              // clientY
            }) => {
              if (document.body.clientWidth / 2 - clientX > 0) {
                // 往左出
                directionType.value = 'right';
              } else {
                // 往又出
                directionType.value = 'left';
              }
              isDragIng.value = false;
            }
          );
      }
    };
    const initMoveableClass = async () => {
      if (document.querySelector('.wrap')) {
        const moveable = new Moveable(document.querySelector('.wrap') as any, {
          target: document.querySelector('#moveNPopover2') as any,
          // If the container is null, the position is fixed. (default: parentElement(document.body))
          container: document.querySelector('.wrap') as any,
          // snappable: true,
          // bounds: {"left":100,"top":100,"right":100,"bottom":100},
          draggable: true,
          resizable: false,
          scalable: false,
          rotatable: false,
          warpable: false,
          pinchable: false, // ["resizable", "scalable", "rotatable"]
          origin: false,
          keepRatio: false,
          // Resize, Scale Events at edges.
          edge: false,
          throttleDrag: 0,
          throttleResize: 0,
          throttleScale: 0,
          throttleRotate: 0
        });
        moveable
          .on(
            'drag',
            ({
              target,
              // transform,
              left,
              top,
              right,
              bottom
            }) => {
              isDragIng.value = true;
              const subdEl = document.getElementById(
                `moveNPopover2`
              ) as HTMLDivElement;
              // console.log(subdEl, "subdEl", "drag");
              const subdElStyle = getComputedStyle(subdEl, null);
              const RectInfo = {
                left: Number(subdElStyle.left.replace('px', '')),
                top: Number(subdElStyle.top.replace('px', '')),
                width: Number(subdElStyle.width.replace('px', '')),
                height: Number(subdElStyle.height.replace('px', ''))
              };

              const mainWidth =
                parseInt(
                  window.getComputedStyle(
                    document.querySelector('.wrap') as Element
                  ).width
                ) - RectInfo.width;

              const mainHeight =
                parseInt(
                  window.getComputedStyle(
                    document.querySelector('.wrap') as Element
                  ).height
                ) - RectInfo.height;

              if (left < 0) {
                left = 2;
              }
              if (top < 0) {
                top = 2;
              }
              if (right < 0) {
                right = 2;
              }
              if (bottom < 0) {
                bottom = 2;
              }
              if (left > mainWidth - 2) {
                left = mainWidth - 2;
              }
              if (top > mainHeight - 2) {
                top = mainHeight - 2;
              }

              target!.style.left = `${left}px`;
              target!.style.top = `${top}px`;
            }
          )
          .on(
            'dragEnd',
            async ({
              // target, isDrag,
              clientX
              // clientY
            }) => {
              if (document.body.clientWidth / 2 - clientX > 0) {
                // 往左出
                directionType.value = 'right';
              } else {
                // 往又出
                directionType.value = 'left';
              }
              isDragIng.value = false;
            }
          )
          .on('click', () => {
            console.log(true, '1212');
            showClass.value = true;
          });
      }
    };
    onMounted(() => {
      initMoveable();
      initMoveableClass();
    });
    const startShowModal = (val: 'setTimeIcon' | 'beatIcon' | 'toneIcon') => {
      if (val == 'setTimeIcon') {
        showModalTime.value = true;
      }
      if (val == 'beatIcon') {
        showModalBeat.value = true;
      }
      if (val == 'toneIcon') {
        showModalTone.value = true;
      }
    };
    return () => (
      <div class={[styles.wrap, 'wrap']}>
        <div>
          <LayoutSilder></LayoutSilder>
        </div>
        <div class={styles.Wrapcore}>
          <LayoutTop></LayoutTop>
          <div class={styles.WrapcoreView}>
            {/* <div class={styles.WrapcoreViewInfo}> */}
            <router-view>
              {(obj: any) => (
                <Transition name="fade-slide" mode="out-in">
                  <obj.Component />
                </Transition>
              )}
            </router-view>
            {/* </div> */}
          </div>
        </div>
        <img
          src={toolStartClass}
          id="moveNPopover2"
          style={{
            display: ['/', '/home', '/classList', '/prepare-lessons'].includes(
              route.path
            )
              ? 'none'
              : 'block'
          }}
          class={[
            styles.toolClassImg,
            'moveNPopover2',
            isDragIng.value ? styles.isDragIng : ''
          ]}
          alt=""
        />
        <NPopover
          raw
          trigger="click"
          show-arrow={false}
          placement={directionType.value as 'left' | 'right'}
          v-slots={{
            trigger: () => (
              // 首页不显示工具箱
              <img
                // src={isDragIng.value ? dragingBoxIcon : toolbox}
                src={toolbox}
                id="moveNPopover"
                style={{
                  display: ['/', '/home'].includes(route.path)
                    ? 'none'
                    : 'block'
                }}
                class={[
                  styles.toolboxImg,
                  'moveNPopover',
                  isDragIng.value ? styles.isDragIng : ''
                ]}
                alt=""
              />
            )
          }}>
          <div class={styles.booxToolWrap}>
            <div
              class={styles.booxToolItem}
              onClick={() => startShowModal('beatIcon')}>
              <img src={beatIcon} alt="" />
              节拍器
            </div>
            <div
              class={styles.booxToolItem}
              onClick={() => startShowModal('toneIcon')}>
              <img src={toneIcon} alt="" />
              调音器
            </div>
            <div
              class={styles.booxToolItem}
              onClick={() => startShowModal('setTimeIcon')}>
              <img src={setTimeIcon} alt="" />
              计时器
            </div>
          </div>
        </NPopover>

        <NModal
          class={['modalTitle background']}
          title={'节拍器'}
          preset="card"
          v-model:show={showModalBeat.value}
          style={{ width: '687px' }}>
          <div class={styles.modeWrap}>
            <iframe
              src={`${vaildUrl()}/metronome/?id=${new Date().getTime()}`}
              scrolling="no"
              frameborder="0"
              width="100%"
              height={'650px'}></iframe>
          </div>
        </NModal>
        <NModal v-model:show={showModalTone.value}>
          <div
            onClick={() => {
              showModalTone.value = false;
            }}>
            <NImage
              src={toneImage}
              previewDisabled
              class={styles.beatImage}></NImage>
          </div>
        </NModal>
        <NModal
          v-model:show={showModalTime.value}
          class={['modalTitle background']}
          title={'计时器'}
          preset="card"
          style={{ width: '772px' }}>
          <div>
            <TimerMeter></TimerMeter>
          </div>
        </NModal>

        <NModal
          v-model:show={showClass.value}
          class={['modalTitle background', styles.showClass]}
          preset="card"
          title={'开始上课'}>
          <ChioseModal onClose={() => (showClass.value = false)} />
        </NModal>
      </div>
    );
  }
});
